PackageManagerService.java revision 8cd28b57ed732656d002d97879e15c5695b54fff
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_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Set;
205import java.util.concurrent.atomic.AtomicBoolean;
206import java.util.concurrent.atomic.AtomicLong;
207
208import dalvik.system.DexFile;
209import dalvik.system.StaleDexCacheError;
210import dalvik.system.VMRuntime;
211
212import libcore.io.IoUtils;
213import libcore.util.EmptyArray;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
252    // Suffix used during package installation when copying/moving
253    // package apks to install directory.
254    private static final String INSTALL_PACKAGE_SUFFIX = "-";
255
256    static final int SCAN_NO_DEX = 1<<1;
257    static final int SCAN_FORCE_DEX = 1<<2;
258    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
259    static final int SCAN_NEW_INSTALL = 1<<4;
260    static final int SCAN_NO_PATHS = 1<<5;
261    static final int SCAN_UPDATE_TIME = 1<<6;
262    static final int SCAN_DEFER_DEX = 1<<7;
263    static final int SCAN_BOOTING = 1<<8;
264    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
265    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
266    static final int SCAN_REPLACING = 1<<11;
267
268    static final int REMOVE_CHATTY = 1<<16;
269
270    /**
271     * Timeout (in milliseconds) after which the watchdog should declare that
272     * our handler thread is wedged.  The usual default for such things is one
273     * minute but we sometimes do very lengthy I/O operations on this thread,
274     * such as installing multi-gigabyte applications, so ours needs to be longer.
275     */
276    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
277
278    /**
279     * Whether verification is enabled by default.
280     */
281    private static final boolean DEFAULT_VERIFY_ENABLE = true;
282
283    /**
284     * The default maximum time to wait for the verification agent to return in
285     * milliseconds.
286     */
287    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
288
289    /**
290     * The default response for package verification timeout.
291     *
292     * This can be either PackageManager.VERIFICATION_ALLOW or
293     * PackageManager.VERIFICATION_REJECT.
294     */
295    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
296
297    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
298
299    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
300            DEFAULT_CONTAINER_PACKAGE,
301            "com.android.defcontainer.DefaultContainerService");
302
303    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
304
305    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
306
307    private static String sPreferredInstructionSet;
308
309    final ServiceThread mHandlerThread;
310
311    private static final String IDMAP_PREFIX = "/data/resource-cache/";
312    private static final String IDMAP_SUFFIX = "@idmap";
313
314    final PackageHandler mHandler;
315
316    /**
317     * Messages for {@link #mHandler} that need to wait for system ready before
318     * being dispatched.
319     */
320    private ArrayList<Message> mPostSystemReadyMessages;
321
322    final int mSdkVersion = Build.VERSION.SDK_INT;
323
324    final Context mContext;
325    final boolean mFactoryTest;
326    final boolean mOnlyCore;
327    final boolean mLazyDexOpt;
328    final DisplayMetrics mMetrics;
329    final int mDefParseFlags;
330    final String[] mSeparateProcesses;
331
332    // This is where all application persistent data goes.
333    final File mAppDataDir;
334
335    // This is where all application persistent data goes for secondary users.
336    final File mUserAppDataDir;
337
338    /** The location for ASEC container files on internal storage. */
339    final String mAsecInternalPath;
340
341    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
342    // LOCK HELD.  Can be called with mInstallLock held.
343    final Installer mInstaller;
344
345    /** Directory where installed third-party apps stored */
346    final File mAppInstallDir;
347
348    /**
349     * Directory to which applications installed internally have their
350     * 32 bit native libraries copied.
351     */
352    private File mAppLib32InstallDir;
353
354    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
355    // apps.
356    final File mDrmAppPrivateInstallDir;
357
358    // ----------------------------------------------------------------
359
360    // Lock for state used when installing and doing other long running
361    // operations.  Methods that must be called with this lock held have
362    // the suffix "LI".
363    final Object mInstallLock = new Object();
364
365    // ----------------------------------------------------------------
366
367    // Keys are String (package name), values are Package.  This also serves
368    // as the lock for the global state.  Methods that must be called with
369    // this lock held have the prefix "LP".
370    final HashMap<String, PackageParser.Package> mPackages =
371            new HashMap<String, PackageParser.Package>();
372
373    // Tracks available target package names -> overlay package paths.
374    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
375        new HashMap<String, HashMap<String, PackageParser.Package>>();
376
377    final Settings mSettings;
378    boolean mRestoredSettings;
379
380    // System configuration read by SystemConfig.
381    final int[] mGlobalGids;
382    final SparseArray<HashSet<String>> mSystemPermissions;
383    final HashMap<String, FeatureInfo> mAvailableFeatures;
384
385    // If mac_permissions.xml was found for seinfo labeling.
386    boolean mFoundPolicyFile;
387
388    // If a recursive restorecon of /data/data/<pkg> is needed.
389    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
390
391    public static final class SharedLibraryEntry {
392        public final String path;
393        public final String apk;
394
395        SharedLibraryEntry(String _path, String _apk) {
396            path = _path;
397            apk = _apk;
398        }
399    }
400
401    // Currently known shared libraries.
402    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
403            new HashMap<String, SharedLibraryEntry>();
404
405    // All available activities, for your resolving pleasure.
406    final ActivityIntentResolver mActivities =
407            new ActivityIntentResolver();
408
409    // All available receivers, for your resolving pleasure.
410    final ActivityIntentResolver mReceivers =
411            new ActivityIntentResolver();
412
413    // All available services, for your resolving pleasure.
414    final ServiceIntentResolver mServices = new ServiceIntentResolver();
415
416    // All available providers, for your resolving pleasure.
417    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
418
419    // Mapping from provider base names (first directory in content URI codePath)
420    // to the provider information.
421    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
422            new HashMap<String, PackageParser.Provider>();
423
424    // Mapping from instrumentation class names to info about them.
425    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
426            new HashMap<ComponentName, PackageParser.Instrumentation>();
427
428    // Mapping from permission names to info about them.
429    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
430            new HashMap<String, PackageParser.PermissionGroup>();
431
432    // Packages whose data we have transfered into another package, thus
433    // should no longer exist.
434    final HashSet<String> mTransferedPackages = new HashSet<String>();
435
436    // Broadcast actions that are only available to the system.
437    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
438
439    /** List of packages waiting for verification. */
440    final SparseArray<PackageVerificationState> mPendingVerification
441            = new SparseArray<PackageVerificationState>();
442
443    /** Set of packages associated with each app op permission. */
444    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
445
446    final PackageInstallerService mInstallerService;
447
448    HashSet<PackageParser.Package> mDeferredDexOpt = null;
449
450    // Cache of users who need badging.
451    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
452
453    /** Token for keys in mPendingVerification. */
454    private int mPendingVerificationToken = 0;
455
456    volatile boolean mSystemReady;
457    volatile boolean mSafeMode;
458    volatile boolean mHasSystemUidErrors;
459
460    ApplicationInfo mAndroidApplication;
461    final ActivityInfo mResolveActivity = new ActivityInfo();
462    final ResolveInfo mResolveInfo = new ResolveInfo();
463    ComponentName mResolveComponentName;
464    PackageParser.Package mPlatformPackage;
465    ComponentName mCustomResolverComponentName;
466
467    boolean mResolverReplaced = false;
468
469    // Set of pending broadcasts for aggregating enable/disable of components.
470    static class PendingPackageBroadcasts {
471        // for each user id, a map of <package name -> components within that package>
472        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
473
474        public PendingPackageBroadcasts() {
475            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
476        }
477
478        public ArrayList<String> get(int userId, String packageName) {
479            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
480            return packages.get(packageName);
481        }
482
483        public void put(int userId, String packageName, ArrayList<String> components) {
484            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
485            packages.put(packageName, components);
486        }
487
488        public void remove(int userId, String packageName) {
489            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
490            if (packages != null) {
491                packages.remove(packageName);
492            }
493        }
494
495        public void remove(int userId) {
496            mUidMap.remove(userId);
497        }
498
499        public int userIdCount() {
500            return mUidMap.size();
501        }
502
503        public int userIdAt(int n) {
504            return mUidMap.keyAt(n);
505        }
506
507        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
508            return mUidMap.get(userId);
509        }
510
511        public int size() {
512            // total number of pending broadcast entries across all userIds
513            int num = 0;
514            for (int i = 0; i< mUidMap.size(); i++) {
515                num += mUidMap.valueAt(i).size();
516            }
517            return num;
518        }
519
520        public void clear() {
521            mUidMap.clear();
522        }
523
524        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
525            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
526            if (map == null) {
527                map = new HashMap<String, ArrayList<String>>();
528                mUidMap.put(userId, map);
529            }
530            return map;
531        }
532    }
533    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
534
535    // Service Connection to remote media container service to copy
536    // package uri's from external media onto secure containers
537    // or internal storage.
538    private IMediaContainerService mContainerService = null;
539
540    static final int SEND_PENDING_BROADCAST = 1;
541    static final int MCS_BOUND = 3;
542    static final int END_COPY = 4;
543    static final int INIT_COPY = 5;
544    static final int MCS_UNBIND = 6;
545    static final int START_CLEANING_PACKAGE = 7;
546    static final int FIND_INSTALL_LOC = 8;
547    static final int POST_INSTALL = 9;
548    static final int MCS_RECONNECT = 10;
549    static final int MCS_GIVE_UP = 11;
550    static final int UPDATED_MEDIA_STATUS = 12;
551    static final int WRITE_SETTINGS = 13;
552    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
553    static final int PACKAGE_VERIFIED = 15;
554    static final int CHECK_PENDING_VERIFICATION = 16;
555
556    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
557
558    // Delay time in millisecs
559    static final int BROADCAST_DELAY = 10 * 1000;
560
561    static UserManagerService sUserManager;
562
563    // Stores a list of users whose package restrictions file needs to be updated
564    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
565
566    final private DefaultContainerConnection mDefContainerConn =
567            new DefaultContainerConnection();
568    class DefaultContainerConnection implements ServiceConnection {
569        public void onServiceConnected(ComponentName name, IBinder service) {
570            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
571            IMediaContainerService imcs =
572                IMediaContainerService.Stub.asInterface(service);
573            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
574        }
575
576        public void onServiceDisconnected(ComponentName name) {
577            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
578        }
579    };
580
581    // Recordkeeping of restore-after-install operations that are currently in flight
582    // between the Package Manager and the Backup Manager
583    class PostInstallData {
584        public InstallArgs args;
585        public PackageInstalledInfo res;
586
587        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
588            args = _a;
589            res = _r;
590        }
591    };
592    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
593    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
594
595    private final String mRequiredVerifierPackage;
596
597    private final PackageUsage mPackageUsage = new PackageUsage();
598
599    private class PackageUsage {
600        private static final int WRITE_INTERVAL
601            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
602
603        private final Object mFileLock = new Object();
604        private final AtomicLong mLastWritten = new AtomicLong(0);
605        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
606
607        private boolean mIsHistoricalPackageUsageAvailable = true;
608
609        boolean isHistoricalPackageUsageAvailable() {
610            return mIsHistoricalPackageUsageAvailable;
611        }
612
613        void write(boolean force) {
614            if (force) {
615                writeInternal();
616                return;
617            }
618            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
619                && !DEBUG_DEXOPT) {
620                return;
621            }
622            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
623                new Thread("PackageUsage_DiskWriter") {
624                    @Override
625                    public void run() {
626                        try {
627                            writeInternal();
628                        } finally {
629                            mBackgroundWriteRunning.set(false);
630                        }
631                    }
632                }.start();
633            }
634        }
635
636        private void writeInternal() {
637            synchronized (mPackages) {
638                synchronized (mFileLock) {
639                    AtomicFile file = getFile();
640                    FileOutputStream f = null;
641                    try {
642                        f = file.startWrite();
643                        BufferedOutputStream out = new BufferedOutputStream(f);
644                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
645                        StringBuilder sb = new StringBuilder();
646                        for (PackageParser.Package pkg : mPackages.values()) {
647                            if (pkg.mLastPackageUsageTimeInMills == 0) {
648                                continue;
649                            }
650                            sb.setLength(0);
651                            sb.append(pkg.packageName);
652                            sb.append(' ');
653                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
654                            sb.append('\n');
655                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
656                        }
657                        out.flush();
658                        file.finishWrite(f);
659                    } catch (IOException e) {
660                        if (f != null) {
661                            file.failWrite(f);
662                        }
663                        Log.e(TAG, "Failed to write package usage times", e);
664                    }
665                }
666            }
667            mLastWritten.set(SystemClock.elapsedRealtime());
668        }
669
670        void readLP() {
671            synchronized (mFileLock) {
672                AtomicFile file = getFile();
673                BufferedInputStream in = null;
674                try {
675                    in = new BufferedInputStream(file.openRead());
676                    StringBuffer sb = new StringBuffer();
677                    while (true) {
678                        String packageName = readToken(in, sb, ' ');
679                        if (packageName == null) {
680                            break;
681                        }
682                        String timeInMillisString = readToken(in, sb, '\n');
683                        if (timeInMillisString == null) {
684                            throw new IOException("Failed to find last usage time for package "
685                                                  + packageName);
686                        }
687                        PackageParser.Package pkg = mPackages.get(packageName);
688                        if (pkg == null) {
689                            continue;
690                        }
691                        long timeInMillis;
692                        try {
693                            timeInMillis = Long.parseLong(timeInMillisString.toString());
694                        } catch (NumberFormatException e) {
695                            throw new IOException("Failed to parse " + timeInMillisString
696                                                  + " as a long.", e);
697                        }
698                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
699                    }
700                } catch (FileNotFoundException expected) {
701                    mIsHistoricalPackageUsageAvailable = false;
702                } catch (IOException e) {
703                    Log.w(TAG, "Failed to read package usage times", e);
704                } finally {
705                    IoUtils.closeQuietly(in);
706                }
707            }
708            mLastWritten.set(SystemClock.elapsedRealtime());
709        }
710
711        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
712                throws IOException {
713            sb.setLength(0);
714            while (true) {
715                int ch = in.read();
716                if (ch == -1) {
717                    if (sb.length() == 0) {
718                        return null;
719                    }
720                    throw new IOException("Unexpected EOF");
721                }
722                if (ch == endOfToken) {
723                    return sb.toString();
724                }
725                sb.append((char)ch);
726            }
727        }
728
729        private AtomicFile getFile() {
730            File dataDir = Environment.getDataDirectory();
731            File systemDir = new File(dataDir, "system");
732            File fname = new File(systemDir, "package-usage.list");
733            return new AtomicFile(fname);
734        }
735    }
736
737    class PackageHandler extends Handler {
738        private boolean mBound = false;
739        final ArrayList<HandlerParams> mPendingInstalls =
740            new ArrayList<HandlerParams>();
741
742        private boolean connectToService() {
743            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
744                    " DefaultContainerService");
745            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
746            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
747            if (mContext.bindServiceAsUser(service, mDefContainerConn,
748                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
749                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
750                mBound = true;
751                return true;
752            }
753            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754            return false;
755        }
756
757        private void disconnectService() {
758            mContainerService = null;
759            mBound = false;
760            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
761            mContext.unbindService(mDefContainerConn);
762            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
763        }
764
765        PackageHandler(Looper looper) {
766            super(looper);
767        }
768
769        public void handleMessage(Message msg) {
770            try {
771                doHandleMessage(msg);
772            } finally {
773                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
774            }
775        }
776
777        void doHandleMessage(Message msg) {
778            switch (msg.what) {
779                case INIT_COPY: {
780                    HandlerParams params = (HandlerParams) msg.obj;
781                    int idx = mPendingInstalls.size();
782                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
783                    // If a bind was already initiated we dont really
784                    // need to do anything. The pending install
785                    // will be processed later on.
786                    if (!mBound) {
787                        // If this is the only one pending we might
788                        // have to bind to the service again.
789                        if (!connectToService()) {
790                            Slog.e(TAG, "Failed to bind to media container service");
791                            params.serviceError();
792                            return;
793                        } else {
794                            // Once we bind to the service, the first
795                            // pending request will be processed.
796                            mPendingInstalls.add(idx, params);
797                        }
798                    } else {
799                        mPendingInstalls.add(idx, params);
800                        // Already bound to the service. Just make
801                        // sure we trigger off processing the first request.
802                        if (idx == 0) {
803                            mHandler.sendEmptyMessage(MCS_BOUND);
804                        }
805                    }
806                    break;
807                }
808                case MCS_BOUND: {
809                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
810                    if (msg.obj != null) {
811                        mContainerService = (IMediaContainerService) msg.obj;
812                    }
813                    if (mContainerService == null) {
814                        // Something seriously wrong. Bail out
815                        Slog.e(TAG, "Cannot bind to media container service");
816                        for (HandlerParams params : mPendingInstalls) {
817                            // Indicate service bind error
818                            params.serviceError();
819                        }
820                        mPendingInstalls.clear();
821                    } else if (mPendingInstalls.size() > 0) {
822                        HandlerParams params = mPendingInstalls.get(0);
823                        if (params != null) {
824                            if (params.startCopy()) {
825                                // We are done...  look for more work or to
826                                // go idle.
827                                if (DEBUG_SD_INSTALL) Log.i(TAG,
828                                        "Checking for more work or unbind...");
829                                // Delete pending install
830                                if (mPendingInstalls.size() > 0) {
831                                    mPendingInstalls.remove(0);
832                                }
833                                if (mPendingInstalls.size() == 0) {
834                                    if (mBound) {
835                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                                "Posting delayed MCS_UNBIND");
837                                        removeMessages(MCS_UNBIND);
838                                        Message ubmsg = obtainMessage(MCS_UNBIND);
839                                        // Unbind after a little delay, to avoid
840                                        // continual thrashing.
841                                        sendMessageDelayed(ubmsg, 10000);
842                                    }
843                                } else {
844                                    // There are more pending requests in queue.
845                                    // Just post MCS_BOUND message to trigger processing
846                                    // of next pending install.
847                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
848                                            "Posting MCS_BOUND for next work");
849                                    mHandler.sendEmptyMessage(MCS_BOUND);
850                                }
851                            }
852                        }
853                    } else {
854                        // Should never happen ideally.
855                        Slog.w(TAG, "Empty queue");
856                    }
857                    break;
858                }
859                case MCS_RECONNECT: {
860                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
861                    if (mPendingInstalls.size() > 0) {
862                        if (mBound) {
863                            disconnectService();
864                        }
865                        if (!connectToService()) {
866                            Slog.e(TAG, "Failed to bind to media container service");
867                            for (HandlerParams params : mPendingInstalls) {
868                                // Indicate service bind error
869                                params.serviceError();
870                            }
871                            mPendingInstalls.clear();
872                        }
873                    }
874                    break;
875                }
876                case MCS_UNBIND: {
877                    // If there is no actual work left, then time to unbind.
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
879
880                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
881                        if (mBound) {
882                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
883
884                            disconnectService();
885                        }
886                    } else if (mPendingInstalls.size() > 0) {
887                        // There are more pending requests in queue.
888                        // Just post MCS_BOUND message to trigger processing
889                        // of next pending install.
890                        mHandler.sendEmptyMessage(MCS_BOUND);
891                    }
892
893                    break;
894                }
895                case MCS_GIVE_UP: {
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
897                    mPendingInstalls.remove(0);
898                    break;
899                }
900                case SEND_PENDING_BROADCAST: {
901                    String packages[];
902                    ArrayList<String> components[];
903                    int size = 0;
904                    int uids[];
905                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
906                    synchronized (mPackages) {
907                        if (mPendingBroadcasts == null) {
908                            return;
909                        }
910                        size = mPendingBroadcasts.size();
911                        if (size <= 0) {
912                            // Nothing to be done. Just return
913                            return;
914                        }
915                        packages = new String[size];
916                        components = new ArrayList[size];
917                        uids = new int[size];
918                        int i = 0;  // filling out the above arrays
919
920                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
921                            int packageUserId = mPendingBroadcasts.userIdAt(n);
922                            Iterator<Map.Entry<String, ArrayList<String>>> it
923                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
924                                            .entrySet().iterator();
925                            while (it.hasNext() && i < size) {
926                                Map.Entry<String, ArrayList<String>> ent = it.next();
927                                packages[i] = ent.getKey();
928                                components[i] = ent.getValue();
929                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
930                                uids[i] = (ps != null)
931                                        ? UserHandle.getUid(packageUserId, ps.appId)
932                                        : -1;
933                                i++;
934                            }
935                        }
936                        size = i;
937                        mPendingBroadcasts.clear();
938                    }
939                    // Send broadcasts
940                    for (int i = 0; i < size; i++) {
941                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
942                    }
943                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
944                    break;
945                }
946                case START_CLEANING_PACKAGE: {
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
948                    final String packageName = (String)msg.obj;
949                    final int userId = msg.arg1;
950                    final boolean andCode = msg.arg2 != 0;
951                    synchronized (mPackages) {
952                        if (userId == UserHandle.USER_ALL) {
953                            int[] users = sUserManager.getUserIds();
954                            for (int user : users) {
955                                mSettings.addPackageToCleanLPw(
956                                        new PackageCleanItem(user, packageName, andCode));
957                            }
958                        } else {
959                            mSettings.addPackageToCleanLPw(
960                                    new PackageCleanItem(userId, packageName, andCode));
961                        }
962                    }
963                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
964                    startCleaningPackages();
965                } break;
966                case POST_INSTALL: {
967                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
968                    PostInstallData data = mRunningInstalls.get(msg.arg1);
969                    mRunningInstalls.delete(msg.arg1);
970                    boolean deleteOld = false;
971
972                    if (data != null) {
973                        InstallArgs args = data.args;
974                        PackageInstalledInfo res = data.res;
975
976                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
977                            res.removedInfo.sendBroadcast(false, true, false);
978                            Bundle extras = new Bundle(1);
979                            extras.putInt(Intent.EXTRA_UID, res.uid);
980                            // Determine the set of users who are adding this
981                            // package for the first time vs. those who are seeing
982                            // an update.
983                            int[] firstUsers;
984                            int[] updateUsers = new int[0];
985                            if (res.origUsers == null || res.origUsers.length == 0) {
986                                firstUsers = res.newUsers;
987                            } else {
988                                firstUsers = new int[0];
989                                for (int i=0; i<res.newUsers.length; i++) {
990                                    int user = res.newUsers[i];
991                                    boolean isNew = true;
992                                    for (int j=0; j<res.origUsers.length; j++) {
993                                        if (res.origUsers[j] == user) {
994                                            isNew = false;
995                                            break;
996                                        }
997                                    }
998                                    if (isNew) {
999                                        int[] newFirst = new int[firstUsers.length+1];
1000                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1001                                                firstUsers.length);
1002                                        newFirst[firstUsers.length] = user;
1003                                        firstUsers = newFirst;
1004                                    } else {
1005                                        int[] newUpdate = new int[updateUsers.length+1];
1006                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1007                                                updateUsers.length);
1008                                        newUpdate[updateUsers.length] = user;
1009                                        updateUsers = newUpdate;
1010                                    }
1011                                }
1012                            }
1013                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1014                                    res.pkg.applicationInfo.packageName,
1015                                    extras, null, null, firstUsers);
1016                            final boolean update = res.removedInfo.removedPackage != null;
1017                            if (update) {
1018                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1019                            }
1020                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1021                                    res.pkg.applicationInfo.packageName,
1022                                    extras, null, null, updateUsers);
1023                            if (update) {
1024                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1025                                        res.pkg.applicationInfo.packageName,
1026                                        extras, null, null, updateUsers);
1027                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1028                                        null, null,
1029                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1030
1031                                // treat asec-hosted packages like removable media on upgrade
1032                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1033                                    if (DEBUG_INSTALL) {
1034                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1035                                                + " is ASEC-hosted -> AVAILABLE");
1036                                    }
1037                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1038                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1039                                    pkgList.add(res.pkg.applicationInfo.packageName);
1040                                    sendResourcesChangedBroadcast(true, true,
1041                                            pkgList,uidArray, null);
1042                                }
1043                            }
1044                            if (res.removedInfo.args != null) {
1045                                // Remove the replaced package's older resources safely now
1046                                deleteOld = true;
1047                            }
1048
1049                            // Log current value of "unknown sources" setting
1050                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1051                                getUnknownSourcesSettings());
1052                        }
1053                        // Force a gc to clear up things
1054                        Runtime.getRuntime().gc();
1055                        // We delete after a gc for applications  on sdcard.
1056                        if (deleteOld) {
1057                            synchronized (mInstallLock) {
1058                                res.removedInfo.args.doPostDeleteLI(true);
1059                            }
1060                        }
1061                        if (args.observer != null) {
1062                            try {
1063                                Bundle extras = extrasForInstallResult(res);
1064                                args.observer.onPackageInstalled(res.name, res.returnCode,
1065                                        res.returnMsg, extras);
1066                            } catch (RemoteException e) {
1067                                Slog.i(TAG, "Observer no longer exists.");
1068                            }
1069                        }
1070                    } else {
1071                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1072                    }
1073                } break;
1074                case UPDATED_MEDIA_STATUS: {
1075                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1076                    boolean reportStatus = msg.arg1 == 1;
1077                    boolean doGc = msg.arg2 == 1;
1078                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1079                    if (doGc) {
1080                        // Force a gc to clear up stale containers.
1081                        Runtime.getRuntime().gc();
1082                    }
1083                    if (msg.obj != null) {
1084                        @SuppressWarnings("unchecked")
1085                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1086                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1087                        // Unload containers
1088                        unloadAllContainers(args);
1089                    }
1090                    if (reportStatus) {
1091                        try {
1092                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1093                            PackageHelper.getMountService().finishMediaUpdate();
1094                        } catch (RemoteException e) {
1095                            Log.e(TAG, "MountService not running?");
1096                        }
1097                    }
1098                } break;
1099                case WRITE_SETTINGS: {
1100                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1101                    synchronized (mPackages) {
1102                        removeMessages(WRITE_SETTINGS);
1103                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1104                        mSettings.writeLPr();
1105                        mDirtyUsers.clear();
1106                    }
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108                } break;
1109                case WRITE_PACKAGE_RESTRICTIONS: {
1110                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111                    synchronized (mPackages) {
1112                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1113                        for (int userId : mDirtyUsers) {
1114                            mSettings.writePackageRestrictionsLPr(userId);
1115                        }
1116                        mDirtyUsers.clear();
1117                    }
1118                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1119                } break;
1120                case CHECK_PENDING_VERIFICATION: {
1121                    final int verificationId = msg.arg1;
1122                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1123
1124                    if ((state != null) && !state.timeoutExtended()) {
1125                        final InstallArgs args = state.getInstallArgs();
1126                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1127
1128                        Slog.i(TAG, "Verification timed out for " + originUri);
1129                        mPendingVerification.remove(verificationId);
1130
1131                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1132
1133                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1134                            Slog.i(TAG, "Continuing with installation of " + originUri);
1135                            state.setVerifierResponse(Binder.getCallingUid(),
1136                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1137                            broadcastPackageVerified(verificationId, originUri,
1138                                    PackageManager.VERIFICATION_ALLOW,
1139                                    state.getInstallArgs().getUser());
1140                            try {
1141                                ret = args.copyApk(mContainerService, true);
1142                            } catch (RemoteException e) {
1143                                Slog.e(TAG, "Could not contact the ContainerService");
1144                            }
1145                        } else {
1146                            broadcastPackageVerified(verificationId, originUri,
1147                                    PackageManager.VERIFICATION_REJECT,
1148                                    state.getInstallArgs().getUser());
1149                        }
1150
1151                        processPendingInstall(args, ret);
1152                        mHandler.sendEmptyMessage(MCS_UNBIND);
1153                    }
1154                    break;
1155                }
1156                case PACKAGE_VERIFIED: {
1157                    final int verificationId = msg.arg1;
1158
1159                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1160                    if (state == null) {
1161                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1162                        break;
1163                    }
1164
1165                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1166
1167                    state.setVerifierResponse(response.callerUid, response.code);
1168
1169                    if (state.isVerificationComplete()) {
1170                        mPendingVerification.remove(verificationId);
1171
1172                        final InstallArgs args = state.getInstallArgs();
1173                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1174
1175                        int ret;
1176                        if (state.isInstallAllowed()) {
1177                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1178                            broadcastPackageVerified(verificationId, originUri,
1179                                    response.code, state.getInstallArgs().getUser());
1180                            try {
1181                                ret = args.copyApk(mContainerService, true);
1182                            } catch (RemoteException e) {
1183                                Slog.e(TAG, "Could not contact the ContainerService");
1184                            }
1185                        } else {
1186                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1187                        }
1188
1189                        processPendingInstall(args, ret);
1190
1191                        mHandler.sendEmptyMessage(MCS_UNBIND);
1192                    }
1193
1194                    break;
1195                }
1196            }
1197        }
1198    }
1199
1200    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1201        Bundle extras = null;
1202        switch (res.returnCode) {
1203            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1204                extras = new Bundle();
1205                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1206                        res.origPermission);
1207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1208                        res.origPackage);
1209                break;
1210            }
1211        }
1212        return extras;
1213    }
1214
1215    void scheduleWriteSettingsLocked() {
1216        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1217            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1218        }
1219    }
1220
1221    void scheduleWritePackageRestrictionsLocked(int userId) {
1222        if (!sUserManager.exists(userId)) return;
1223        mDirtyUsers.add(userId);
1224        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1225            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1226        }
1227    }
1228
1229    public static final PackageManagerService main(Context context, Installer installer,
1230            boolean factoryTest, boolean onlyCore) {
1231        PackageManagerService m = new PackageManagerService(context, installer,
1232                factoryTest, onlyCore);
1233        ServiceManager.addService("package", m);
1234        return m;
1235    }
1236
1237    static String[] splitString(String str, char sep) {
1238        int count = 1;
1239        int i = 0;
1240        while ((i=str.indexOf(sep, i)) >= 0) {
1241            count++;
1242            i++;
1243        }
1244
1245        String[] res = new String[count];
1246        i=0;
1247        count = 0;
1248        int lastI=0;
1249        while ((i=str.indexOf(sep, i)) >= 0) {
1250            res[count] = str.substring(lastI, i);
1251            count++;
1252            i++;
1253            lastI = i;
1254        }
1255        res[count] = str.substring(lastI, str.length());
1256        return res;
1257    }
1258
1259    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1260        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1261                Context.DISPLAY_SERVICE);
1262        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1263    }
1264
1265    public PackageManagerService(Context context, Installer installer,
1266            boolean factoryTest, boolean onlyCore) {
1267        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1268                SystemClock.uptimeMillis());
1269
1270        if (mSdkVersion <= 0) {
1271            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1272        }
1273
1274        mContext = context;
1275        mFactoryTest = factoryTest;
1276        mOnlyCore = onlyCore;
1277        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1278        mMetrics = new DisplayMetrics();
1279        mSettings = new Settings(context);
1280        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1281                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1282        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1283                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1284        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292
1293        String separateProcesses = SystemProperties.get("debug.separate_processes");
1294        if (separateProcesses != null && separateProcesses.length() > 0) {
1295            if ("*".equals(separateProcesses)) {
1296                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1297                mSeparateProcesses = null;
1298                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1299            } else {
1300                mDefParseFlags = 0;
1301                mSeparateProcesses = separateProcesses.split(",");
1302                Slog.w(TAG, "Running with debug.separate_processes: "
1303                        + separateProcesses);
1304            }
1305        } else {
1306            mDefParseFlags = 0;
1307            mSeparateProcesses = null;
1308        }
1309
1310        mInstaller = installer;
1311
1312        getDefaultDisplayMetrics(context, mMetrics);
1313
1314        SystemConfig systemConfig = SystemConfig.getInstance();
1315        mGlobalGids = systemConfig.getGlobalGids();
1316        mSystemPermissions = systemConfig.getSystemPermissions();
1317        mAvailableFeatures = systemConfig.getAvailableFeatures();
1318
1319        synchronized (mInstallLock) {
1320        // writer
1321        synchronized (mPackages) {
1322            mHandlerThread = new ServiceThread(TAG,
1323                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1324            mHandlerThread.start();
1325            mHandler = new PackageHandler(mHandlerThread.getLooper());
1326            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1327
1328            File dataDir = Environment.getDataDirectory();
1329            mAppDataDir = new File(dataDir, "data");
1330            mAppInstallDir = new File(dataDir, "app");
1331            mAppLib32InstallDir = new File(dataDir, "app-lib");
1332            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1333            mUserAppDataDir = new File(dataDir, "user");
1334            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1335
1336            sUserManager = new UserManagerService(context, this,
1337                    mInstallLock, mPackages);
1338
1339            // Propagate permission configuration in to package manager.
1340            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1341                    = systemConfig.getPermissions();
1342            for (int i=0; i<permConfig.size(); i++) {
1343                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1344                BasePermission bp = mSettings.mPermissions.get(perm.name);
1345                if (bp == null) {
1346                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1347                    mSettings.mPermissions.put(perm.name, bp);
1348                }
1349                if (perm.gids != null) {
1350                    bp.gids = appendInts(bp.gids, perm.gids);
1351                }
1352            }
1353
1354            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1355            for (int i=0; i<libConfig.size(); i++) {
1356                mSharedLibraries.put(libConfig.keyAt(i),
1357                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1358            }
1359
1360            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1361
1362            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1363                    mSdkVersion, mOnlyCore);
1364
1365            String customResolverActivity = Resources.getSystem().getString(
1366                    R.string.config_customResolverActivity);
1367            if (TextUtils.isEmpty(customResolverActivity)) {
1368                customResolverActivity = null;
1369            } else {
1370                mCustomResolverComponentName = ComponentName.unflattenFromString(
1371                        customResolverActivity);
1372            }
1373
1374            long startTime = SystemClock.uptimeMillis();
1375
1376            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1377                    startTime);
1378
1379            // Set flag to monitor and not change apk file paths when
1380            // scanning install directories.
1381            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1382
1383            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1384
1385            /**
1386             * Add everything in the in the boot class path to the
1387             * list of process files because dexopt will have been run
1388             * if necessary during zygote startup.
1389             */
1390            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1391            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1392
1393            if (bootClassPath != null) {
1394                String[] bootClassPathElements = splitString(bootClassPath, ':');
1395                for (String element : bootClassPathElements) {
1396                    alreadyDexOpted.add(element);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            if (systemServerClassPath != null) {
1403                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1404                for (String element : systemServerClassPathElements) {
1405                    alreadyDexOpted.add(element);
1406                }
1407            } else {
1408                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1409            }
1410
1411            boolean didDexOptLibraryOrTool = false;
1412
1413            final List<String> allInstructionSets = getAllInstructionSets();
1414            final String[] dexCodeInstructionSets =
1415                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1416
1417            /**
1418             * Ensure all external libraries have had dexopt run on them.
1419             */
1420            if (mSharedLibraries.size() > 0) {
1421                // NOTE: For now, we're compiling these system "shared libraries"
1422                // (and framework jars) into all available architectures. It's possible
1423                // to compile them only when we come across an app that uses them (there's
1424                // already logic for that in scanPackageLI) but that adds some complexity.
1425                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1426                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1427                        final String lib = libEntry.path;
1428                        if (lib == null) {
1429                            continue;
1430                        }
1431
1432                        try {
1433                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1434                                                                                 dexCodeInstructionSet,
1435                                                                                 false);
1436                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1437                                alreadyDexOpted.add(lib);
1438
1439                                // The list of "shared libraries" we have at this point is
1440                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1441                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1442                                } else {
1443                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1444                                }
1445                                didDexOptLibraryOrTool = true;
1446                            }
1447                        } catch (FileNotFoundException e) {
1448                            Slog.w(TAG, "Library not found: " + lib);
1449                        } catch (IOException e) {
1450                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1451                                    + e.getMessage());
1452                        }
1453                    }
1454                }
1455            }
1456
1457            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1458
1459            // Gross hack for now: we know this file doesn't contain any
1460            // code, so don't dexopt it to avoid the resulting log spew.
1461            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1462
1463            // Gross hack for now: we know this file is only part of
1464            // the boot class path for art, so don't dexopt it to
1465            // avoid the resulting log spew.
1466            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1467
1468            /**
1469             * And there are a number of commands implemented in Java, which
1470             * we currently need to do the dexopt on so that they can be
1471             * run from a non-root shell.
1472             */
1473            String[] frameworkFiles = frameworkDir.list();
1474            if (frameworkFiles != null) {
1475                // TODO: We could compile these only for the most preferred ABI. We should
1476                // first double check that the dex files for these commands are not referenced
1477                // by other system apps.
1478                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1479                    for (int i=0; i<frameworkFiles.length; i++) {
1480                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1481                        String path = libPath.getPath();
1482                        // Skip the file if we already did it.
1483                        if (alreadyDexOpted.contains(path)) {
1484                            continue;
1485                        }
1486                        // Skip the file if it is not a type we want to dexopt.
1487                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1488                            continue;
1489                        }
1490                        try {
1491                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1492                                                                                 dexCodeInstructionSet,
1493                                                                                 false);
1494                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1495                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1496                                didDexOptLibraryOrTool = true;
1497                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1498                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1499                                didDexOptLibraryOrTool = true;
1500                            }
1501                        } catch (FileNotFoundException e) {
1502                            Slog.w(TAG, "Jar not found: " + path);
1503                        } catch (IOException e) {
1504                            Slog.w(TAG, "Exception reading jar: " + path, e);
1505                        }
1506                    }
1507                }
1508            }
1509
1510            // Collect vendor overlay packages.
1511            // (Do this before scanning any apps.)
1512            // For security and version matching reason, only consider
1513            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1514            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1515            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1516                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1517
1518            // Find base frameworks (resource packages without code).
1519            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR
1521                    | PackageParser.PARSE_IS_PRIVILEGED,
1522                    scanFlags | SCAN_NO_DEX, 0);
1523
1524            // Collected privileged system packages.
1525            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1526            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1527                    | PackageParser.PARSE_IS_SYSTEM_DIR
1528                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1529
1530            // Collect ordinary system packages.
1531            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1532            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1534
1535            // Collect all vendor packages.
1536            File vendorAppDir = new File("/vendor/app");
1537            try {
1538                vendorAppDir = vendorAppDir.getCanonicalFile();
1539            } catch (IOException e) {
1540                // failed to look up canonical path, continue with original one
1541            }
1542            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1544
1545            // Collect all OEM packages.
1546            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1547            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1549
1550            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1551            mInstaller.moveFiles();
1552
1553            // Prune any system packages that no longer exist.
1554            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1555            if (!mOnlyCore) {
1556                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1557                while (psit.hasNext()) {
1558                    PackageSetting ps = psit.next();
1559
1560                    /*
1561                     * If this is not a system app, it can't be a
1562                     * disable system app.
1563                     */
1564                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1565                        continue;
1566                    }
1567
1568                    /*
1569                     * If the package is scanned, it's not erased.
1570                     */
1571                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1572                    if (scannedPkg != null) {
1573                        /*
1574                         * If the system app is both scanned and in the
1575                         * disabled packages list, then it must have been
1576                         * added via OTA. Remove it from the currently
1577                         * scanned package so the previously user-installed
1578                         * application can be scanned.
1579                         */
1580                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1581                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1582                                    + "; removing system app");
1583                            removePackageLI(ps, true);
1584                        }
1585
1586                        continue;
1587                    }
1588
1589                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1590                        psit.remove();
1591                        String msg = "System package " + ps.name
1592                                + " no longer exists; wiping its data";
1593                        reportSettingsProblem(Log.WARN, msg);
1594                        removeDataDirsLI(ps.name);
1595                    } else {
1596                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1597                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1598                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1599                        }
1600                    }
1601                }
1602            }
1603
1604            //look for any incomplete package installations
1605            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1606            //clean up list
1607            for(int i = 0; i < deletePkgsList.size(); i++) {
1608                //clean up here
1609                cleanupInstallFailedPackage(deletePkgsList.get(i));
1610            }
1611            //delete tmp files
1612            deleteTempPackageFiles();
1613
1614            // Remove any shared userIDs that have no associated packages
1615            mSettings.pruneSharedUsersLPw();
1616
1617            if (!mOnlyCore) {
1618                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1619                        SystemClock.uptimeMillis());
1620                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1621
1622                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1623                        scanFlags, 0);
1624
1625                /**
1626                 * Remove disable package settings for any updated system
1627                 * apps that were removed via an OTA. If they're not a
1628                 * previously-updated app, remove them completely.
1629                 * Otherwise, just revoke their system-level permissions.
1630                 */
1631                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1632                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1633                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1634
1635                    String msg;
1636                    if (deletedPkg == null) {
1637                        msg = "Updated system package " + deletedAppName
1638                                + " no longer exists; wiping its data";
1639                        removeDataDirsLI(deletedAppName);
1640                    } else {
1641                        msg = "Updated system app + " + deletedAppName
1642                                + " no longer present; removing system privileges for "
1643                                + deletedAppName;
1644
1645                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1646
1647                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1648                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1649                    }
1650                    reportSettingsProblem(Log.WARN, msg);
1651                }
1652            }
1653
1654            // Now that we know all of the shared libraries, update all clients to have
1655            // the correct library paths.
1656            updateAllSharedLibrariesLPw();
1657
1658            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1659                // NOTE: We ignore potential failures here during a system scan (like
1660                // the rest of the commands above) because there's precious little we
1661                // can do about it. A settings error is reported, though.
1662                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1663                        false /* force dexopt */, false /* defer dexopt */);
1664            }
1665
1666            // Now that we know all the packages we are keeping,
1667            // read and update their last usage times.
1668            mPackageUsage.readLP();
1669
1670            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1671                    SystemClock.uptimeMillis());
1672            Slog.i(TAG, "Time to scan packages: "
1673                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1674                    + " seconds");
1675
1676            // If the platform SDK has changed since the last time we booted,
1677            // we need to re-grant app permission to catch any new ones that
1678            // appear.  This is really a hack, and means that apps can in some
1679            // cases get permissions that the user didn't initially explicitly
1680            // allow...  it would be nice to have some better way to handle
1681            // this situation.
1682            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1683                    != mSdkVersion;
1684            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1685                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1686                    + "; regranting permissions for internal storage");
1687            mSettings.mInternalSdkPlatform = mSdkVersion;
1688
1689            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1690                    | (regrantPermissions
1691                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1692                            : 0));
1693
1694            // If this is the first boot, and it is a normal boot, then
1695            // we need to initialize the default preferred apps.
1696            if (!mRestoredSettings && !onlyCore) {
1697                mSettings.readDefaultPreferredAppsLPw(this, 0);
1698            }
1699
1700            // If this is first boot after an OTA, and a normal boot, then
1701            // we need to clear code cache directories.
1702            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1703                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1704                for (String pkgName : mSettings.mPackages.keySet()) {
1705                    deleteCodeCacheDirsLI(pkgName);
1706                }
1707                mSettings.mFingerprint = Build.FINGERPRINT;
1708            }
1709
1710            // All the changes are done during package scanning.
1711            mSettings.updateInternalDatabaseVersion();
1712
1713            // can downgrade to reader
1714            mSettings.writeLPr();
1715
1716            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1717                    SystemClock.uptimeMillis());
1718
1719
1720            mRequiredVerifierPackage = getRequiredVerifierLPr();
1721        } // synchronized (mPackages)
1722        } // synchronized (mInstallLock)
1723
1724        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1725
1726        // Now after opening every single application zip, make sure they
1727        // are all flushed.  Not really needed, but keeps things nice and
1728        // tidy.
1729        Runtime.getRuntime().gc();
1730    }
1731
1732    @Override
1733    public boolean isFirstBoot() {
1734        return !mRestoredSettings;
1735    }
1736
1737    @Override
1738    public boolean isOnlyCoreApps() {
1739        return mOnlyCore;
1740    }
1741
1742    private String getRequiredVerifierLPr() {
1743        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1744        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1745                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1746
1747        String requiredVerifier = null;
1748
1749        final int N = receivers.size();
1750        for (int i = 0; i < N; i++) {
1751            final ResolveInfo info = receivers.get(i);
1752
1753            if (info.activityInfo == null) {
1754                continue;
1755            }
1756
1757            final String packageName = info.activityInfo.packageName;
1758
1759            final PackageSetting ps = mSettings.mPackages.get(packageName);
1760            if (ps == null) {
1761                continue;
1762            }
1763
1764            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1765            if (!gp.grantedPermissions
1766                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1767                continue;
1768            }
1769
1770            if (requiredVerifier != null) {
1771                throw new RuntimeException("There can be only one required verifier");
1772            }
1773
1774            requiredVerifier = packageName;
1775        }
1776
1777        return requiredVerifier;
1778    }
1779
1780    @Override
1781    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1782            throws RemoteException {
1783        try {
1784            return super.onTransact(code, data, reply, flags);
1785        } catch (RuntimeException e) {
1786            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1787                Slog.wtf(TAG, "Package Manager Crash", e);
1788            }
1789            throw e;
1790        }
1791    }
1792
1793    void cleanupInstallFailedPackage(PackageSetting ps) {
1794        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1795        removeDataDirsLI(ps.name);
1796
1797        // TODO: try cleaning up codePath directory contents first, since it
1798        // might be a cluster
1799
1800        if (ps.codePath != null) {
1801            if (!ps.codePath.delete()) {
1802                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1803            }
1804        }
1805        if (ps.resourcePath != null) {
1806            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1807                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1808            }
1809        }
1810        mSettings.removePackageLPw(ps.name);
1811    }
1812
1813    static int[] appendInts(int[] cur, int[] add) {
1814        if (add == null) return cur;
1815        if (cur == null) return add;
1816        final int N = add.length;
1817        for (int i=0; i<N; i++) {
1818            cur = appendInt(cur, add[i]);
1819        }
1820        return cur;
1821    }
1822
1823    static int[] removeInts(int[] cur, int[] rem) {
1824        if (rem == null) return cur;
1825        if (cur == null) return cur;
1826        final int N = rem.length;
1827        for (int i=0; i<N; i++) {
1828            cur = removeInt(cur, rem[i]);
1829        }
1830        return cur;
1831    }
1832
1833    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1834        if (!sUserManager.exists(userId)) return null;
1835        final PackageSetting ps = (PackageSetting) p.mExtras;
1836        if (ps == null) {
1837            return null;
1838        }
1839        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1840        final PackageUserState state = ps.readUserState(userId);
1841        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1842                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1843                state, userId);
1844    }
1845
1846    @Override
1847    public boolean isPackageAvailable(String packageName, int userId) {
1848        if (!sUserManager.exists(userId)) return false;
1849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1850        synchronized (mPackages) {
1851            PackageParser.Package p = mPackages.get(packageName);
1852            if (p != null) {
1853                final PackageSetting ps = (PackageSetting) p.mExtras;
1854                if (ps != null) {
1855                    final PackageUserState state = ps.readUserState(userId);
1856                    if (state != null) {
1857                        return PackageParser.isAvailable(state);
1858                    }
1859                }
1860            }
1861        }
1862        return false;
1863    }
1864
1865    @Override
1866    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1867        if (!sUserManager.exists(userId)) return null;
1868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1869        // reader
1870        synchronized (mPackages) {
1871            PackageParser.Package p = mPackages.get(packageName);
1872            if (DEBUG_PACKAGE_INFO)
1873                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1874            if (p != null) {
1875                return generatePackageInfo(p, flags, userId);
1876            }
1877            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1878                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1879            }
1880        }
1881        return null;
1882    }
1883
1884    @Override
1885    public String[] currentToCanonicalPackageNames(String[] names) {
1886        String[] out = new String[names.length];
1887        // reader
1888        synchronized (mPackages) {
1889            for (int i=names.length-1; i>=0; i--) {
1890                PackageSetting ps = mSettings.mPackages.get(names[i]);
1891                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1892            }
1893        }
1894        return out;
1895    }
1896
1897    @Override
1898    public String[] canonicalToCurrentPackageNames(String[] names) {
1899        String[] out = new String[names.length];
1900        // reader
1901        synchronized (mPackages) {
1902            for (int i=names.length-1; i>=0; i--) {
1903                String cur = mSettings.mRenamedPackages.get(names[i]);
1904                out[i] = cur != null ? cur : names[i];
1905            }
1906        }
1907        return out;
1908    }
1909
1910    @Override
1911    public int getPackageUid(String packageName, int userId) {
1912        if (!sUserManager.exists(userId)) return -1;
1913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1914        // reader
1915        synchronized (mPackages) {
1916            PackageParser.Package p = mPackages.get(packageName);
1917            if(p != null) {
1918                return UserHandle.getUid(userId, p.applicationInfo.uid);
1919            }
1920            PackageSetting ps = mSettings.mPackages.get(packageName);
1921            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1922                return -1;
1923            }
1924            p = ps.pkg;
1925            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1926        }
1927    }
1928
1929    @Override
1930    public int[] getPackageGids(String packageName) {
1931        // reader
1932        synchronized (mPackages) {
1933            PackageParser.Package p = mPackages.get(packageName);
1934            if (DEBUG_PACKAGE_INFO)
1935                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1936            if (p != null) {
1937                final PackageSetting ps = (PackageSetting)p.mExtras;
1938                return ps.getGids();
1939            }
1940        }
1941        // stupid thing to indicate an error.
1942        return new int[0];
1943    }
1944
1945    static final PermissionInfo generatePermissionInfo(
1946            BasePermission bp, int flags) {
1947        if (bp.perm != null) {
1948            return PackageParser.generatePermissionInfo(bp.perm, flags);
1949        }
1950        PermissionInfo pi = new PermissionInfo();
1951        pi.name = bp.name;
1952        pi.packageName = bp.sourcePackage;
1953        pi.nonLocalizedLabel = bp.name;
1954        pi.protectionLevel = bp.protectionLevel;
1955        return pi;
1956    }
1957
1958    @Override
1959    public PermissionInfo getPermissionInfo(String name, int flags) {
1960        // reader
1961        synchronized (mPackages) {
1962            final BasePermission p = mSettings.mPermissions.get(name);
1963            if (p != null) {
1964                return generatePermissionInfo(p, flags);
1965            }
1966            return null;
1967        }
1968    }
1969
1970    @Override
1971    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1972        // reader
1973        synchronized (mPackages) {
1974            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1975            for (BasePermission p : mSettings.mPermissions.values()) {
1976                if (group == null) {
1977                    if (p.perm == null || p.perm.info.group == null) {
1978                        out.add(generatePermissionInfo(p, flags));
1979                    }
1980                } else {
1981                    if (p.perm != null && group.equals(p.perm.info.group)) {
1982                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1983                    }
1984                }
1985            }
1986
1987            if (out.size() > 0) {
1988                return out;
1989            }
1990            return mPermissionGroups.containsKey(group) ? out : null;
1991        }
1992    }
1993
1994    @Override
1995    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1996        // reader
1997        synchronized (mPackages) {
1998            return PackageParser.generatePermissionGroupInfo(
1999                    mPermissionGroups.get(name), flags);
2000        }
2001    }
2002
2003    @Override
2004    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2005        // reader
2006        synchronized (mPackages) {
2007            final int N = mPermissionGroups.size();
2008            ArrayList<PermissionGroupInfo> out
2009                    = new ArrayList<PermissionGroupInfo>(N);
2010            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2011                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2012            }
2013            return out;
2014        }
2015    }
2016
2017    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2018            int userId) {
2019        if (!sUserManager.exists(userId)) return null;
2020        PackageSetting ps = mSettings.mPackages.get(packageName);
2021        if (ps != null) {
2022            if (ps.pkg == null) {
2023                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2024                        flags, userId);
2025                if (pInfo != null) {
2026                    return pInfo.applicationInfo;
2027                }
2028                return null;
2029            }
2030            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2031                    ps.readUserState(userId), userId);
2032        }
2033        return null;
2034    }
2035
2036    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2037            int userId) {
2038        if (!sUserManager.exists(userId)) return null;
2039        PackageSetting ps = mSettings.mPackages.get(packageName);
2040        if (ps != null) {
2041            PackageParser.Package pkg = ps.pkg;
2042            if (pkg == null) {
2043                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2044                    return null;
2045                }
2046                // Only data remains, so we aren't worried about code paths
2047                pkg = new PackageParser.Package(packageName);
2048                pkg.applicationInfo.packageName = packageName;
2049                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2050                pkg.applicationInfo.dataDir =
2051                        getDataPathForPackage(packageName, 0).getPath();
2052                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2053                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2054            }
2055            return generatePackageInfo(pkg, flags, userId);
2056        }
2057        return null;
2058    }
2059
2060    @Override
2061    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2062        if (!sUserManager.exists(userId)) return null;
2063        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2064        // writer
2065        synchronized (mPackages) {
2066            PackageParser.Package p = mPackages.get(packageName);
2067            if (DEBUG_PACKAGE_INFO) Log.v(
2068                    TAG, "getApplicationInfo " + packageName
2069                    + ": " + p);
2070            if (p != null) {
2071                PackageSetting ps = mSettings.mPackages.get(packageName);
2072                if (ps == null) return null;
2073                // Note: isEnabledLP() does not apply here - always return info
2074                return PackageParser.generateApplicationInfo(
2075                        p, flags, ps.readUserState(userId), userId);
2076            }
2077            if ("android".equals(packageName)||"system".equals(packageName)) {
2078                return mAndroidApplication;
2079            }
2080            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2081                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2082            }
2083        }
2084        return null;
2085    }
2086
2087
2088    @Override
2089    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2090        mContext.enforceCallingOrSelfPermission(
2091                android.Manifest.permission.CLEAR_APP_CACHE, null);
2092        // Queue up an async operation since clearing cache may take a little while.
2093        mHandler.post(new Runnable() {
2094            public void run() {
2095                mHandler.removeCallbacks(this);
2096                int retCode = -1;
2097                synchronized (mInstallLock) {
2098                    retCode = mInstaller.freeCache(freeStorageSize);
2099                    if (retCode < 0) {
2100                        Slog.w(TAG, "Couldn't clear application caches");
2101                    }
2102                }
2103                if (observer != null) {
2104                    try {
2105                        observer.onRemoveCompleted(null, (retCode >= 0));
2106                    } catch (RemoteException e) {
2107                        Slog.w(TAG, "RemoveException when invoking call back");
2108                    }
2109                }
2110            }
2111        });
2112    }
2113
2114    @Override
2115    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2116        mContext.enforceCallingOrSelfPermission(
2117                android.Manifest.permission.CLEAR_APP_CACHE, null);
2118        // Queue up an async operation since clearing cache may take a little while.
2119        mHandler.post(new Runnable() {
2120            public void run() {
2121                mHandler.removeCallbacks(this);
2122                int retCode = -1;
2123                synchronized (mInstallLock) {
2124                    retCode = mInstaller.freeCache(freeStorageSize);
2125                    if (retCode < 0) {
2126                        Slog.w(TAG, "Couldn't clear application caches");
2127                    }
2128                }
2129                if(pi != null) {
2130                    try {
2131                        // Callback via pending intent
2132                        int code = (retCode >= 0) ? 1 : 0;
2133                        pi.sendIntent(null, code, null,
2134                                null, null);
2135                    } catch (SendIntentException e1) {
2136                        Slog.i(TAG, "Failed to send pending intent");
2137                    }
2138                }
2139            }
2140        });
2141    }
2142
2143    void freeStorage(long freeStorageSize) throws IOException {
2144        synchronized (mInstallLock) {
2145            if (mInstaller.freeCache(freeStorageSize) < 0) {
2146                throw new IOException("Failed to free enough space");
2147            }
2148        }
2149    }
2150
2151    @Override
2152    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2153        if (!sUserManager.exists(userId)) return null;
2154        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2155        synchronized (mPackages) {
2156            PackageParser.Activity a = mActivities.mActivities.get(component);
2157
2158            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2159            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2160                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2161                if (ps == null) return null;
2162                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2163                        userId);
2164            }
2165            if (mResolveComponentName.equals(component)) {
2166                return mResolveActivity;
2167            }
2168        }
2169        return null;
2170    }
2171
2172    @Override
2173    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2174            String resolvedType) {
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177            if (a == null) {
2178                return false;
2179            }
2180            for (int i=0; i<a.intents.size(); i++) {
2181                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2182                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2183                    return true;
2184                }
2185            }
2186            return false;
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mReceivers.mActivities.get(component);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                TAG, "getReceiverInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2212        synchronized (mPackages) {
2213            PackageParser.Service s = mServices.mServices.get(component);
2214            if (DEBUG_PACKAGE_INFO) Log.v(
2215                TAG, "getServiceInfo " + component + ": " + s);
2216            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2230        synchronized (mPackages) {
2231            PackageParser.Provider p = mProviders.mProviders.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getProviderInfo " + component + ": " + p);
2234            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public String[] getSystemSharedLibraryNames() {
2246        Set<String> libSet;
2247        synchronized (mPackages) {
2248            libSet = mSharedLibraries.keySet();
2249            int size = libSet.size();
2250            if (size > 0) {
2251                String[] libs = new String[size];
2252                libSet.toArray(libs);
2253                return libs;
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public FeatureInfo[] getSystemAvailableFeatures() {
2261        Collection<FeatureInfo> featSet;
2262        synchronized (mPackages) {
2263            featSet = mAvailableFeatures.values();
2264            int size = featSet.size();
2265            if (size > 0) {
2266                FeatureInfo[] features = new FeatureInfo[size+1];
2267                featSet.toArray(features);
2268                FeatureInfo fi = new FeatureInfo();
2269                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2270                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2271                features[size] = fi;
2272                return features;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public boolean hasSystemFeature(String name) {
2280        synchronized (mPackages) {
2281            return mAvailableFeatures.containsKey(name);
2282        }
2283    }
2284
2285    private void checkValidCaller(int uid, int userId) {
2286        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2287            return;
2288
2289        throw new SecurityException("Caller uid=" + uid
2290                + " is not privileged to communicate with user=" + userId);
2291    }
2292
2293    @Override
2294    public int checkPermission(String permName, String pkgName) {
2295        synchronized (mPackages) {
2296            PackageParser.Package p = mPackages.get(pkgName);
2297            if (p != null && p.mExtras != null) {
2298                PackageSetting ps = (PackageSetting)p.mExtras;
2299                if (ps.sharedUser != null) {
2300                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2301                        return PackageManager.PERMISSION_GRANTED;
2302                    }
2303                } else if (ps.grantedPermissions.contains(permName)) {
2304                    return PackageManager.PERMISSION_GRANTED;
2305                }
2306            }
2307        }
2308        return PackageManager.PERMISSION_DENIED;
2309    }
2310
2311    @Override
2312    public int checkUidPermission(String permName, int uid) {
2313        synchronized (mPackages) {
2314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2315            if (obj != null) {
2316                GrantedPermissions gp = (GrantedPermissions)obj;
2317                if (gp.grantedPermissions.contains(permName)) {
2318                    return PackageManager.PERMISSION_GRANTED;
2319                }
2320            } else {
2321                HashSet<String> perms = mSystemPermissions.get(uid);
2322                if (perms != null && perms.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    /**
2331     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2332     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2333     * @param checkShell TODO(yamasani):
2334     * @param message the message to log on security exception
2335     */
2336    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2337            boolean checkShell, String message) {
2338        if (userId < 0) {
2339            throw new IllegalArgumentException("Invalid userId " + userId);
2340        }
2341        if (checkShell) {
2342            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2343        }
2344        if (userId == UserHandle.getUserId(callingUid)) return;
2345        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2346            if (requireFullPermission) {
2347                mContext.enforceCallingOrSelfPermission(
2348                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2349            } else {
2350                try {
2351                    mContext.enforceCallingOrSelfPermission(
2352                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2353                } catch (SecurityException se) {
2354                    mContext.enforceCallingOrSelfPermission(
2355                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2356                }
2357            }
2358        }
2359    }
2360
2361    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2362        if (callingUid == Process.SHELL_UID) {
2363            if (userHandle >= 0
2364                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2365                throw new SecurityException("Shell does not have permission to access user "
2366                        + userHandle);
2367            } else if (userHandle < 0) {
2368                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2369                        + Debug.getCallers(3));
2370            }
2371        }
2372    }
2373
2374    private BasePermission findPermissionTreeLP(String permName) {
2375        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2376            if (permName.startsWith(bp.name) &&
2377                    permName.length() > bp.name.length() &&
2378                    permName.charAt(bp.name.length()) == '.') {
2379                return bp;
2380            }
2381        }
2382        return null;
2383    }
2384
2385    private BasePermission checkPermissionTreeLP(String permName) {
2386        if (permName != null) {
2387            BasePermission bp = findPermissionTreeLP(permName);
2388            if (bp != null) {
2389                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2390                    return bp;
2391                }
2392                throw new SecurityException("Calling uid "
2393                        + Binder.getCallingUid()
2394                        + " is not allowed to add to permission tree "
2395                        + bp.name + " owned by uid " + bp.uid);
2396            }
2397        }
2398        throw new SecurityException("No permission tree found for " + permName);
2399    }
2400
2401    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2402        if (s1 == null) {
2403            return s2 == null;
2404        }
2405        if (s2 == null) {
2406            return false;
2407        }
2408        if (s1.getClass() != s2.getClass()) {
2409            return false;
2410        }
2411        return s1.equals(s2);
2412    }
2413
2414    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2415        if (pi1.icon != pi2.icon) return false;
2416        if (pi1.logo != pi2.logo) return false;
2417        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2418        if (!compareStrings(pi1.name, pi2.name)) return false;
2419        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2420        // We'll take care of setting this one.
2421        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2422        // These are not currently stored in settings.
2423        //if (!compareStrings(pi1.group, pi2.group)) return false;
2424        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2425        //if (pi1.labelRes != pi2.labelRes) return false;
2426        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2427        return true;
2428    }
2429
2430    int permissionInfoFootprint(PermissionInfo info) {
2431        int size = info.name.length();
2432        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2433        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2434        return size;
2435    }
2436
2437    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2438        int size = 0;
2439        for (BasePermission perm : mSettings.mPermissions.values()) {
2440            if (perm.uid == tree.uid) {
2441                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2442            }
2443        }
2444        return size;
2445    }
2446
2447    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2448        // We calculate the max size of permissions defined by this uid and throw
2449        // if that plus the size of 'info' would exceed our stated maximum.
2450        if (tree.uid != Process.SYSTEM_UID) {
2451            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2452            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2453                throw new SecurityException("Permission tree size cap exceeded");
2454            }
2455        }
2456    }
2457
2458    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2459        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2460            throw new SecurityException("Label must be specified in permission");
2461        }
2462        BasePermission tree = checkPermissionTreeLP(info.name);
2463        BasePermission bp = mSettings.mPermissions.get(info.name);
2464        boolean added = bp == null;
2465        boolean changed = true;
2466        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2467        if (added) {
2468            enforcePermissionCapLocked(info, tree);
2469            bp = new BasePermission(info.name, tree.sourcePackage,
2470                    BasePermission.TYPE_DYNAMIC);
2471        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2472            throw new SecurityException(
2473                    "Not allowed to modify non-dynamic permission "
2474                    + info.name);
2475        } else {
2476            if (bp.protectionLevel == fixedLevel
2477                    && bp.perm.owner.equals(tree.perm.owner)
2478                    && bp.uid == tree.uid
2479                    && comparePermissionInfos(bp.perm.info, info)) {
2480                changed = false;
2481            }
2482        }
2483        bp.protectionLevel = fixedLevel;
2484        info = new PermissionInfo(info);
2485        info.protectionLevel = fixedLevel;
2486        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2487        bp.perm.info.packageName = tree.perm.info.packageName;
2488        bp.uid = tree.uid;
2489        if (added) {
2490            mSettings.mPermissions.put(info.name, bp);
2491        }
2492        if (changed) {
2493            if (!async) {
2494                mSettings.writeLPr();
2495            } else {
2496                scheduleWriteSettingsLocked();
2497            }
2498        }
2499        return added;
2500    }
2501
2502    @Override
2503    public boolean addPermission(PermissionInfo info) {
2504        synchronized (mPackages) {
2505            return addPermissionLocked(info, false);
2506        }
2507    }
2508
2509    @Override
2510    public boolean addPermissionAsync(PermissionInfo info) {
2511        synchronized (mPackages) {
2512            return addPermissionLocked(info, true);
2513        }
2514    }
2515
2516    @Override
2517    public void removePermission(String name) {
2518        synchronized (mPackages) {
2519            checkPermissionTreeLP(name);
2520            BasePermission bp = mSettings.mPermissions.get(name);
2521            if (bp != null) {
2522                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2523                    throw new SecurityException(
2524                            "Not allowed to modify non-dynamic permission "
2525                            + name);
2526                }
2527                mSettings.mPermissions.remove(name);
2528                mSettings.writeLPr();
2529            }
2530        }
2531    }
2532
2533    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2534        int index = pkg.requestedPermissions.indexOf(bp.name);
2535        if (index == -1) {
2536            throw new SecurityException("Package " + pkg.packageName
2537                    + " has not requested permission " + bp.name);
2538        }
2539        boolean isNormal =
2540                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2541                        == PermissionInfo.PROTECTION_NORMAL);
2542        boolean isDangerous =
2543                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2544                        == PermissionInfo.PROTECTION_DANGEROUS);
2545        boolean isDevelopment =
2546                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2547
2548        if (!isNormal && !isDangerous && !isDevelopment) {
2549            throw new SecurityException("Permission " + bp.name
2550                    + " is not a changeable permission type");
2551        }
2552
2553        if (isNormal || isDangerous) {
2554            if (pkg.requestedPermissionsRequired.get(index)) {
2555                throw new SecurityException("Can't change " + bp.name
2556                        + ". It is required by the application");
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public void grantPermission(String packageName, String permissionName) {
2563        mContext.enforceCallingOrSelfPermission(
2564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2565        synchronized (mPackages) {
2566            final PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg == null) {
2568                throw new IllegalArgumentException("Unknown package: " + packageName);
2569            }
2570            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2571            if (bp == null) {
2572                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2573            }
2574
2575            checkGrantRevokePermissions(pkg, bp);
2576
2577            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2578            if (ps == null) {
2579                return;
2580            }
2581            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2582            if (gp.grantedPermissions.add(permissionName)) {
2583                if (ps.haveGids) {
2584                    gp.gids = appendInts(gp.gids, bp.gids);
2585                }
2586                mSettings.writeLPr();
2587            }
2588        }
2589    }
2590
2591    @Override
2592    public void revokePermission(String packageName, String permissionName) {
2593        int changedAppId = -1;
2594
2595        synchronized (mPackages) {
2596            final PackageParser.Package pkg = mPackages.get(packageName);
2597            if (pkg == null) {
2598                throw new IllegalArgumentException("Unknown package: " + packageName);
2599            }
2600            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2601                mContext.enforceCallingOrSelfPermission(
2602                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2603            }
2604            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2605            if (bp == null) {
2606                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2607            }
2608
2609            checkGrantRevokePermissions(pkg, bp);
2610
2611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2612            if (ps == null) {
2613                return;
2614            }
2615            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2616            if (gp.grantedPermissions.remove(permissionName)) {
2617                gp.grantedPermissions.remove(permissionName);
2618                if (ps.haveGids) {
2619                    gp.gids = removeInts(gp.gids, bp.gids);
2620                }
2621                mSettings.writeLPr();
2622                changedAppId = ps.appId;
2623            }
2624        }
2625
2626        if (changedAppId >= 0) {
2627            // We changed the perm on someone, kill its processes.
2628            IActivityManager am = ActivityManagerNative.getDefault();
2629            if (am != null) {
2630                final int callingUserId = UserHandle.getCallingUserId();
2631                final long ident = Binder.clearCallingIdentity();
2632                try {
2633                    //XXX we should only revoke for the calling user's app permissions,
2634                    // but for now we impact all users.
2635                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2636                    //        "revoke " + permissionName);
2637                    int[] users = sUserManager.getUserIds();
2638                    for (int user : users) {
2639                        am.killUid(UserHandle.getUid(user, changedAppId),
2640                                "revoke " + permissionName);
2641                    }
2642                } catch (RemoteException e) {
2643                } finally {
2644                    Binder.restoreCallingIdentity(ident);
2645                }
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public boolean isProtectedBroadcast(String actionName) {
2652        synchronized (mPackages) {
2653            return mProtectedBroadcasts.contains(actionName);
2654        }
2655    }
2656
2657    @Override
2658    public int checkSignatures(String pkg1, String pkg2) {
2659        synchronized (mPackages) {
2660            final PackageParser.Package p1 = mPackages.get(pkg1);
2661            final PackageParser.Package p2 = mPackages.get(pkg2);
2662            if (p1 == null || p1.mExtras == null
2663                    || p2 == null || p2.mExtras == null) {
2664                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2665            }
2666            return compareSignatures(p1.mSignatures, p2.mSignatures);
2667        }
2668    }
2669
2670    @Override
2671    public int checkUidSignatures(int uid1, int uid2) {
2672        // Map to base uids.
2673        uid1 = UserHandle.getAppId(uid1);
2674        uid2 = UserHandle.getAppId(uid2);
2675        // reader
2676        synchronized (mPackages) {
2677            Signature[] s1;
2678            Signature[] s2;
2679            Object obj = mSettings.getUserIdLPr(uid1);
2680            if (obj != null) {
2681                if (obj instanceof SharedUserSetting) {
2682                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2683                } else if (obj instanceof PackageSetting) {
2684                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2685                } else {
2686                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2687                }
2688            } else {
2689                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2690            }
2691            obj = mSettings.getUserIdLPr(uid2);
2692            if (obj != null) {
2693                if (obj instanceof SharedUserSetting) {
2694                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2695                } else if (obj instanceof PackageSetting) {
2696                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2697                } else {
2698                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2699                }
2700            } else {
2701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2702            }
2703            return compareSignatures(s1, s2);
2704        }
2705    }
2706
2707    /**
2708     * Compares two sets of signatures. Returns:
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2719     */
2720    static int compareSignatures(Signature[] s1, Signature[] s2) {
2721        if (s1 == null) {
2722            return s2 == null
2723                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2724                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2725        }
2726
2727        if (s2 == null) {
2728            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2729        }
2730
2731        if (s1.length != s2.length) {
2732            return PackageManager.SIGNATURE_NO_MATCH;
2733        }
2734
2735        // Since both signature sets are of size 1, we can compare without HashSets.
2736        if (s1.length == 1) {
2737            return s1[0].equals(s2[0]) ?
2738                    PackageManager.SIGNATURE_MATCH :
2739                    PackageManager.SIGNATURE_NO_MATCH;
2740        }
2741
2742        HashSet<Signature> set1 = new HashSet<Signature>();
2743        for (Signature sig : s1) {
2744            set1.add(sig);
2745        }
2746        HashSet<Signature> set2 = new HashSet<Signature>();
2747        for (Signature sig : s2) {
2748            set2.add(sig);
2749        }
2750        // Make sure s2 contains all signatures in s1.
2751        if (set1.equals(set2)) {
2752            return PackageManager.SIGNATURE_MATCH;
2753        }
2754        return PackageManager.SIGNATURE_NO_MATCH;
2755    }
2756
2757    /**
2758     * If the database version for this type of package (internal storage or
2759     * external storage) is less than the version where package signatures
2760     * were updated, return true.
2761     */
2762    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2763        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2764                DatabaseVersion.SIGNATURE_END_ENTITY))
2765                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2766                        DatabaseVersion.SIGNATURE_END_ENTITY));
2767    }
2768
2769    /**
2770     * Used for backward compatibility to make sure any packages with
2771     * certificate chains get upgraded to the new style. {@code existingSigs}
2772     * will be in the old format (since they were stored on disk from before the
2773     * system upgrade) and {@code scannedSigs} will be in the newer format.
2774     */
2775    private int compareSignaturesCompat(PackageSignatures existingSigs,
2776            PackageParser.Package scannedPkg) {
2777        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2778            return PackageManager.SIGNATURE_NO_MATCH;
2779        }
2780
2781        HashSet<Signature> existingSet = new HashSet<Signature>();
2782        for (Signature sig : existingSigs.mSignatures) {
2783            existingSet.add(sig);
2784        }
2785        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2786        for (Signature sig : scannedPkg.mSignatures) {
2787            try {
2788                Signature[] chainSignatures = sig.getChainSignatures();
2789                for (Signature chainSig : chainSignatures) {
2790                    scannedCompatSet.add(chainSig);
2791                }
2792            } catch (CertificateEncodingException e) {
2793                scannedCompatSet.add(sig);
2794            }
2795        }
2796        /*
2797         * Make sure the expanded scanned set contains all signatures in the
2798         * existing one.
2799         */
2800        if (scannedCompatSet.equals(existingSet)) {
2801            // Migrate the old signatures to the new scheme.
2802            existingSigs.assignSignatures(scannedPkg.mSignatures);
2803            // The new KeySets will be re-added later in the scanning process.
2804            synchronized (mPackages) {
2805                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2806            }
2807            return PackageManager.SIGNATURE_MATCH;
2808        }
2809        return PackageManager.SIGNATURE_NO_MATCH;
2810    }
2811
2812    @Override
2813    public String[] getPackagesForUid(int uid) {
2814        uid = UserHandle.getAppId(uid);
2815        // reader
2816        synchronized (mPackages) {
2817            Object obj = mSettings.getUserIdLPr(uid);
2818            if (obj instanceof SharedUserSetting) {
2819                final SharedUserSetting sus = (SharedUserSetting) obj;
2820                final int N = sus.packages.size();
2821                final String[] res = new String[N];
2822                final Iterator<PackageSetting> it = sus.packages.iterator();
2823                int i = 0;
2824                while (it.hasNext()) {
2825                    res[i++] = it.next().name;
2826                }
2827                return res;
2828            } else if (obj instanceof PackageSetting) {
2829                final PackageSetting ps = (PackageSetting) obj;
2830                return new String[] { ps.name };
2831            }
2832        }
2833        return null;
2834    }
2835
2836    @Override
2837    public String getNameForUid(int uid) {
2838        // reader
2839        synchronized (mPackages) {
2840            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2841            if (obj instanceof SharedUserSetting) {
2842                final SharedUserSetting sus = (SharedUserSetting) obj;
2843                return sus.name + ":" + sus.userId;
2844            } else if (obj instanceof PackageSetting) {
2845                final PackageSetting ps = (PackageSetting) obj;
2846                return ps.name;
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public int getUidForSharedUser(String sharedUserName) {
2854        if(sharedUserName == null) {
2855            return -1;
2856        }
2857        // reader
2858        synchronized (mPackages) {
2859            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2860            if (suid == null) {
2861                return -1;
2862            }
2863            return suid.userId;
2864        }
2865    }
2866
2867    @Override
2868    public int getFlagsForUid(int uid) {
2869        synchronized (mPackages) {
2870            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2871            if (obj instanceof SharedUserSetting) {
2872                final SharedUserSetting sus = (SharedUserSetting) obj;
2873                return sus.pkgFlags;
2874            } else if (obj instanceof PackageSetting) {
2875                final PackageSetting ps = (PackageSetting) obj;
2876                return ps.pkgFlags;
2877            }
2878        }
2879        return 0;
2880    }
2881
2882    @Override
2883    public String[] getAppOpPermissionPackages(String permissionName) {
2884        synchronized (mPackages) {
2885            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2886            if (pkgs == null) {
2887                return null;
2888            }
2889            return pkgs.toArray(new String[pkgs.size()]);
2890        }
2891    }
2892
2893    @Override
2894    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2895            int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2900    }
2901
2902    @Override
2903    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2904            IntentFilter filter, int match, ComponentName activity) {
2905        final int userId = UserHandle.getCallingUserId();
2906        if (DEBUG_PREFERRED) {
2907            Log.v(TAG, "setLastChosenActivity intent=" + intent
2908                + " resolvedType=" + resolvedType
2909                + " flags=" + flags
2910                + " filter=" + filter
2911                + " match=" + match
2912                + " activity=" + activity);
2913            filter.dump(new PrintStreamPrinter(System.out), "    ");
2914        }
2915        intent.setComponent(null);
2916        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2917        // Find any earlier preferred or last chosen entries and nuke them
2918        findPreferredActivity(intent, resolvedType,
2919                flags, query, 0, false, true, false, userId);
2920        // Add the new activity as the last chosen for this filter
2921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2922                "Setting last chosen");
2923    }
2924
2925    @Override
2926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2927        final int userId = UserHandle.getCallingUserId();
2928        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2929        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2931                false, false, false, userId);
2932    }
2933
2934    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2935            int flags, List<ResolveInfo> query, int userId) {
2936        if (query != null) {
2937            final int N = query.size();
2938            if (N == 1) {
2939                return query.get(0);
2940            } else if (N > 1) {
2941                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2942                // If there is more than one activity with the same priority,
2943                // then let the user decide between them.
2944                ResolveInfo r0 = query.get(0);
2945                ResolveInfo r1 = query.get(1);
2946                if (DEBUG_INTENT_MATCHING || debug) {
2947                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2948                            + r1.activityInfo.name + "=" + r1.priority);
2949                }
2950                // If the first activity has a higher priority, or a different
2951                // default, then it is always desireable to pick it.
2952                if (r0.priority != r1.priority
2953                        || r0.preferredOrder != r1.preferredOrder
2954                        || r0.isDefault != r1.isDefault) {
2955                    return query.get(0);
2956                }
2957                // If we have saved a preference for a preferred activity for
2958                // this Intent, use that.
2959                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2960                        flags, query, r0.priority, true, false, debug, userId);
2961                if (ri != null) {
2962                    return ri;
2963                }
2964                if (userId != 0) {
2965                    ri = new ResolveInfo(mResolveInfo);
2966                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2967                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2968                            ri.activityInfo.applicationInfo);
2969                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2970                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2971                    return ri;
2972                }
2973                return mResolveInfo;
2974            }
2975        }
2976        return null;
2977    }
2978
2979    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2980            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2981        final int N = query.size();
2982        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2983                .get(userId);
2984        // Get the list of persistent preferred activities that handle the intent
2985        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2986        List<PersistentPreferredActivity> pprefs = ppir != null
2987                ? ppir.queryIntent(intent, resolvedType,
2988                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2989                : null;
2990        if (pprefs != null && pprefs.size() > 0) {
2991            final int M = pprefs.size();
2992            for (int i=0; i<M; i++) {
2993                final PersistentPreferredActivity ppa = pprefs.get(i);
2994                if (DEBUG_PREFERRED || debug) {
2995                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2996                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2997                            + "\n  component=" + ppa.mComponent);
2998                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2999                }
3000                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3001                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3002                if (DEBUG_PREFERRED || debug) {
3003                    Slog.v(TAG, "Found persistent preferred activity:");
3004                    if (ai != null) {
3005                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3006                    } else {
3007                        Slog.v(TAG, "  null");
3008                    }
3009                }
3010                if (ai == null) {
3011                    // This previously registered persistent preferred activity
3012                    // component is no longer known. Ignore it and do NOT remove it.
3013                    continue;
3014                }
3015                for (int j=0; j<N; j++) {
3016                    final ResolveInfo ri = query.get(j);
3017                    if (!ri.activityInfo.applicationInfo.packageName
3018                            .equals(ai.applicationInfo.packageName)) {
3019                        continue;
3020                    }
3021                    if (!ri.activityInfo.name.equals(ai.name)) {
3022                        continue;
3023                    }
3024                    //  Found a persistent preference that can handle the intent.
3025                    if (DEBUG_PREFERRED || debug) {
3026                        Slog.v(TAG, "Returning persistent preferred activity: " +
3027                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3028                    }
3029                    return ri;
3030                }
3031            }
3032        }
3033        return null;
3034    }
3035
3036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3037            List<ResolveInfo> query, int priority, boolean always,
3038            boolean removeMatches, boolean debug, int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        // writer
3041        synchronized (mPackages) {
3042            if (intent.getSelector() != null) {
3043                intent = intent.getSelector();
3044            }
3045            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3046
3047            // Try to find a matching persistent preferred activity.
3048            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3049                    debug, userId);
3050
3051            // If a persistent preferred activity matched, use it.
3052            if (pri != null) {
3053                return pri;
3054            }
3055
3056            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3057            // Get the list of preferred activities that handle the intent
3058            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3059            List<PreferredActivity> prefs = pir != null
3060                    ? pir.queryIntent(intent, resolvedType,
3061                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3062                    : null;
3063            if (prefs != null && prefs.size() > 0) {
3064                boolean changed = false;
3065                try {
3066                    // First figure out how good the original match set is.
3067                    // We will only allow preferred activities that came
3068                    // from the same match quality.
3069                    int match = 0;
3070
3071                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3072
3073                    final int N = query.size();
3074                    for (int j=0; j<N; j++) {
3075                        final ResolveInfo ri = query.get(j);
3076                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3077                                + ": 0x" + Integer.toHexString(match));
3078                        if (ri.match > match) {
3079                            match = ri.match;
3080                        }
3081                    }
3082
3083                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3084                            + Integer.toHexString(match));
3085
3086                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3087                    final int M = prefs.size();
3088                    for (int i=0; i<M; i++) {
3089                        final PreferredActivity pa = prefs.get(i);
3090                        if (DEBUG_PREFERRED || debug) {
3091                            Slog.v(TAG, "Checking PreferredActivity ds="
3092                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3093                                    + "\n  component=" + pa.mPref.mComponent);
3094                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                        }
3096                        if (pa.mPref.mMatch != match) {
3097                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3098                                    + Integer.toHexString(pa.mPref.mMatch));
3099                            continue;
3100                        }
3101                        // If it's not an "always" type preferred activity and that's what we're
3102                        // looking for, skip it.
3103                        if (always && !pa.mPref.mAlways) {
3104                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3105                            continue;
3106                        }
3107                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3108                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3109                        if (DEBUG_PREFERRED || debug) {
3110                            Slog.v(TAG, "Found preferred activity:");
3111                            if (ai != null) {
3112                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3113                            } else {
3114                                Slog.v(TAG, "  null");
3115                            }
3116                        }
3117                        if (ai == null) {
3118                            // This previously registered preferred activity
3119                            // component is no longer known.  Most likely an update
3120                            // to the app was installed and in the new version this
3121                            // component no longer exists.  Clean it up by removing
3122                            // it from the preferred activities list, and skip it.
3123                            Slog.w(TAG, "Removing dangling preferred activity: "
3124                                    + pa.mPref.mComponent);
3125                            pir.removeFilter(pa);
3126                            changed = true;
3127                            continue;
3128                        }
3129                        for (int j=0; j<N; j++) {
3130                            final ResolveInfo ri = query.get(j);
3131                            if (!ri.activityInfo.applicationInfo.packageName
3132                                    .equals(ai.applicationInfo.packageName)) {
3133                                continue;
3134                            }
3135                            if (!ri.activityInfo.name.equals(ai.name)) {
3136                                continue;
3137                            }
3138
3139                            if (removeMatches) {
3140                                pir.removeFilter(pa);
3141                                changed = true;
3142                                if (DEBUG_PREFERRED) {
3143                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3144                                }
3145                                break;
3146                            }
3147
3148                            // Okay we found a previously set preferred or last chosen app.
3149                            // If the result set is different from when this
3150                            // was created, we need to clear it and re-ask the
3151                            // user their preference, if we're looking for an "always" type entry.
3152                            if (always && !pa.mPref.sameSet(query, priority)) {
3153                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3154                                        + intent + " type " + resolvedType);
3155                                if (DEBUG_PREFERRED) {
3156                                    Slog.v(TAG, "Removing preferred activity since set changed "
3157                                            + pa.mPref.mComponent);
3158                                }
3159                                pir.removeFilter(pa);
3160                                // Re-add the filter as a "last chosen" entry (!always)
3161                                PreferredActivity lastChosen = new PreferredActivity(
3162                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3163                                pir.addFilter(lastChosen);
3164                                changed = true;
3165                                return null;
3166                            }
3167
3168                            // Yay! Either the set matched or we're looking for the last chosen
3169                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3170                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3171                            return ri;
3172                        }
3173                    }
3174                } finally {
3175                    if (changed) {
3176                        if (DEBUG_PREFERRED) {
3177                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3178                        }
3179                        mSettings.writePackageRestrictionsLPr(userId);
3180                    }
3181                }
3182            }
3183        }
3184        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3185        return null;
3186    }
3187
3188    /*
3189     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3190     */
3191    @Override
3192    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3193            int targetUserId) {
3194        mContext.enforceCallingOrSelfPermission(
3195                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3196        List<CrossProfileIntentFilter> matches =
3197                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3198        if (matches != null) {
3199            int size = matches.size();
3200            for (int i = 0; i < size; i++) {
3201                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3202            }
3203        }
3204        ArrayList<String> packageNames = null;
3205        SparseArray<ArrayList<String>> fromSource =
3206                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3207        if (fromSource != null) {
3208            packageNames = fromSource.get(targetUserId);
3209            if (packageNames != null) {
3210                // We need the package name, so we try to resolve with the loosest flags possible
3211                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3212                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3213                int count = resolveInfos.size();
3214                for (int i = 0; i < count; i++) {
3215                    ResolveInfo resolveInfo = resolveInfos.get(i);
3216                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3217                        return true;
3218                    }
3219                }
3220            }
3221        }
3222        return false;
3223    }
3224
3225    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3226            String resolvedType, int userId) {
3227        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3228        if (resolver != null) {
3229            return resolver.queryIntent(intent, resolvedType, false, userId);
3230        }
3231        return null;
3232    }
3233
3234    @Override
3235    public List<ResolveInfo> queryIntentActivities(Intent intent,
3236            String resolvedType, int flags, int userId) {
3237        if (!sUserManager.exists(userId)) return Collections.emptyList();
3238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3239        ComponentName comp = intent.getComponent();
3240        if (comp == null) {
3241            if (intent.getSelector() != null) {
3242                intent = intent.getSelector();
3243                comp = intent.getComponent();
3244            }
3245        }
3246
3247        if (comp != null) {
3248            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3249            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3250            if (ai != null) {
3251                final ResolveInfo ri = new ResolveInfo();
3252                ri.activityInfo = ai;
3253                list.add(ri);
3254            }
3255            return list;
3256        }
3257
3258        // reader
3259        synchronized (mPackages) {
3260            final String pkgName = intent.getPackage();
3261            if (pkgName == null) {
3262                ResolveInfo resolveInfo = null;
3263
3264                // Check if the intent needs to be forwarded to another user for this package
3265                ArrayList<ResolveInfo> crossProfileResult =
3266                        queryIntentActivitiesCrossProfilePackage(
3267                                intent, resolvedType, flags, userId);
3268                if (!crossProfileResult.isEmpty()) {
3269                    // Skip the current profile
3270                    return crossProfileResult;
3271                }
3272                List<CrossProfileIntentFilter> matchingFilters =
3273                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3274                // Check for results that need to skip the current profile.
3275                resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3276                        resolvedType, flags, userId);
3277                if (resolveInfo != null) {
3278                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3279                    result.add(resolveInfo);
3280                    return result;
3281                }
3282                // Check for cross profile results.
3283                resolveInfo = queryCrossProfileIntents(
3284                        matchingFilters, intent, resolvedType, flags, userId);
3285
3286                // Check for results in the current profile.
3287                List<ResolveInfo> result = mActivities.queryIntent(
3288                        intent, resolvedType, flags, userId);
3289                if (resolveInfo != null) {
3290                    result.add(resolveInfo);
3291                    Collections.sort(result, mResolvePrioritySorter);
3292                }
3293                return result;
3294            }
3295            final PackageParser.Package pkg = mPackages.get(pkgName);
3296            if (pkg != null) {
3297                ArrayList<ResolveInfo> crossProfileResult =
3298                        queryIntentActivitiesCrossProfilePackage(
3299                                intent, resolvedType, flags, userId, pkg, pkgName);
3300                if (!crossProfileResult.isEmpty()) {
3301                    // Skip the current profile
3302                    return crossProfileResult;
3303                }
3304                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3305                        pkg.activities, userId);
3306            }
3307            return new ArrayList<ResolveInfo>();
3308        }
3309    }
3310
3311    private ResolveInfo querySkipCurrentProfileIntents(
3312            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3313            int flags, int sourceUserId) {
3314        if (matchingFilters != null) {
3315            int size = matchingFilters.size();
3316            for (int i = 0; i < size; i ++) {
3317                CrossProfileIntentFilter filter = matchingFilters.get(i);
3318                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3319                    // Checking if there are activities in the target user that can handle the
3320                    // intent.
3321                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3322                            flags, sourceUserId);
3323                    if (resolveInfo != null) {
3324                        return resolveInfo;
3325                    }
3326                }
3327            }
3328        }
3329        return null;
3330    }
3331
3332    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3333            Intent intent, String resolvedType, int flags, int userId) {
3334        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3335        SparseArray<ArrayList<String>> sourceForwardingInfo =
3336                mSettings.mCrossProfilePackageInfo.get(userId);
3337        if (sourceForwardingInfo != null) {
3338            int NI = sourceForwardingInfo.size();
3339            for (int i = 0; i < NI; i++) {
3340                int targetUserId = sourceForwardingInfo.keyAt(i);
3341                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3342                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3343                        intent, resolvedType, flags, targetUserId);
3344                int NJ = resolveInfos.size();
3345                for (int j = 0; j < NJ; j++) {
3346                    ResolveInfo resolveInfo = resolveInfos.get(j);
3347                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3348                        matchingResolveInfos.add(createForwardingResolveInfo(
3349                                resolveInfo.filter, userId, targetUserId));
3350                    }
3351                }
3352            }
3353        }
3354        return matchingResolveInfos;
3355    }
3356
3357    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3358            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3359            String packageName) {
3360        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3361        SparseArray<ArrayList<String>> sourceForwardingInfo =
3362                mSettings.mCrossProfilePackageInfo.get(userId);
3363        if (sourceForwardingInfo != null) {
3364            int NI = sourceForwardingInfo.size();
3365            for (int i = 0; i < NI; i++) {
3366                int targetUserId = sourceForwardingInfo.keyAt(i);
3367                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3368                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3369                            intent, resolvedType, flags, pkg.activities, targetUserId);
3370                    int NJ = resolveInfos.size();
3371                    for (int j = 0; j < NJ; j++) {
3372                        ResolveInfo resolveInfo = resolveInfos.get(j);
3373                        matchingResolveInfos.add(createForwardingResolveInfo(
3374                                resolveInfo.filter, userId, targetUserId));
3375                    }
3376                }
3377            }
3378        }
3379        return matchingResolveInfos;
3380    }
3381
3382    // Return matching ResolveInfo if any for skip current profile intent filters.
3383    private ResolveInfo queryCrossProfileIntents(
3384            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3385            int flags, int sourceUserId) {
3386        if (matchingFilters != null) {
3387            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3388            // match the same intent. For performance reasons, it is better not to
3389            // run queryIntent twice for the same userId
3390            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3391            int size = matchingFilters.size();
3392            for (int i = 0; i < size; i++) {
3393                CrossProfileIntentFilter filter = matchingFilters.get(i);
3394                int targetUserId = filter.getTargetUserId();
3395                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3396                        && !alreadyTriedUserIds.get(targetUserId)) {
3397                    // Checking if there are activities in the target user that can handle the
3398                    // intent.
3399                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3400                            flags, sourceUserId);
3401                    if (resolveInfo != null) return resolveInfo;
3402                    alreadyTriedUserIds.put(targetUserId, true);
3403                }
3404            }
3405        }
3406        return null;
3407    }
3408
3409    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3410            String resolvedType, int flags, int sourceUserId) {
3411        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3412                resolvedType, flags, filter.getTargetUserId());
3413        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3414            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3415        }
3416        return null;
3417    }
3418
3419    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3420            int sourceUserId, int targetUserId) {
3421        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3422        String className;
3423        if (targetUserId == UserHandle.USER_OWNER) {
3424            className = FORWARD_INTENT_TO_USER_OWNER;
3425        } else {
3426            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3427        }
3428        ComponentName forwardingActivityComponentName = new ComponentName(
3429                mAndroidApplication.packageName, className);
3430        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3431                sourceUserId);
3432        if (targetUserId == UserHandle.USER_OWNER) {
3433            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3434            forwardingResolveInfo.noResourceId = true;
3435        }
3436        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3437        forwardingResolveInfo.priority = 0;
3438        forwardingResolveInfo.preferredOrder = 0;
3439        forwardingResolveInfo.match = 0;
3440        forwardingResolveInfo.isDefault = true;
3441        forwardingResolveInfo.filter = filter;
3442        forwardingResolveInfo.targetUserId = targetUserId;
3443        return forwardingResolveInfo;
3444    }
3445
3446    @Override
3447    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3448            Intent[] specifics, String[] specificTypes, Intent intent,
3449            String resolvedType, int flags, int userId) {
3450        if (!sUserManager.exists(userId)) return Collections.emptyList();
3451        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3452                false, "query intent activity options");
3453        final String resultsAction = intent.getAction();
3454
3455        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3456                | PackageManager.GET_RESOLVED_FILTER, userId);
3457
3458        if (DEBUG_INTENT_MATCHING) {
3459            Log.v(TAG, "Query " + intent + ": " + results);
3460        }
3461
3462        int specificsPos = 0;
3463        int N;
3464
3465        // todo: note that the algorithm used here is O(N^2).  This
3466        // isn't a problem in our current environment, but if we start running
3467        // into situations where we have more than 5 or 10 matches then this
3468        // should probably be changed to something smarter...
3469
3470        // First we go through and resolve each of the specific items
3471        // that were supplied, taking care of removing any corresponding
3472        // duplicate items in the generic resolve list.
3473        if (specifics != null) {
3474            for (int i=0; i<specifics.length; i++) {
3475                final Intent sintent = specifics[i];
3476                if (sintent == null) {
3477                    continue;
3478                }
3479
3480                if (DEBUG_INTENT_MATCHING) {
3481                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3482                }
3483
3484                String action = sintent.getAction();
3485                if (resultsAction != null && resultsAction.equals(action)) {
3486                    // If this action was explicitly requested, then don't
3487                    // remove things that have it.
3488                    action = null;
3489                }
3490
3491                ResolveInfo ri = null;
3492                ActivityInfo ai = null;
3493
3494                ComponentName comp = sintent.getComponent();
3495                if (comp == null) {
3496                    ri = resolveIntent(
3497                        sintent,
3498                        specificTypes != null ? specificTypes[i] : null,
3499                            flags, userId);
3500                    if (ri == null) {
3501                        continue;
3502                    }
3503                    if (ri == mResolveInfo) {
3504                        // ACK!  Must do something better with this.
3505                    }
3506                    ai = ri.activityInfo;
3507                    comp = new ComponentName(ai.applicationInfo.packageName,
3508                            ai.name);
3509                } else {
3510                    ai = getActivityInfo(comp, flags, userId);
3511                    if (ai == null) {
3512                        continue;
3513                    }
3514                }
3515
3516                // Look for any generic query activities that are duplicates
3517                // of this specific one, and remove them from the results.
3518                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3519                N = results.size();
3520                int j;
3521                for (j=specificsPos; j<N; j++) {
3522                    ResolveInfo sri = results.get(j);
3523                    if ((sri.activityInfo.name.equals(comp.getClassName())
3524                            && sri.activityInfo.applicationInfo.packageName.equals(
3525                                    comp.getPackageName()))
3526                        || (action != null && sri.filter.matchAction(action))) {
3527                        results.remove(j);
3528                        if (DEBUG_INTENT_MATCHING) Log.v(
3529                            TAG, "Removing duplicate item from " + j
3530                            + " due to specific " + specificsPos);
3531                        if (ri == null) {
3532                            ri = sri;
3533                        }
3534                        j--;
3535                        N--;
3536                    }
3537                }
3538
3539                // Add this specific item to its proper place.
3540                if (ri == null) {
3541                    ri = new ResolveInfo();
3542                    ri.activityInfo = ai;
3543                }
3544                results.add(specificsPos, ri);
3545                ri.specificIndex = i;
3546                specificsPos++;
3547            }
3548        }
3549
3550        // Now we go through the remaining generic results and remove any
3551        // duplicate actions that are found here.
3552        N = results.size();
3553        for (int i=specificsPos; i<N-1; i++) {
3554            final ResolveInfo rii = results.get(i);
3555            if (rii.filter == null) {
3556                continue;
3557            }
3558
3559            // Iterate over all of the actions of this result's intent
3560            // filter...  typically this should be just one.
3561            final Iterator<String> it = rii.filter.actionsIterator();
3562            if (it == null) {
3563                continue;
3564            }
3565            while (it.hasNext()) {
3566                final String action = it.next();
3567                if (resultsAction != null && resultsAction.equals(action)) {
3568                    // If this action was explicitly requested, then don't
3569                    // remove things that have it.
3570                    continue;
3571                }
3572                for (int j=i+1; j<N; j++) {
3573                    final ResolveInfo rij = results.get(j);
3574                    if (rij.filter != null && rij.filter.hasAction(action)) {
3575                        results.remove(j);
3576                        if (DEBUG_INTENT_MATCHING) Log.v(
3577                            TAG, "Removing duplicate item from " + j
3578                            + " due to action " + action + " at " + i);
3579                        j--;
3580                        N--;
3581                    }
3582                }
3583            }
3584
3585            // If the caller didn't request filter information, drop it now
3586            // so we don't have to marshall/unmarshall it.
3587            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3588                rii.filter = null;
3589            }
3590        }
3591
3592        // Filter out the caller activity if so requested.
3593        if (caller != null) {
3594            N = results.size();
3595            for (int i=0; i<N; i++) {
3596                ActivityInfo ainfo = results.get(i).activityInfo;
3597                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3598                        && caller.getClassName().equals(ainfo.name)) {
3599                    results.remove(i);
3600                    break;
3601                }
3602            }
3603        }
3604
3605        // If the caller didn't request filter information,
3606        // drop them now so we don't have to
3607        // marshall/unmarshall it.
3608        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3609            N = results.size();
3610            for (int i=0; i<N; i++) {
3611                results.get(i).filter = null;
3612            }
3613        }
3614
3615        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3616        return results;
3617    }
3618
3619    @Override
3620    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3621            int userId) {
3622        if (!sUserManager.exists(userId)) return Collections.emptyList();
3623        ComponentName comp = intent.getComponent();
3624        if (comp == null) {
3625            if (intent.getSelector() != null) {
3626                intent = intent.getSelector();
3627                comp = intent.getComponent();
3628            }
3629        }
3630        if (comp != null) {
3631            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3632            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3633            if (ai != null) {
3634                ResolveInfo ri = new ResolveInfo();
3635                ri.activityInfo = ai;
3636                list.add(ri);
3637            }
3638            return list;
3639        }
3640
3641        // reader
3642        synchronized (mPackages) {
3643            String pkgName = intent.getPackage();
3644            if (pkgName == null) {
3645                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3646            }
3647            final PackageParser.Package pkg = mPackages.get(pkgName);
3648            if (pkg != null) {
3649                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3650                        userId);
3651            }
3652            return null;
3653        }
3654    }
3655
3656    @Override
3657    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3658        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3659        if (!sUserManager.exists(userId)) return null;
3660        if (query != null) {
3661            if (query.size() >= 1) {
3662                // If there is more than one service with the same priority,
3663                // just arbitrarily pick the first one.
3664                return query.get(0);
3665            }
3666        }
3667        return null;
3668    }
3669
3670    @Override
3671    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3672            int userId) {
3673        if (!sUserManager.exists(userId)) return Collections.emptyList();
3674        ComponentName comp = intent.getComponent();
3675        if (comp == null) {
3676            if (intent.getSelector() != null) {
3677                intent = intent.getSelector();
3678                comp = intent.getComponent();
3679            }
3680        }
3681        if (comp != null) {
3682            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3683            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3684            if (si != null) {
3685                final ResolveInfo ri = new ResolveInfo();
3686                ri.serviceInfo = si;
3687                list.add(ri);
3688            }
3689            return list;
3690        }
3691
3692        // reader
3693        synchronized (mPackages) {
3694            String pkgName = intent.getPackage();
3695            if (pkgName == null) {
3696                return mServices.queryIntent(intent, resolvedType, flags, userId);
3697            }
3698            final PackageParser.Package pkg = mPackages.get(pkgName);
3699            if (pkg != null) {
3700                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3701                        userId);
3702            }
3703            return null;
3704        }
3705    }
3706
3707    @Override
3708    public List<ResolveInfo> queryIntentContentProviders(
3709            Intent intent, String resolvedType, int flags, int userId) {
3710        if (!sUserManager.exists(userId)) return Collections.emptyList();
3711        ComponentName comp = intent.getComponent();
3712        if (comp == null) {
3713            if (intent.getSelector() != null) {
3714                intent = intent.getSelector();
3715                comp = intent.getComponent();
3716            }
3717        }
3718        if (comp != null) {
3719            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3720            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3721            if (pi != null) {
3722                final ResolveInfo ri = new ResolveInfo();
3723                ri.providerInfo = pi;
3724                list.add(ri);
3725            }
3726            return list;
3727        }
3728
3729        // reader
3730        synchronized (mPackages) {
3731            String pkgName = intent.getPackage();
3732            if (pkgName == null) {
3733                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3734            }
3735            final PackageParser.Package pkg = mPackages.get(pkgName);
3736            if (pkg != null) {
3737                return mProviders.queryIntentForPackage(
3738                        intent, resolvedType, flags, pkg.providers, userId);
3739            }
3740            return null;
3741        }
3742    }
3743
3744    @Override
3745    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3746        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3747
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3749
3750        // writer
3751        synchronized (mPackages) {
3752            ArrayList<PackageInfo> list;
3753            if (listUninstalled) {
3754                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3755                for (PackageSetting ps : mSettings.mPackages.values()) {
3756                    PackageInfo pi;
3757                    if (ps.pkg != null) {
3758                        pi = generatePackageInfo(ps.pkg, flags, userId);
3759                    } else {
3760                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3761                    }
3762                    if (pi != null) {
3763                        list.add(pi);
3764                    }
3765                }
3766            } else {
3767                list = new ArrayList<PackageInfo>(mPackages.size());
3768                for (PackageParser.Package p : mPackages.values()) {
3769                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3770                    if (pi != null) {
3771                        list.add(pi);
3772                    }
3773                }
3774            }
3775
3776            return new ParceledListSlice<PackageInfo>(list);
3777        }
3778    }
3779
3780    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3781            String[] permissions, boolean[] tmp, int flags, int userId) {
3782        int numMatch = 0;
3783        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3784        for (int i=0; i<permissions.length; i++) {
3785            if (gp.grantedPermissions.contains(permissions[i])) {
3786                tmp[i] = true;
3787                numMatch++;
3788            } else {
3789                tmp[i] = false;
3790            }
3791        }
3792        if (numMatch == 0) {
3793            return;
3794        }
3795        PackageInfo pi;
3796        if (ps.pkg != null) {
3797            pi = generatePackageInfo(ps.pkg, flags, userId);
3798        } else {
3799            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3800        }
3801        // The above might return null in cases of uninstalled apps or install-state
3802        // skew across users/profiles.
3803        if (pi != null) {
3804            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3805                if (numMatch == permissions.length) {
3806                    pi.requestedPermissions = permissions;
3807                } else {
3808                    pi.requestedPermissions = new String[numMatch];
3809                    numMatch = 0;
3810                    for (int i=0; i<permissions.length; i++) {
3811                        if (tmp[i]) {
3812                            pi.requestedPermissions[numMatch] = permissions[i];
3813                            numMatch++;
3814                        }
3815                    }
3816                }
3817            }
3818            list.add(pi);
3819        }
3820    }
3821
3822    @Override
3823    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3824            String[] permissions, int flags, int userId) {
3825        if (!sUserManager.exists(userId)) return null;
3826        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3827
3828        // writer
3829        synchronized (mPackages) {
3830            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3831            boolean[] tmpBools = new boolean[permissions.length];
3832            if (listUninstalled) {
3833                for (PackageSetting ps : mSettings.mPackages.values()) {
3834                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3835                }
3836            } else {
3837                for (PackageParser.Package pkg : mPackages.values()) {
3838                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3839                    if (ps != null) {
3840                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3841                                userId);
3842                    }
3843                }
3844            }
3845
3846            return new ParceledListSlice<PackageInfo>(list);
3847        }
3848    }
3849
3850    @Override
3851    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3852        if (!sUserManager.exists(userId)) return null;
3853        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3854
3855        // writer
3856        synchronized (mPackages) {
3857            ArrayList<ApplicationInfo> list;
3858            if (listUninstalled) {
3859                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3860                for (PackageSetting ps : mSettings.mPackages.values()) {
3861                    ApplicationInfo ai;
3862                    if (ps.pkg != null) {
3863                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3864                                ps.readUserState(userId), userId);
3865                    } else {
3866                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3867                    }
3868                    if (ai != null) {
3869                        list.add(ai);
3870                    }
3871                }
3872            } else {
3873                list = new ArrayList<ApplicationInfo>(mPackages.size());
3874                for (PackageParser.Package p : mPackages.values()) {
3875                    if (p.mExtras != null) {
3876                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3877                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3878                        if (ai != null) {
3879                            list.add(ai);
3880                        }
3881                    }
3882                }
3883            }
3884
3885            return new ParceledListSlice<ApplicationInfo>(list);
3886        }
3887    }
3888
3889    public List<ApplicationInfo> getPersistentApplications(int flags) {
3890        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3891
3892        // reader
3893        synchronized (mPackages) {
3894            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3895            final int userId = UserHandle.getCallingUserId();
3896            while (i.hasNext()) {
3897                final PackageParser.Package p = i.next();
3898                if (p.applicationInfo != null
3899                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3900                        && (!mSafeMode || isSystemApp(p))) {
3901                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3902                    if (ps != null) {
3903                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3904                                ps.readUserState(userId), userId);
3905                        if (ai != null) {
3906                            finalList.add(ai);
3907                        }
3908                    }
3909                }
3910            }
3911        }
3912
3913        return finalList;
3914    }
3915
3916    @Override
3917    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3918        if (!sUserManager.exists(userId)) return null;
3919        // reader
3920        synchronized (mPackages) {
3921            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3922            PackageSetting ps = provider != null
3923                    ? mSettings.mPackages.get(provider.owner.packageName)
3924                    : null;
3925            return ps != null
3926                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3927                    && (!mSafeMode || (provider.info.applicationInfo.flags
3928                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3929                    ? PackageParser.generateProviderInfo(provider, flags,
3930                            ps.readUserState(userId), userId)
3931                    : null;
3932        }
3933    }
3934
3935    /**
3936     * @deprecated
3937     */
3938    @Deprecated
3939    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3940        // reader
3941        synchronized (mPackages) {
3942            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3943                    .entrySet().iterator();
3944            final int userId = UserHandle.getCallingUserId();
3945            while (i.hasNext()) {
3946                Map.Entry<String, PackageParser.Provider> entry = i.next();
3947                PackageParser.Provider p = entry.getValue();
3948                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3949
3950                if (ps != null && p.syncable
3951                        && (!mSafeMode || (p.info.applicationInfo.flags
3952                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3953                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3954                            ps.readUserState(userId), userId);
3955                    if (info != null) {
3956                        outNames.add(entry.getKey());
3957                        outInfo.add(info);
3958                    }
3959                }
3960            }
3961        }
3962    }
3963
3964    @Override
3965    public List<ProviderInfo> queryContentProviders(String processName,
3966            int uid, int flags) {
3967        ArrayList<ProviderInfo> finalList = null;
3968        // reader
3969        synchronized (mPackages) {
3970            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3971            final int userId = processName != null ?
3972                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3973            while (i.hasNext()) {
3974                final PackageParser.Provider p = i.next();
3975                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3976                if (ps != null && p.info.authority != null
3977                        && (processName == null
3978                                || (p.info.processName.equals(processName)
3979                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3980                        && mSettings.isEnabledLPr(p.info, flags, userId)
3981                        && (!mSafeMode
3982                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3983                    if (finalList == null) {
3984                        finalList = new ArrayList<ProviderInfo>(3);
3985                    }
3986                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3987                            ps.readUserState(userId), userId);
3988                    if (info != null) {
3989                        finalList.add(info);
3990                    }
3991                }
3992            }
3993        }
3994
3995        if (finalList != null) {
3996            Collections.sort(finalList, mProviderInitOrderSorter);
3997        }
3998
3999        return finalList;
4000    }
4001
4002    @Override
4003    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4004            int flags) {
4005        // reader
4006        synchronized (mPackages) {
4007            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4008            return PackageParser.generateInstrumentationInfo(i, flags);
4009        }
4010    }
4011
4012    @Override
4013    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4014            int flags) {
4015        ArrayList<InstrumentationInfo> finalList =
4016            new ArrayList<InstrumentationInfo>();
4017
4018        // reader
4019        synchronized (mPackages) {
4020            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4021            while (i.hasNext()) {
4022                final PackageParser.Instrumentation p = i.next();
4023                if (targetPackage == null
4024                        || targetPackage.equals(p.info.targetPackage)) {
4025                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4026                            flags);
4027                    if (ii != null) {
4028                        finalList.add(ii);
4029                    }
4030                }
4031            }
4032        }
4033
4034        return finalList;
4035    }
4036
4037    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4038        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4039        if (overlays == null) {
4040            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4041            return;
4042        }
4043        for (PackageParser.Package opkg : overlays.values()) {
4044            // Not much to do if idmap fails: we already logged the error
4045            // and we certainly don't want to abort installation of pkg simply
4046            // because an overlay didn't fit properly. For these reasons,
4047            // ignore the return value of createIdmapForPackagePairLI.
4048            createIdmapForPackagePairLI(pkg, opkg);
4049        }
4050    }
4051
4052    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4053            PackageParser.Package opkg) {
4054        if (!opkg.mTrustedOverlay) {
4055            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4056                    opkg.baseCodePath + ": overlay not trusted");
4057            return false;
4058        }
4059        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4060        if (overlaySet == null) {
4061            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4062                    opkg.baseCodePath + " but target package has no known overlays");
4063            return false;
4064        }
4065        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4066        // TODO: generate idmap for split APKs
4067        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4068            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4069                    + opkg.baseCodePath);
4070            return false;
4071        }
4072        PackageParser.Package[] overlayArray =
4073            overlaySet.values().toArray(new PackageParser.Package[0]);
4074        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4075            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4076                return p1.mOverlayPriority - p2.mOverlayPriority;
4077            }
4078        };
4079        Arrays.sort(overlayArray, cmp);
4080
4081        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4082        int i = 0;
4083        for (PackageParser.Package p : overlayArray) {
4084            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4085        }
4086        return true;
4087    }
4088
4089    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4090        final File[] files = dir.listFiles();
4091        if (ArrayUtils.isEmpty(files)) {
4092            Log.d(TAG, "No files in app dir " + dir);
4093            return;
4094        }
4095
4096        if (DEBUG_PACKAGE_SCANNING) {
4097            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4098                    + " flags=0x" + Integer.toHexString(parseFlags));
4099        }
4100
4101        for (File file : files) {
4102            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4103                    && !PackageInstallerService.isStageName(file.getName());
4104            if (!isPackage) {
4105                // Ignore entries which are not packages
4106                continue;
4107            }
4108            try {
4109                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4110                        scanFlags, currentTime, null);
4111            } catch (PackageManagerException e) {
4112                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4113
4114                // Delete invalid userdata apps
4115                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4116                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4117                    Slog.w(TAG, "Deleting invalid package at " + file);
4118                    if (file.isDirectory()) {
4119                        FileUtils.deleteContents(file);
4120                    }
4121                    file.delete();
4122                }
4123            }
4124        }
4125    }
4126
4127    private static File getSettingsProblemFile() {
4128        File dataDir = Environment.getDataDirectory();
4129        File systemDir = new File(dataDir, "system");
4130        File fname = new File(systemDir, "uiderrors.txt");
4131        return fname;
4132    }
4133
4134    static void reportSettingsProblem(int priority, String msg) {
4135        try {
4136            File fname = getSettingsProblemFile();
4137            FileOutputStream out = new FileOutputStream(fname, true);
4138            PrintWriter pw = new FastPrintWriter(out);
4139            SimpleDateFormat formatter = new SimpleDateFormat();
4140            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4141            pw.println(dateString + ": " + msg);
4142            pw.close();
4143            FileUtils.setPermissions(
4144                    fname.toString(),
4145                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4146                    -1, -1);
4147        } catch (java.io.IOException e) {
4148        }
4149        Slog.println(priority, TAG, msg);
4150    }
4151
4152    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4153            PackageParser.Package pkg, File srcFile, int parseFlags)
4154            throws PackageManagerException {
4155        if (ps != null
4156                && ps.codePath.equals(srcFile)
4157                && ps.timeStamp == srcFile.lastModified()
4158                && !isCompatSignatureUpdateNeeded(pkg)) {
4159            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4160            if (ps.signatures.mSignatures != null
4161                    && ps.signatures.mSignatures.length != 0
4162                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4163                // Optimization: reuse the existing cached certificates
4164                // if the package appears to be unchanged.
4165                pkg.mSignatures = ps.signatures.mSignatures;
4166                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4167                synchronized (mPackages) {
4168                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4169                }
4170                return;
4171            }
4172
4173            Slog.w(TAG, "PackageSetting for " + ps.name
4174                    + " is missing signatures.  Collecting certs again to recover them.");
4175        } else {
4176            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4177        }
4178
4179        try {
4180            pp.collectCertificates(pkg, parseFlags);
4181            pp.collectManifestDigest(pkg);
4182        } catch (PackageParserException e) {
4183            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4184                    + pkg.packageName + ": " + e.getMessage());
4185        }
4186    }
4187
4188    /*
4189     *  Scan a package and return the newly parsed package.
4190     *  Returns null in case of errors and the error code is stored in mLastScanError
4191     */
4192    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4193            long currentTime, UserHandle user) throws PackageManagerException {
4194        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4195        parseFlags |= mDefParseFlags;
4196        PackageParser pp = new PackageParser();
4197        pp.setSeparateProcesses(mSeparateProcesses);
4198        pp.setOnlyCoreApps(mOnlyCore);
4199        pp.setDisplayMetrics(mMetrics);
4200
4201        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4202            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4203        }
4204
4205        final PackageParser.Package pkg;
4206        try {
4207            pkg = pp.parsePackage(scanFile, parseFlags);
4208        } catch (PackageParserException e) {
4209            throw new PackageManagerException(e.error,
4210                    "Failed to scan " + scanFile + ": " + e.getMessage());
4211        }
4212
4213        PackageSetting ps = null;
4214        PackageSetting updatedPkg;
4215        // reader
4216        synchronized (mPackages) {
4217            // Look to see if we already know about this package.
4218            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4219            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4220                // This package has been renamed to its original name.  Let's
4221                // use that.
4222                ps = mSettings.peekPackageLPr(oldName);
4223            }
4224            // If there was no original package, see one for the real package name.
4225            if (ps == null) {
4226                ps = mSettings.peekPackageLPr(pkg.packageName);
4227            }
4228            // Check to see if this package could be hiding/updating a system
4229            // package.  Must look for it either under the original or real
4230            // package name depending on our state.
4231            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4232            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4233        }
4234        boolean updatedPkgBetter = false;
4235        // First check if this is a system package that may involve an update
4236        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4237            if (ps != null && !ps.codePath.equals(scanFile)) {
4238                // The path has changed from what was last scanned...  check the
4239                // version of the new path against what we have stored to determine
4240                // what to do.
4241                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4242                if (pkg.mVersionCode < ps.versionCode) {
4243                    // The system package has been updated and the code path does not match
4244                    // Ignore entry. Skip it.
4245                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4246                            + " ignored: updated version " + ps.versionCode
4247                            + " better than this " + pkg.mVersionCode);
4248                    if (!updatedPkg.codePath.equals(scanFile)) {
4249                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4250                                + ps.name + " changing from " + updatedPkg.codePathString
4251                                + " to " + scanFile);
4252                        updatedPkg.codePath = scanFile;
4253                        updatedPkg.codePathString = scanFile.toString();
4254                        // This is the point at which we know that the system-disk APK
4255                        // for this package has moved during a reboot (e.g. due to an OTA),
4256                        // so we need to reevaluate it for privilege policy.
4257                        if (locationIsPrivileged(scanFile)) {
4258                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4259                        }
4260                    }
4261                    updatedPkg.pkg = pkg;
4262                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4263                } else {
4264                    // The current app on the system partition is better than
4265                    // what we have updated to on the data partition; switch
4266                    // back to the system partition version.
4267                    // At this point, its safely assumed that package installation for
4268                    // apps in system partition will go through. If not there won't be a working
4269                    // version of the app
4270                    // writer
4271                    synchronized (mPackages) {
4272                        // Just remove the loaded entries from package lists.
4273                        mPackages.remove(ps.name);
4274                    }
4275                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4276                            + "reverting from " + ps.codePathString
4277                            + ": new version " + pkg.mVersionCode
4278                            + " better than installed " + ps.versionCode);
4279
4280                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4281                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4282                            getAppDexInstructionSets(ps));
4283                    synchronized (mInstallLock) {
4284                        args.cleanUpResourcesLI();
4285                    }
4286                    synchronized (mPackages) {
4287                        mSettings.enableSystemPackageLPw(ps.name);
4288                    }
4289                    updatedPkgBetter = true;
4290                }
4291            }
4292        }
4293
4294        if (updatedPkg != null) {
4295            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4296            // initially
4297            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4298
4299            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4300            // flag set initially
4301            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4302                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4303            }
4304        }
4305
4306        // Verify certificates against what was last scanned
4307        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4308
4309        /*
4310         * A new system app appeared, but we already had a non-system one of the
4311         * same name installed earlier.
4312         */
4313        boolean shouldHideSystemApp = false;
4314        if (updatedPkg == null && ps != null
4315                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4316            /*
4317             * Check to make sure the signatures match first. If they don't,
4318             * wipe the installed application and its data.
4319             */
4320            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4321                    != PackageManager.SIGNATURE_MATCH) {
4322                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4323                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4324                ps = null;
4325            } else {
4326                /*
4327                 * If the newly-added system app is an older version than the
4328                 * already installed version, hide it. It will be scanned later
4329                 * and re-added like an update.
4330                 */
4331                if (pkg.mVersionCode < ps.versionCode) {
4332                    shouldHideSystemApp = true;
4333                } else {
4334                    /*
4335                     * The newly found system app is a newer version that the
4336                     * one previously installed. Simply remove the
4337                     * already-installed application and replace it with our own
4338                     * while keeping the application data.
4339                     */
4340                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4341                            + ps.codePathString + ": new version " + pkg.mVersionCode
4342                            + " better than installed " + ps.versionCode);
4343                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4344                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4345                            getAppDexInstructionSets(ps));
4346                    synchronized (mInstallLock) {
4347                        args.cleanUpResourcesLI();
4348                    }
4349                }
4350            }
4351        }
4352
4353        // The apk is forward locked (not public) if its code and resources
4354        // are kept in different files. (except for app in either system or
4355        // vendor path).
4356        // TODO grab this value from PackageSettings
4357        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4358            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4359                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4360            }
4361        }
4362
4363        // TODO: extend to support forward-locked splits
4364        String resourcePath = null;
4365        String baseResourcePath = null;
4366        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4367            if (ps != null && ps.resourcePathString != null) {
4368                resourcePath = ps.resourcePathString;
4369                baseResourcePath = ps.resourcePathString;
4370            } else {
4371                // Should not happen at all. Just log an error.
4372                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4373            }
4374        } else {
4375            resourcePath = pkg.codePath;
4376            baseResourcePath = pkg.baseCodePath;
4377        }
4378
4379        // Set application objects path explicitly.
4380        pkg.applicationInfo.setCodePath(pkg.codePath);
4381        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4382        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4383        pkg.applicationInfo.setResourcePath(resourcePath);
4384        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4385        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4386
4387        // Note that we invoke the following method only if we are about to unpack an application
4388        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4389                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4390
4391        /*
4392         * If the system app should be overridden by a previously installed
4393         * data, hide the system app now and let the /data/app scan pick it up
4394         * again.
4395         */
4396        if (shouldHideSystemApp) {
4397            synchronized (mPackages) {
4398                /*
4399                 * We have to grant systems permissions before we hide, because
4400                 * grantPermissions will assume the package update is trying to
4401                 * expand its permissions.
4402                 */
4403                grantPermissionsLPw(pkg, true);
4404                mSettings.disableSystemPackageLPw(pkg.packageName);
4405            }
4406        }
4407
4408        return scannedPkg;
4409    }
4410
4411    private static String fixProcessName(String defProcessName,
4412            String processName, int uid) {
4413        if (processName == null) {
4414            return defProcessName;
4415        }
4416        return processName;
4417    }
4418
4419    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4420            throws PackageManagerException {
4421        if (pkgSetting.signatures.mSignatures != null) {
4422            // Already existing package. Make sure signatures match
4423            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4424                    == PackageManager.SIGNATURE_MATCH;
4425            if (!match) {
4426                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4427                        == PackageManager.SIGNATURE_MATCH;
4428            }
4429            if (!match) {
4430                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4431                        + pkg.packageName + " signatures do not match the "
4432                        + "previously installed version; ignoring!");
4433            }
4434        }
4435
4436        // Check for shared user signatures
4437        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4438            // Already existing package. Make sure signatures match
4439            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4440                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4441            if (!match) {
4442                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4443                        == PackageManager.SIGNATURE_MATCH;
4444            }
4445            if (!match) {
4446                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4447                        "Package " + pkg.packageName
4448                        + " has no signatures that match those in shared user "
4449                        + pkgSetting.sharedUser.name + "; ignoring!");
4450            }
4451        }
4452    }
4453
4454    /**
4455     * Enforces that only the system UID or root's UID can call a method exposed
4456     * via Binder.
4457     *
4458     * @param message used as message if SecurityException is thrown
4459     * @throws SecurityException if the caller is not system or root
4460     */
4461    private static final void enforceSystemOrRoot(String message) {
4462        final int uid = Binder.getCallingUid();
4463        if (uid != Process.SYSTEM_UID && uid != 0) {
4464            throw new SecurityException(message);
4465        }
4466    }
4467
4468    @Override
4469    public void performBootDexOpt() {
4470        enforceSystemOrRoot("Only the system can request dexopt be performed");
4471
4472        final HashSet<PackageParser.Package> pkgs;
4473        synchronized (mPackages) {
4474            pkgs = mDeferredDexOpt;
4475            mDeferredDexOpt = null;
4476        }
4477
4478        if (pkgs != null) {
4479            // Filter out packages that aren't recently used.
4480            //
4481            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4482            // should do a full dexopt.
4483            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4484                // TODO: add a property to control this?
4485                long dexOptLRUThresholdInMinutes;
4486                if (mLazyDexOpt) {
4487                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4488                } else {
4489                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4490                }
4491                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4492
4493                int total = pkgs.size();
4494                int skipped = 0;
4495                long now = System.currentTimeMillis();
4496                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4497                    PackageParser.Package pkg = i.next();
4498                    long then = pkg.mLastPackageUsageTimeInMills;
4499                    if (then + dexOptLRUThresholdInMills < now) {
4500                        if (DEBUG_DEXOPT) {
4501                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4502                                  ((then == 0) ? "never" : new Date(then)));
4503                        }
4504                        i.remove();
4505                        skipped++;
4506                    }
4507                }
4508                if (DEBUG_DEXOPT) {
4509                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4510                }
4511            }
4512
4513            int i = 0;
4514            for (PackageParser.Package pkg : pkgs) {
4515                i++;
4516                if (DEBUG_DEXOPT) {
4517                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4518                          + ": " + pkg.packageName);
4519                }
4520                if (!isFirstBoot()) {
4521                    try {
4522                        ActivityManagerNative.getDefault().showBootMessage(
4523                                mContext.getResources().getString(
4524                                        R.string.android_upgrading_apk,
4525                                        i, pkgs.size()), true);
4526                    } catch (RemoteException e) {
4527                    }
4528                }
4529                PackageParser.Package p = pkg;
4530                synchronized (mInstallLock) {
4531                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4532                            true /* include dependencies */);
4533                }
4534            }
4535        }
4536    }
4537
4538    @Override
4539    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4540        return performDexOpt(packageName, instructionSet, false);
4541    }
4542
4543    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4544        if (info.primaryCpuAbi == null) {
4545            return getPreferredInstructionSet();
4546        }
4547
4548        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4549    }
4550
4551    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4552        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4553        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4554        if (!dexopt && !updateUsage) {
4555            // We aren't going to dexopt or update usage, so bail early.
4556            return false;
4557        }
4558        PackageParser.Package p;
4559        final String targetInstructionSet;
4560        synchronized (mPackages) {
4561            p = mPackages.get(packageName);
4562            if (p == null) {
4563                return false;
4564            }
4565            if (updateUsage) {
4566                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4567            }
4568            mPackageUsage.write(false);
4569            if (!dexopt) {
4570                // We aren't going to dexopt, so bail early.
4571                return false;
4572            }
4573
4574            targetInstructionSet = instructionSet != null ? instructionSet :
4575                    getPrimaryInstructionSet(p.applicationInfo);
4576            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4577                return false;
4578            }
4579        }
4580
4581        synchronized (mInstallLock) {
4582            final String[] instructionSets = new String[] { targetInstructionSet };
4583            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4584                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4585        }
4586    }
4587
4588    public HashSet<String> getPackagesThatNeedDexOpt() {
4589        HashSet<String> pkgs = null;
4590        synchronized (mPackages) {
4591            for (PackageParser.Package p : mPackages.values()) {
4592                if (DEBUG_DEXOPT) {
4593                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4594                }
4595                if (!p.mDexOptPerformed.isEmpty()) {
4596                    continue;
4597                }
4598                if (pkgs == null) {
4599                    pkgs = new HashSet<String>();
4600                }
4601                pkgs.add(p.packageName);
4602            }
4603        }
4604        return pkgs;
4605    }
4606
4607    public void shutdown() {
4608        mPackageUsage.write(true);
4609    }
4610
4611    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4612             boolean forceDex, boolean defer, HashSet<String> done) {
4613        for (int i=0; i<libs.size(); i++) {
4614            PackageParser.Package libPkg;
4615            String libName;
4616            synchronized (mPackages) {
4617                libName = libs.get(i);
4618                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4619                if (lib != null && lib.apk != null) {
4620                    libPkg = mPackages.get(lib.apk);
4621                } else {
4622                    libPkg = null;
4623                }
4624            }
4625            if (libPkg != null && !done.contains(libName)) {
4626                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4627            }
4628        }
4629    }
4630
4631    static final int DEX_OPT_SKIPPED = 0;
4632    static final int DEX_OPT_PERFORMED = 1;
4633    static final int DEX_OPT_DEFERRED = 2;
4634    static final int DEX_OPT_FAILED = -1;
4635
4636    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4637            boolean forceDex, boolean defer, HashSet<String> done) {
4638        final String[] instructionSets = targetInstructionSets != null ?
4639                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4640
4641        if (done != null) {
4642            done.add(pkg.packageName);
4643            if (pkg.usesLibraries != null) {
4644                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4645            }
4646            if (pkg.usesOptionalLibraries != null) {
4647                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4648            }
4649        }
4650
4651        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4652            return DEX_OPT_SKIPPED;
4653        }
4654
4655        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4656
4657        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4658        boolean performedDexOpt = false;
4659        // There are three basic cases here:
4660        // 1.) we need to dexopt, either because we are forced or it is needed
4661        // 2.) we are defering a needed dexopt
4662        // 3.) we are skipping an unneeded dexopt
4663        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4664        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4665            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4666                continue;
4667            }
4668
4669            for (String path : paths) {
4670                try {
4671                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4672                    // patckage or the one we find does not match the image checksum (i.e. it was
4673                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4674                    // odex file and it matches the checksum of the image but not its base address,
4675                    // meaning we need to move it.
4676                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4677                            pkg.packageName, dexCodeInstructionSet, defer);
4678                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4679                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4680                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4681                                + " vmSafeMode=" + vmSafeMode);
4682                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4683                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4684                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4685
4686                        if (ret < 0) {
4687                            // Don't bother running dexopt again if we failed, it will probably
4688                            // just result in an error again. Also, don't bother dexopting for other
4689                            // paths & ISAs.
4690                            return DEX_OPT_FAILED;
4691                        }
4692
4693                        performedDexOpt = true;
4694                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4695                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4696                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4697                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4698                                pkg.packageName, dexCodeInstructionSet);
4699
4700                        if (ret < 0) {
4701                            // Don't bother running patchoat again if we failed, it will probably
4702                            // just result in an error again. Also, don't bother dexopting for other
4703                            // paths & ISAs.
4704                            return DEX_OPT_FAILED;
4705                        }
4706
4707                        performedDexOpt = true;
4708                    }
4709
4710                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4711                    // paths and instruction sets. We'll deal with them all together when we process
4712                    // our list of deferred dexopts.
4713                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4714                        if (mDeferredDexOpt == null) {
4715                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4716                        }
4717                        mDeferredDexOpt.add(pkg);
4718                        return DEX_OPT_DEFERRED;
4719                    }
4720                } catch (FileNotFoundException e) {
4721                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4722                    return DEX_OPT_FAILED;
4723                } catch (IOException e) {
4724                    Slog.w(TAG, "IOException reading apk: " + path, e);
4725                    return DEX_OPT_FAILED;
4726                } catch (StaleDexCacheError e) {
4727                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4728                    return DEX_OPT_FAILED;
4729                } catch (Exception e) {
4730                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4731                    return DEX_OPT_FAILED;
4732                }
4733            }
4734
4735            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4736            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4737            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4738            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4739            // it.
4740            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4741        }
4742
4743        // If we've gotten here, we're sure that no error occurred and that we haven't
4744        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4745        // we've skipped all of them because they are up to date. In both cases this
4746        // package doesn't need dexopt any longer.
4747        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4748    }
4749
4750    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4751        if (info.primaryCpuAbi != null) {
4752            if (info.secondaryCpuAbi != null) {
4753                return new String[] {
4754                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4755                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4756            } else {
4757                return new String[] {
4758                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4759            }
4760        }
4761
4762        return new String[] { getPreferredInstructionSet() };
4763    }
4764
4765    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4766        if (ps.primaryCpuAbiString != null) {
4767            if (ps.secondaryCpuAbiString != null) {
4768                return new String[] {
4769                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4770                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4771            } else {
4772                return new String[] {
4773                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4774            }
4775        }
4776
4777        return new String[] { getPreferredInstructionSet() };
4778    }
4779
4780    private static String getPreferredInstructionSet() {
4781        if (sPreferredInstructionSet == null) {
4782            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4783        }
4784
4785        return sPreferredInstructionSet;
4786    }
4787
4788    private static List<String> getAllInstructionSets() {
4789        final String[] allAbis = Build.SUPPORTED_ABIS;
4790        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4791
4792        for (String abi : allAbis) {
4793            final String instructionSet = VMRuntime.getInstructionSet(abi);
4794            if (!allInstructionSets.contains(instructionSet)) {
4795                allInstructionSets.add(instructionSet);
4796            }
4797        }
4798
4799        return allInstructionSets;
4800    }
4801
4802    /**
4803     * Returns the instruction set that should be used to compile dex code. In the presence of
4804     * a native bridge this might be different than the one shared libraries use.
4805     */
4806    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4807        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4808        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4809    }
4810
4811    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4812        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4813        for (String instructionSet : instructionSets) {
4814            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4815        }
4816        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4817    }
4818
4819    @Override
4820    public void forceDexOpt(String packageName) {
4821        enforceSystemOrRoot("forceDexOpt");
4822
4823        PackageParser.Package pkg;
4824        synchronized (mPackages) {
4825            pkg = mPackages.get(packageName);
4826            if (pkg == null) {
4827                throw new IllegalArgumentException("Missing package: " + packageName);
4828            }
4829        }
4830
4831        synchronized (mInstallLock) {
4832            final String[] instructionSets = new String[] {
4833                    getPrimaryInstructionSet(pkg.applicationInfo) };
4834            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4835            if (res != DEX_OPT_PERFORMED) {
4836                throw new IllegalStateException("Failed to dexopt: " + res);
4837            }
4838        }
4839    }
4840
4841    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4842                                boolean forceDex, boolean defer, boolean inclDependencies) {
4843        HashSet<String> done;
4844        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4845            done = new HashSet<String>();
4846            done.add(pkg.packageName);
4847        } else {
4848            done = null;
4849        }
4850        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4851    }
4852
4853    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4854        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4855            Slog.w(TAG, "Unable to update from " + oldPkg.name
4856                    + " to " + newPkg.packageName
4857                    + ": old package not in system partition");
4858            return false;
4859        } else if (mPackages.get(oldPkg.name) != null) {
4860            Slog.w(TAG, "Unable to update from " + oldPkg.name
4861                    + " to " + newPkg.packageName
4862                    + ": old package still exists");
4863            return false;
4864        }
4865        return true;
4866    }
4867
4868    File getDataPathForUser(int userId) {
4869        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4870    }
4871
4872    private File getDataPathForPackage(String packageName, int userId) {
4873        /*
4874         * Until we fully support multiple users, return the directory we
4875         * previously would have. The PackageManagerTests will need to be
4876         * revised when this is changed back..
4877         */
4878        if (userId == 0) {
4879            return new File(mAppDataDir, packageName);
4880        } else {
4881            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4882                + File.separator + packageName);
4883        }
4884    }
4885
4886    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4887        int[] users = sUserManager.getUserIds();
4888        int res = mInstaller.install(packageName, uid, uid, seinfo);
4889        if (res < 0) {
4890            return res;
4891        }
4892        for (int user : users) {
4893            if (user != 0) {
4894                res = mInstaller.createUserData(packageName,
4895                        UserHandle.getUid(user, uid), user, seinfo);
4896                if (res < 0) {
4897                    return res;
4898                }
4899            }
4900        }
4901        return res;
4902    }
4903
4904    private int removeDataDirsLI(String packageName) {
4905        int[] users = sUserManager.getUserIds();
4906        int res = 0;
4907        for (int user : users) {
4908            int resInner = mInstaller.remove(packageName, user);
4909            if (resInner < 0) {
4910                res = resInner;
4911            }
4912        }
4913
4914        return res;
4915    }
4916
4917    private int deleteCodeCacheDirsLI(String packageName) {
4918        int[] users = sUserManager.getUserIds();
4919        int res = 0;
4920        for (int user : users) {
4921            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4922            if (resInner < 0) {
4923                res = resInner;
4924            }
4925        }
4926        return res;
4927    }
4928
4929    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4930            PackageParser.Package changingLib) {
4931        if (file.path != null) {
4932            usesLibraryFiles.add(file.path);
4933            return;
4934        }
4935        PackageParser.Package p = mPackages.get(file.apk);
4936        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4937            // If we are doing this while in the middle of updating a library apk,
4938            // then we need to make sure to use that new apk for determining the
4939            // dependencies here.  (We haven't yet finished committing the new apk
4940            // to the package manager state.)
4941            if (p == null || p.packageName.equals(changingLib.packageName)) {
4942                p = changingLib;
4943            }
4944        }
4945        if (p != null) {
4946            usesLibraryFiles.addAll(p.getAllCodePaths());
4947        }
4948    }
4949
4950    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4951            PackageParser.Package changingLib) throws PackageManagerException {
4952        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4953            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4954            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4955            for (int i=0; i<N; i++) {
4956                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4957                if (file == null) {
4958                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4959                            "Package " + pkg.packageName + " requires unavailable shared library "
4960                            + pkg.usesLibraries.get(i) + "; failing!");
4961                }
4962                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4963            }
4964            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4965            for (int i=0; i<N; i++) {
4966                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4967                if (file == null) {
4968                    Slog.w(TAG, "Package " + pkg.packageName
4969                            + " desires unavailable shared library "
4970                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4971                } else {
4972                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4973                }
4974            }
4975            N = usesLibraryFiles.size();
4976            if (N > 0) {
4977                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4978            } else {
4979                pkg.usesLibraryFiles = null;
4980            }
4981        }
4982    }
4983
4984    private static boolean hasString(List<String> list, List<String> which) {
4985        if (list == null) {
4986            return false;
4987        }
4988        for (int i=list.size()-1; i>=0; i--) {
4989            for (int j=which.size()-1; j>=0; j--) {
4990                if (which.get(j).equals(list.get(i))) {
4991                    return true;
4992                }
4993            }
4994        }
4995        return false;
4996    }
4997
4998    private void updateAllSharedLibrariesLPw() {
4999        for (PackageParser.Package pkg : mPackages.values()) {
5000            try {
5001                updateSharedLibrariesLPw(pkg, null);
5002            } catch (PackageManagerException e) {
5003                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5004            }
5005        }
5006    }
5007
5008    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5009            PackageParser.Package changingPkg) {
5010        ArrayList<PackageParser.Package> res = null;
5011        for (PackageParser.Package pkg : mPackages.values()) {
5012            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5013                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5014                if (res == null) {
5015                    res = new ArrayList<PackageParser.Package>();
5016                }
5017                res.add(pkg);
5018                try {
5019                    updateSharedLibrariesLPw(pkg, changingPkg);
5020                } catch (PackageManagerException e) {
5021                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5022                }
5023            }
5024        }
5025        return res;
5026    }
5027
5028    /**
5029     * Derive the value of the {@code cpuAbiOverride} based on the provided
5030     * value and an optional stored value from the package settings.
5031     */
5032    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5033        String cpuAbiOverride = null;
5034
5035        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5036            cpuAbiOverride = null;
5037        } else if (abiOverride != null) {
5038            cpuAbiOverride = abiOverride;
5039        } else if (settings != null) {
5040            cpuAbiOverride = settings.cpuAbiOverrideString;
5041        }
5042
5043        return cpuAbiOverride;
5044    }
5045
5046    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5047            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5048        final File scanFile = new File(pkg.codePath);
5049        if (pkg.applicationInfo.getCodePath() == null ||
5050                pkg.applicationInfo.getResourcePath() == null) {
5051            // Bail out. The resource and code paths haven't been set.
5052            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5053                    "Code and resource paths haven't been set correctly");
5054        }
5055
5056        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5057            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5058        }
5059
5060        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5061            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5062        }
5063
5064        if (mCustomResolverComponentName != null &&
5065                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5066            setUpCustomResolverActivity(pkg);
5067        }
5068
5069        if (pkg.packageName.equals("android")) {
5070            synchronized (mPackages) {
5071                if (mAndroidApplication != null) {
5072                    Slog.w(TAG, "*************************************************");
5073                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5074                    Slog.w(TAG, " file=" + scanFile);
5075                    Slog.w(TAG, "*************************************************");
5076                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5077                            "Core android package being redefined.  Skipping.");
5078                }
5079
5080                // Set up information for our fall-back user intent resolution activity.
5081                mPlatformPackage = pkg;
5082                pkg.mVersionCode = mSdkVersion;
5083                mAndroidApplication = pkg.applicationInfo;
5084
5085                if (!mResolverReplaced) {
5086                    mResolveActivity.applicationInfo = mAndroidApplication;
5087                    mResolveActivity.name = ResolverActivity.class.getName();
5088                    mResolveActivity.packageName = mAndroidApplication.packageName;
5089                    mResolveActivity.processName = "system:ui";
5090                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5091                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5092                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5093                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5094                    mResolveActivity.exported = true;
5095                    mResolveActivity.enabled = true;
5096                    mResolveInfo.activityInfo = mResolveActivity;
5097                    mResolveInfo.priority = 0;
5098                    mResolveInfo.preferredOrder = 0;
5099                    mResolveInfo.match = 0;
5100                    mResolveComponentName = new ComponentName(
5101                            mAndroidApplication.packageName, mResolveActivity.name);
5102                }
5103            }
5104        }
5105
5106        if (DEBUG_PACKAGE_SCANNING) {
5107            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5108                Log.d(TAG, "Scanning package " + pkg.packageName);
5109        }
5110
5111        if (mPackages.containsKey(pkg.packageName)
5112                || mSharedLibraries.containsKey(pkg.packageName)) {
5113            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5114                    "Application package " + pkg.packageName
5115                    + " already installed.  Skipping duplicate.");
5116        }
5117
5118        // Initialize package source and resource directories
5119        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5120        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5121
5122        SharedUserSetting suid = null;
5123        PackageSetting pkgSetting = null;
5124
5125        if (!isSystemApp(pkg)) {
5126            // Only system apps can use these features.
5127            pkg.mOriginalPackages = null;
5128            pkg.mRealPackage = null;
5129            pkg.mAdoptPermissions = null;
5130        }
5131
5132        // writer
5133        synchronized (mPackages) {
5134            if (pkg.mSharedUserId != null) {
5135                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5136                if (suid == null) {
5137                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5138                            "Creating application package " + pkg.packageName
5139                            + " for shared user failed");
5140                }
5141                if (DEBUG_PACKAGE_SCANNING) {
5142                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5143                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5144                                + "): packages=" + suid.packages);
5145                }
5146            }
5147
5148            // Check if we are renaming from an original package name.
5149            PackageSetting origPackage = null;
5150            String realName = null;
5151            if (pkg.mOriginalPackages != null) {
5152                // This package may need to be renamed to a previously
5153                // installed name.  Let's check on that...
5154                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5155                if (pkg.mOriginalPackages.contains(renamed)) {
5156                    // This package had originally been installed as the
5157                    // original name, and we have already taken care of
5158                    // transitioning to the new one.  Just update the new
5159                    // one to continue using the old name.
5160                    realName = pkg.mRealPackage;
5161                    if (!pkg.packageName.equals(renamed)) {
5162                        // Callers into this function may have already taken
5163                        // care of renaming the package; only do it here if
5164                        // it is not already done.
5165                        pkg.setPackageName(renamed);
5166                    }
5167
5168                } else {
5169                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5170                        if ((origPackage = mSettings.peekPackageLPr(
5171                                pkg.mOriginalPackages.get(i))) != null) {
5172                            // We do have the package already installed under its
5173                            // original name...  should we use it?
5174                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5175                                // New package is not compatible with original.
5176                                origPackage = null;
5177                                continue;
5178                            } else if (origPackage.sharedUser != null) {
5179                                // Make sure uid is compatible between packages.
5180                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5181                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5182                                            + " to " + pkg.packageName + ": old uid "
5183                                            + origPackage.sharedUser.name
5184                                            + " differs from " + pkg.mSharedUserId);
5185                                    origPackage = null;
5186                                    continue;
5187                                }
5188                            } else {
5189                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5190                                        + pkg.packageName + " to old name " + origPackage.name);
5191                            }
5192                            break;
5193                        }
5194                    }
5195                }
5196            }
5197
5198            if (mTransferedPackages.contains(pkg.packageName)) {
5199                Slog.w(TAG, "Package " + pkg.packageName
5200                        + " was transferred to another, but its .apk remains");
5201            }
5202
5203            // Just create the setting, don't add it yet. For already existing packages
5204            // the PkgSetting exists already and doesn't have to be created.
5205            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5206                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5207                    pkg.applicationInfo.primaryCpuAbi,
5208                    pkg.applicationInfo.secondaryCpuAbi,
5209                    pkg.applicationInfo.flags, user, false);
5210            if (pkgSetting == null) {
5211                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5212                        "Creating application package " + pkg.packageName + " failed");
5213            }
5214
5215            if (pkgSetting.origPackage != null) {
5216                // If we are first transitioning from an original package,
5217                // fix up the new package's name now.  We need to do this after
5218                // looking up the package under its new name, so getPackageLP
5219                // can take care of fiddling things correctly.
5220                pkg.setPackageName(origPackage.name);
5221
5222                // File a report about this.
5223                String msg = "New package " + pkgSetting.realName
5224                        + " renamed to replace old package " + pkgSetting.name;
5225                reportSettingsProblem(Log.WARN, msg);
5226
5227                // Make a note of it.
5228                mTransferedPackages.add(origPackage.name);
5229
5230                // No longer need to retain this.
5231                pkgSetting.origPackage = null;
5232            }
5233
5234            if (realName != null) {
5235                // Make a note of it.
5236                mTransferedPackages.add(pkg.packageName);
5237            }
5238
5239            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5240                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5241            }
5242
5243            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5244                // Check all shared libraries and map to their actual file path.
5245                // We only do this here for apps not on a system dir, because those
5246                // are the only ones that can fail an install due to this.  We
5247                // will take care of the system apps by updating all of their
5248                // library paths after the scan is done.
5249                updateSharedLibrariesLPw(pkg, null);
5250            }
5251
5252            if (mFoundPolicyFile) {
5253                SELinuxMMAC.assignSeinfoValue(pkg);
5254            }
5255
5256            pkg.applicationInfo.uid = pkgSetting.appId;
5257            pkg.mExtras = pkgSetting;
5258            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5259                try {
5260                    verifySignaturesLP(pkgSetting, pkg);
5261                } catch (PackageManagerException e) {
5262                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5263                        throw e;
5264                    }
5265                    // The signature has changed, but this package is in the system
5266                    // image...  let's recover!
5267                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5268                    // However...  if this package is part of a shared user, but it
5269                    // doesn't match the signature of the shared user, let's fail.
5270                    // What this means is that you can't change the signatures
5271                    // associated with an overall shared user, which doesn't seem all
5272                    // that unreasonable.
5273                    if (pkgSetting.sharedUser != null) {
5274                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5275                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5276                            throw new PackageManagerException(
5277                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5278                                            "Signature mismatch for shared user : "
5279                                            + pkgSetting.sharedUser);
5280                        }
5281                    }
5282                    // File a report about this.
5283                    String msg = "System package " + pkg.packageName
5284                        + " signature changed; retaining data.";
5285                    reportSettingsProblem(Log.WARN, msg);
5286                }
5287            } else {
5288                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5289                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5290                            + pkg.packageName + " upgrade keys do not match the "
5291                            + "previously installed version");
5292                } else {
5293                    // signatures may have changed as result of upgrade
5294                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5295                }
5296            }
5297            // Verify that this new package doesn't have any content providers
5298            // that conflict with existing packages.  Only do this if the
5299            // package isn't already installed, since we don't want to break
5300            // things that are installed.
5301            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5302                final int N = pkg.providers.size();
5303                int i;
5304                for (i=0; i<N; i++) {
5305                    PackageParser.Provider p = pkg.providers.get(i);
5306                    if (p.info.authority != null) {
5307                        String names[] = p.info.authority.split(";");
5308                        for (int j = 0; j < names.length; j++) {
5309                            if (mProvidersByAuthority.containsKey(names[j])) {
5310                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5311                                final String otherPackageName =
5312                                        ((other != null && other.getComponentName() != null) ?
5313                                                other.getComponentName().getPackageName() : "?");
5314                                throw new PackageManagerException(
5315                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5316                                                "Can't install because provider name " + names[j]
5317                                                + " (in package " + pkg.applicationInfo.packageName
5318                                                + ") is already used by " + otherPackageName);
5319                            }
5320                        }
5321                    }
5322                }
5323            }
5324
5325            if (pkg.mAdoptPermissions != null) {
5326                // This package wants to adopt ownership of permissions from
5327                // another package.
5328                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5329                    final String origName = pkg.mAdoptPermissions.get(i);
5330                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5331                    if (orig != null) {
5332                        if (verifyPackageUpdateLPr(orig, pkg)) {
5333                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5334                                    + pkg.packageName);
5335                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5336                        }
5337                    }
5338                }
5339            }
5340        }
5341
5342        final String pkgName = pkg.packageName;
5343
5344        final long scanFileTime = scanFile.lastModified();
5345        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5346        pkg.applicationInfo.processName = fixProcessName(
5347                pkg.applicationInfo.packageName,
5348                pkg.applicationInfo.processName,
5349                pkg.applicationInfo.uid);
5350
5351        File dataPath;
5352        if (mPlatformPackage == pkg) {
5353            // The system package is special.
5354            dataPath = new File (Environment.getDataDirectory(), "system");
5355            pkg.applicationInfo.dataDir = dataPath.getPath();
5356
5357        } else {
5358            // This is a normal package, need to make its data directory.
5359            dataPath = getDataPathForPackage(pkg.packageName, 0);
5360
5361            boolean uidError = false;
5362
5363            if (dataPath.exists()) {
5364                int currentUid = 0;
5365                try {
5366                    StructStat stat = Os.stat(dataPath.getPath());
5367                    currentUid = stat.st_uid;
5368                } catch (ErrnoException e) {
5369                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5370                }
5371
5372                // If we have mismatched owners for the data path, we have a problem.
5373                if (currentUid != pkg.applicationInfo.uid) {
5374                    boolean recovered = false;
5375                    if (currentUid == 0) {
5376                        // The directory somehow became owned by root.  Wow.
5377                        // This is probably because the system was stopped while
5378                        // installd was in the middle of messing with its libs
5379                        // directory.  Ask installd to fix that.
5380                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5381                                pkg.applicationInfo.uid);
5382                        if (ret >= 0) {
5383                            recovered = true;
5384                            String msg = "Package " + pkg.packageName
5385                                    + " unexpectedly changed to uid 0; recovered to " +
5386                                    + pkg.applicationInfo.uid;
5387                            reportSettingsProblem(Log.WARN, msg);
5388                        }
5389                    }
5390                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5391                            || (scanFlags&SCAN_BOOTING) != 0)) {
5392                        // If this is a system app, we can at least delete its
5393                        // current data so the application will still work.
5394                        int ret = removeDataDirsLI(pkgName);
5395                        if (ret >= 0) {
5396                            // TODO: Kill the processes first
5397                            // Old data gone!
5398                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5399                                    ? "System package " : "Third party package ";
5400                            String msg = prefix + pkg.packageName
5401                                    + " has changed from uid: "
5402                                    + currentUid + " to "
5403                                    + pkg.applicationInfo.uid + "; old data erased";
5404                            reportSettingsProblem(Log.WARN, msg);
5405                            recovered = true;
5406
5407                            // And now re-install the app.
5408                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5409                                                   pkg.applicationInfo.seinfo);
5410                            if (ret == -1) {
5411                                // Ack should not happen!
5412                                msg = prefix + pkg.packageName
5413                                        + " could not have data directory re-created after delete.";
5414                                reportSettingsProblem(Log.WARN, msg);
5415                                throw new PackageManagerException(
5416                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5417                            }
5418                        }
5419                        if (!recovered) {
5420                            mHasSystemUidErrors = true;
5421                        }
5422                    } else if (!recovered) {
5423                        // If we allow this install to proceed, we will be broken.
5424                        // Abort, abort!
5425                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5426                                "scanPackageLI");
5427                    }
5428                    if (!recovered) {
5429                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5430                            + pkg.applicationInfo.uid + "/fs_"
5431                            + currentUid;
5432                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5433                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5434                        String msg = "Package " + pkg.packageName
5435                                + " has mismatched uid: "
5436                                + currentUid + " on disk, "
5437                                + pkg.applicationInfo.uid + " in settings";
5438                        // writer
5439                        synchronized (mPackages) {
5440                            mSettings.mReadMessages.append(msg);
5441                            mSettings.mReadMessages.append('\n');
5442                            uidError = true;
5443                            if (!pkgSetting.uidError) {
5444                                reportSettingsProblem(Log.ERROR, msg);
5445                            }
5446                        }
5447                    }
5448                }
5449                pkg.applicationInfo.dataDir = dataPath.getPath();
5450                if (mShouldRestoreconData) {
5451                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5452                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5453                                pkg.applicationInfo.uid);
5454                }
5455            } else {
5456                if (DEBUG_PACKAGE_SCANNING) {
5457                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5458                        Log.v(TAG, "Want this data dir: " + dataPath);
5459                }
5460                //invoke installer to do the actual installation
5461                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5462                                           pkg.applicationInfo.seinfo);
5463                if (ret < 0) {
5464                    // Error from installer
5465                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5466                            "Unable to create data dirs [errorCode=" + ret + "]");
5467                }
5468
5469                if (dataPath.exists()) {
5470                    pkg.applicationInfo.dataDir = dataPath.getPath();
5471                } else {
5472                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5473                    pkg.applicationInfo.dataDir = null;
5474                }
5475            }
5476
5477            pkgSetting.uidError = uidError;
5478        }
5479
5480        final String path = scanFile.getPath();
5481        final String codePath = pkg.applicationInfo.getCodePath();
5482        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5483        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5484            setBundledAppAbisAndRoots(pkg, pkgSetting);
5485
5486            // If we haven't found any native libraries for the app, check if it has
5487            // renderscript code. We'll need to force the app to 32 bit if it has
5488            // renderscript bitcode.
5489            if (pkg.applicationInfo.primaryCpuAbi == null
5490                    && pkg.applicationInfo.secondaryCpuAbi == null
5491                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5492                NativeLibraryHelper.Handle handle = null;
5493                try {
5494                    handle = NativeLibraryHelper.Handle.create(scanFile);
5495                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5496                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5497                    }
5498                } catch (IOException ioe) {
5499                    Slog.w(TAG, "Error scanning system app : " + ioe);
5500                } finally {
5501                    IoUtils.closeQuietly(handle);
5502                }
5503            }
5504
5505            setNativeLibraryPaths(pkg);
5506        } else {
5507            // TODO: We can probably be smarter about this stuff. For installed apps,
5508            // we can calculate this information at install time once and for all. For
5509            // system apps, we can probably assume that this information doesn't change
5510            // after the first boot scan. As things stand, we do lots of unnecessary work.
5511
5512            // Give ourselves some initial paths; we'll come back for another
5513            // pass once we've determined ABI below.
5514            setNativeLibraryPaths(pkg);
5515
5516            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5517            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5518            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5519
5520            NativeLibraryHelper.Handle handle = null;
5521            try {
5522                handle = NativeLibraryHelper.Handle.create(scanFile);
5523                // TODO(multiArch): This can be null for apps that didn't go through the
5524                // usual installation process. We can calculate it again, like we
5525                // do during install time.
5526                //
5527                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5528                // unnecessary.
5529                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5530
5531                // Null out the abis so that they can be recalculated.
5532                pkg.applicationInfo.primaryCpuAbi = null;
5533                pkg.applicationInfo.secondaryCpuAbi = null;
5534                if (isMultiArch(pkg.applicationInfo)) {
5535                    // Warn if we've set an abiOverride for multi-lib packages..
5536                    // By definition, we need to copy both 32 and 64 bit libraries for
5537                    // such packages.
5538                    if (pkg.cpuAbiOverride != null
5539                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5540                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5541                    }
5542
5543                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5544                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5545                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5546                        if (isAsec) {
5547                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5548                        } else {
5549                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5550                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5551                                    useIsaSpecificSubdirs);
5552                        }
5553                    }
5554
5555                    maybeThrowExceptionForMultiArchCopy(
5556                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5557
5558                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5559                        if (isAsec) {
5560                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5561                        } else {
5562                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5563                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5564                                    useIsaSpecificSubdirs);
5565                        }
5566                    }
5567
5568                    maybeThrowExceptionForMultiArchCopy(
5569                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5570
5571                    if (abi64 >= 0) {
5572                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5573                    }
5574
5575                    if (abi32 >= 0) {
5576                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5577                        if (abi64 >= 0) {
5578                            pkg.applicationInfo.secondaryCpuAbi = abi;
5579                        } else {
5580                            pkg.applicationInfo.primaryCpuAbi = abi;
5581                        }
5582                    }
5583                } else {
5584                    String[] abiList = (cpuAbiOverride != null) ?
5585                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5586
5587                    // Enable gross and lame hacks for apps that are built with old
5588                    // SDK tools. We must scan their APKs for renderscript bitcode and
5589                    // not launch them if it's present. Don't bother checking on devices
5590                    // that don't have 64 bit support.
5591                    boolean needsRenderScriptOverride = false;
5592                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5593                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5594                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5595                        needsRenderScriptOverride = true;
5596                    }
5597
5598                    final int copyRet;
5599                    if (isAsec) {
5600                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5601                    } else {
5602                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5603                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5604                    }
5605
5606                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5607                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5608                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5609                    }
5610
5611                    if (copyRet >= 0) {
5612                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5613                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5614                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5615                    } else if (needsRenderScriptOverride) {
5616                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5617                    }
5618                }
5619            } catch (IOException ioe) {
5620                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5621            } finally {
5622                IoUtils.closeQuietly(handle);
5623            }
5624
5625            // Now that we've calculated the ABIs and determined if it's an internal app,
5626            // we will go ahead and populate the nativeLibraryPath.
5627            setNativeLibraryPaths(pkg);
5628
5629            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5630            final int[] userIds = sUserManager.getUserIds();
5631            synchronized (mInstallLock) {
5632                // Create a native library symlink only if we have native libraries
5633                // and if the native libraries are 32 bit libraries. We do not provide
5634                // this symlink for 64 bit libraries.
5635                if (pkg.applicationInfo.primaryCpuAbi != null &&
5636                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5637                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5638                    for (int userId : userIds) {
5639                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5640                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5641                                    "Failed linking native library dir (user=" + userId + ")");
5642                        }
5643                    }
5644                }
5645            }
5646        }
5647
5648        // This is a special case for the "system" package, where the ABI is
5649        // dictated by the zygote configuration (and init.rc). We should keep track
5650        // of this ABI so that we can deal with "normal" applications that run under
5651        // the same UID correctly.
5652        if (mPlatformPackage == pkg) {
5653            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5654                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5655        }
5656
5657        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5658        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5659        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5660        // Copy the derived override back to the parsed package, so that we can
5661        // update the package settings accordingly.
5662        pkg.cpuAbiOverride = cpuAbiOverride;
5663
5664        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5665                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5666                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5667
5668        // Push the derived path down into PackageSettings so we know what to
5669        // clean up at uninstall time.
5670        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5671
5672        if (DEBUG_ABI_SELECTION) {
5673            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5674                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5675                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5676        }
5677
5678        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5679            // We don't do this here during boot because we can do it all
5680            // at once after scanning all existing packages.
5681            //
5682            // We also do this *before* we perform dexopt on this package, so that
5683            // we can avoid redundant dexopts, and also to make sure we've got the
5684            // code and package path correct.
5685            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5686                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5687        }
5688
5689        if ((scanFlags&SCAN_NO_DEX) == 0) {
5690            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5691                    == DEX_OPT_FAILED) {
5692                if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5693                    removeDataDirsLI(pkg.packageName);
5694                }
5695
5696                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5697            }
5698        }
5699
5700        if (mFactoryTest && pkg.requestedPermissions.contains(
5701                android.Manifest.permission.FACTORY_TEST)) {
5702            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5703        }
5704
5705        ArrayList<PackageParser.Package> clientLibPkgs = null;
5706
5707        // writer
5708        synchronized (mPackages) {
5709            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5710                // Only system apps can add new shared libraries.
5711                if (pkg.libraryNames != null) {
5712                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5713                        String name = pkg.libraryNames.get(i);
5714                        boolean allowed = false;
5715                        if (isUpdatedSystemApp(pkg)) {
5716                            // New library entries can only be added through the
5717                            // system image.  This is important to get rid of a lot
5718                            // of nasty edge cases: for example if we allowed a non-
5719                            // system update of the app to add a library, then uninstalling
5720                            // the update would make the library go away, and assumptions
5721                            // we made such as through app install filtering would now
5722                            // have allowed apps on the device which aren't compatible
5723                            // with it.  Better to just have the restriction here, be
5724                            // conservative, and create many fewer cases that can negatively
5725                            // impact the user experience.
5726                            final PackageSetting sysPs = mSettings
5727                                    .getDisabledSystemPkgLPr(pkg.packageName);
5728                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5729                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5730                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5731                                        allowed = true;
5732                                        allowed = true;
5733                                        break;
5734                                    }
5735                                }
5736                            }
5737                        } else {
5738                            allowed = true;
5739                        }
5740                        if (allowed) {
5741                            if (!mSharedLibraries.containsKey(name)) {
5742                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5743                            } else if (!name.equals(pkg.packageName)) {
5744                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5745                                        + name + " already exists; skipping");
5746                            }
5747                        } else {
5748                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5749                                    + name + " that is not declared on system image; skipping");
5750                        }
5751                    }
5752                    if ((scanFlags&SCAN_BOOTING) == 0) {
5753                        // If we are not booting, we need to update any applications
5754                        // that are clients of our shared library.  If we are booting,
5755                        // this will all be done once the scan is complete.
5756                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5757                    }
5758                }
5759            }
5760        }
5761
5762        // We also need to dexopt any apps that are dependent on this library.  Note that
5763        // if these fail, we should abort the install since installing the library will
5764        // result in some apps being broken.
5765        if (clientLibPkgs != null) {
5766            if ((scanFlags&SCAN_NO_DEX) == 0) {
5767                for (int i=0; i<clientLibPkgs.size(); i++) {
5768                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5769                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5770                            forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5771                            == DEX_OPT_FAILED) {
5772                        if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5773                            removeDataDirsLI(pkg.packageName);
5774                        }
5775
5776                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5777                                "scanPackageLI failed to dexopt clientLibPkgs");
5778                    }
5779                }
5780            }
5781        }
5782
5783        // Request the ActivityManager to kill the process(only for existing packages)
5784        // so that we do not end up in a confused state while the user is still using the older
5785        // version of the application while the new one gets installed.
5786        if ((scanFlags & SCAN_REPLACING) != 0) {
5787            killApplication(pkg.applicationInfo.packageName,
5788                        pkg.applicationInfo.uid, "update pkg");
5789        }
5790
5791        // Also need to kill any apps that are dependent on the library.
5792        if (clientLibPkgs != null) {
5793            for (int i=0; i<clientLibPkgs.size(); i++) {
5794                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5795                killApplication(clientPkg.applicationInfo.packageName,
5796                        clientPkg.applicationInfo.uid, "update lib");
5797            }
5798        }
5799
5800        // writer
5801        synchronized (mPackages) {
5802            // We don't expect installation to fail beyond this point
5803
5804            // Add the new setting to mSettings
5805            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5806            // Add the new setting to mPackages
5807            mPackages.put(pkg.applicationInfo.packageName, pkg);
5808            // Make sure we don't accidentally delete its data.
5809            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5810            while (iter.hasNext()) {
5811                PackageCleanItem item = iter.next();
5812                if (pkgName.equals(item.packageName)) {
5813                    iter.remove();
5814                }
5815            }
5816
5817            // Take care of first install / last update times.
5818            if (currentTime != 0) {
5819                if (pkgSetting.firstInstallTime == 0) {
5820                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5821                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5822                    pkgSetting.lastUpdateTime = currentTime;
5823                }
5824            } else if (pkgSetting.firstInstallTime == 0) {
5825                // We need *something*.  Take time time stamp of the file.
5826                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5827            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5828                if (scanFileTime != pkgSetting.timeStamp) {
5829                    // A package on the system image has changed; consider this
5830                    // to be an update.
5831                    pkgSetting.lastUpdateTime = scanFileTime;
5832                }
5833            }
5834
5835            // Add the package's KeySets to the global KeySetManagerService
5836            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5837            try {
5838                // Old KeySetData no longer valid.
5839                ksms.removeAppKeySetDataLPw(pkg.packageName);
5840                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5841                if (pkg.mKeySetMapping != null) {
5842                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5843                            pkg.mKeySetMapping.entrySet()) {
5844                        if (entry.getValue() != null) {
5845                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5846                                                          entry.getValue(), entry.getKey());
5847                        }
5848                    }
5849                    if (pkg.mUpgradeKeySets != null) {
5850                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5851                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5852                        }
5853                    }
5854                }
5855            } catch (NullPointerException e) {
5856                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5857            } catch (IllegalArgumentException e) {
5858                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5859            }
5860
5861            int N = pkg.providers.size();
5862            StringBuilder r = null;
5863            int i;
5864            for (i=0; i<N; i++) {
5865                PackageParser.Provider p = pkg.providers.get(i);
5866                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5867                        p.info.processName, pkg.applicationInfo.uid);
5868                mProviders.addProvider(p);
5869                p.syncable = p.info.isSyncable;
5870                if (p.info.authority != null) {
5871                    String names[] = p.info.authority.split(";");
5872                    p.info.authority = null;
5873                    for (int j = 0; j < names.length; j++) {
5874                        if (j == 1 && p.syncable) {
5875                            // We only want the first authority for a provider to possibly be
5876                            // syncable, so if we already added this provider using a different
5877                            // authority clear the syncable flag. We copy the provider before
5878                            // changing it because the mProviders object contains a reference
5879                            // to a provider that we don't want to change.
5880                            // Only do this for the second authority since the resulting provider
5881                            // object can be the same for all future authorities for this provider.
5882                            p = new PackageParser.Provider(p);
5883                            p.syncable = false;
5884                        }
5885                        if (!mProvidersByAuthority.containsKey(names[j])) {
5886                            mProvidersByAuthority.put(names[j], p);
5887                            if (p.info.authority == null) {
5888                                p.info.authority = names[j];
5889                            } else {
5890                                p.info.authority = p.info.authority + ";" + names[j];
5891                            }
5892                            if (DEBUG_PACKAGE_SCANNING) {
5893                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5894                                    Log.d(TAG, "Registered content provider: " + names[j]
5895                                            + ", className = " + p.info.name + ", isSyncable = "
5896                                            + p.info.isSyncable);
5897                            }
5898                        } else {
5899                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5900                            Slog.w(TAG, "Skipping provider name " + names[j] +
5901                                    " (in package " + pkg.applicationInfo.packageName +
5902                                    "): name already used by "
5903                                    + ((other != null && other.getComponentName() != null)
5904                                            ? other.getComponentName().getPackageName() : "?"));
5905                        }
5906                    }
5907                }
5908                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5909                    if (r == null) {
5910                        r = new StringBuilder(256);
5911                    } else {
5912                        r.append(' ');
5913                    }
5914                    r.append(p.info.name);
5915                }
5916            }
5917            if (r != null) {
5918                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5919            }
5920
5921            N = pkg.services.size();
5922            r = null;
5923            for (i=0; i<N; i++) {
5924                PackageParser.Service s = pkg.services.get(i);
5925                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5926                        s.info.processName, pkg.applicationInfo.uid);
5927                mServices.addService(s);
5928                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5929                    if (r == null) {
5930                        r = new StringBuilder(256);
5931                    } else {
5932                        r.append(' ');
5933                    }
5934                    r.append(s.info.name);
5935                }
5936            }
5937            if (r != null) {
5938                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5939            }
5940
5941            N = pkg.receivers.size();
5942            r = null;
5943            for (i=0; i<N; i++) {
5944                PackageParser.Activity a = pkg.receivers.get(i);
5945                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5946                        a.info.processName, pkg.applicationInfo.uid);
5947                mReceivers.addActivity(a, "receiver");
5948                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5949                    if (r == null) {
5950                        r = new StringBuilder(256);
5951                    } else {
5952                        r.append(' ');
5953                    }
5954                    r.append(a.info.name);
5955                }
5956            }
5957            if (r != null) {
5958                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5959            }
5960
5961            N = pkg.activities.size();
5962            r = null;
5963            for (i=0; i<N; i++) {
5964                PackageParser.Activity a = pkg.activities.get(i);
5965                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5966                        a.info.processName, pkg.applicationInfo.uid);
5967                mActivities.addActivity(a, "activity");
5968                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5969                    if (r == null) {
5970                        r = new StringBuilder(256);
5971                    } else {
5972                        r.append(' ');
5973                    }
5974                    r.append(a.info.name);
5975                }
5976            }
5977            if (r != null) {
5978                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5979            }
5980
5981            N = pkg.permissionGroups.size();
5982            r = null;
5983            for (i=0; i<N; i++) {
5984                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5985                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5986                if (cur == null) {
5987                    mPermissionGroups.put(pg.info.name, pg);
5988                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5989                        if (r == null) {
5990                            r = new StringBuilder(256);
5991                        } else {
5992                            r.append(' ');
5993                        }
5994                        r.append(pg.info.name);
5995                    }
5996                } else {
5997                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5998                            + pg.info.packageName + " ignored: original from "
5999                            + cur.info.packageName);
6000                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6001                        if (r == null) {
6002                            r = new StringBuilder(256);
6003                        } else {
6004                            r.append(' ');
6005                        }
6006                        r.append("DUP:");
6007                        r.append(pg.info.name);
6008                    }
6009                }
6010            }
6011            if (r != null) {
6012                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6013            }
6014
6015            N = pkg.permissions.size();
6016            r = null;
6017            for (i=0; i<N; i++) {
6018                PackageParser.Permission p = pkg.permissions.get(i);
6019                HashMap<String, BasePermission> permissionMap =
6020                        p.tree ? mSettings.mPermissionTrees
6021                        : mSettings.mPermissions;
6022                p.group = mPermissionGroups.get(p.info.group);
6023                if (p.info.group == null || p.group != null) {
6024                    BasePermission bp = permissionMap.get(p.info.name);
6025                    if (bp == null) {
6026                        bp = new BasePermission(p.info.name, p.info.packageName,
6027                                BasePermission.TYPE_NORMAL);
6028                        permissionMap.put(p.info.name, bp);
6029                    }
6030                    if (bp.perm == null) {
6031                        if (bp.sourcePackage != null
6032                                && !bp.sourcePackage.equals(p.info.packageName)) {
6033                            // If this is a permission that was formerly defined by a non-system
6034                            // app, but is now defined by a system app (following an upgrade),
6035                            // discard the previous declaration and consider the system's to be
6036                            // canonical.
6037                            if (isSystemApp(p.owner)) {
6038                                String msg = "New decl " + p.owner + " of permission  "
6039                                        + p.info.name + " is system";
6040                                reportSettingsProblem(Log.WARN, msg);
6041                                bp.sourcePackage = null;
6042                            }
6043                        }
6044                        if (bp.sourcePackage == null
6045                                || bp.sourcePackage.equals(p.info.packageName)) {
6046                            BasePermission tree = findPermissionTreeLP(p.info.name);
6047                            if (tree == null
6048                                    || tree.sourcePackage.equals(p.info.packageName)) {
6049                                bp.packageSetting = pkgSetting;
6050                                bp.perm = p;
6051                                bp.uid = pkg.applicationInfo.uid;
6052                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6053                                    if (r == null) {
6054                                        r = new StringBuilder(256);
6055                                    } else {
6056                                        r.append(' ');
6057                                    }
6058                                    r.append(p.info.name);
6059                                }
6060                            } else {
6061                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6062                                        + p.info.packageName + " ignored: base tree "
6063                                        + tree.name + " is from package "
6064                                        + tree.sourcePackage);
6065                            }
6066                        } else {
6067                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6068                                    + p.info.packageName + " ignored: original from "
6069                                    + bp.sourcePackage);
6070                        }
6071                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6072                        if (r == null) {
6073                            r = new StringBuilder(256);
6074                        } else {
6075                            r.append(' ');
6076                        }
6077                        r.append("DUP:");
6078                        r.append(p.info.name);
6079                    }
6080                    if (bp.perm == p) {
6081                        bp.protectionLevel = p.info.protectionLevel;
6082                    }
6083                } else {
6084                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6085                            + p.info.packageName + " ignored: no group "
6086                            + p.group);
6087                }
6088            }
6089            if (r != null) {
6090                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6091            }
6092
6093            N = pkg.instrumentation.size();
6094            r = null;
6095            for (i=0; i<N; i++) {
6096                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6097                a.info.packageName = pkg.applicationInfo.packageName;
6098                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6099                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6100                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6101                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6102                a.info.dataDir = pkg.applicationInfo.dataDir;
6103
6104                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6105                // need other information about the application, like the ABI and what not ?
6106                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6107                mInstrumentation.put(a.getComponentName(), a);
6108                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6109                    if (r == null) {
6110                        r = new StringBuilder(256);
6111                    } else {
6112                        r.append(' ');
6113                    }
6114                    r.append(a.info.name);
6115                }
6116            }
6117            if (r != null) {
6118                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6119            }
6120
6121            if (pkg.protectedBroadcasts != null) {
6122                N = pkg.protectedBroadcasts.size();
6123                for (i=0; i<N; i++) {
6124                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6125                }
6126            }
6127
6128            pkgSetting.setTimeStamp(scanFileTime);
6129
6130            // Create idmap files for pairs of (packages, overlay packages).
6131            // Note: "android", ie framework-res.apk, is handled by native layers.
6132            if (pkg.mOverlayTarget != null) {
6133                // This is an overlay package.
6134                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6135                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6136                        mOverlays.put(pkg.mOverlayTarget,
6137                                new HashMap<String, PackageParser.Package>());
6138                    }
6139                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6140                    map.put(pkg.packageName, pkg);
6141                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6142                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6143                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6144                                "scanPackageLI failed to createIdmap");
6145                    }
6146                }
6147            } else if (mOverlays.containsKey(pkg.packageName) &&
6148                    !pkg.packageName.equals("android")) {
6149                // This is a regular package, with one or more known overlay packages.
6150                createIdmapsForPackageLI(pkg);
6151            }
6152        }
6153
6154        return pkg;
6155    }
6156
6157    /**
6158     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6159     * i.e, so that all packages can be run inside a single process if required.
6160     *
6161     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6162     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6163     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6164     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6165     * updating a package that belongs to a shared user.
6166     *
6167     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6168     * adds unnecessary complexity.
6169     */
6170    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6171            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6172        String requiredInstructionSet = null;
6173        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6174            requiredInstructionSet = VMRuntime.getInstructionSet(
6175                     scannedPackage.applicationInfo.primaryCpuAbi);
6176        }
6177
6178        PackageSetting requirer = null;
6179        for (PackageSetting ps : packagesForUser) {
6180            // If packagesForUser contains scannedPackage, we skip it. This will happen
6181            // when scannedPackage is an update of an existing package. Without this check,
6182            // we will never be able to change the ABI of any package belonging to a shared
6183            // user, even if it's compatible with other packages.
6184            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6185                if (ps.primaryCpuAbiString == null) {
6186                    continue;
6187                }
6188
6189                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6190                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6191                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6192                    // this but there's not much we can do.
6193                    String errorMessage = "Instruction set mismatch, "
6194                            + ((requirer == null) ? "[caller]" : requirer)
6195                            + " requires " + requiredInstructionSet + " whereas " + ps
6196                            + " requires " + instructionSet;
6197                    Slog.w(TAG, errorMessage);
6198                }
6199
6200                if (requiredInstructionSet == null) {
6201                    requiredInstructionSet = instructionSet;
6202                    requirer = ps;
6203                }
6204            }
6205        }
6206
6207        if (requiredInstructionSet != null) {
6208            String adjustedAbi;
6209            if (requirer != null) {
6210                // requirer != null implies that either scannedPackage was null or that scannedPackage
6211                // did not require an ABI, in which case we have to adjust scannedPackage to match
6212                // the ABI of the set (which is the same as requirer's ABI)
6213                adjustedAbi = requirer.primaryCpuAbiString;
6214                if (scannedPackage != null) {
6215                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6216                }
6217            } else {
6218                // requirer == null implies that we're updating all ABIs in the set to
6219                // match scannedPackage.
6220                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6221            }
6222
6223            for (PackageSetting ps : packagesForUser) {
6224                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6225                    if (ps.primaryCpuAbiString != null) {
6226                        continue;
6227                    }
6228
6229                    ps.primaryCpuAbiString = adjustedAbi;
6230                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6231                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6232                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6233
6234                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6235                                deferDexOpt, true) == DEX_OPT_FAILED) {
6236                            ps.primaryCpuAbiString = null;
6237                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6238                            return;
6239                        } else {
6240                            mInstaller.rmdex(ps.codePathString,
6241                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6242                        }
6243                    }
6244                }
6245            }
6246        }
6247    }
6248
6249    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6250        synchronized (mPackages) {
6251            mResolverReplaced = true;
6252            // Set up information for custom user intent resolution activity.
6253            mResolveActivity.applicationInfo = pkg.applicationInfo;
6254            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6255            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6256            mResolveActivity.processName = null;
6257            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6258            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6259                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6260            mResolveActivity.theme = 0;
6261            mResolveActivity.exported = true;
6262            mResolveActivity.enabled = true;
6263            mResolveInfo.activityInfo = mResolveActivity;
6264            mResolveInfo.priority = 0;
6265            mResolveInfo.preferredOrder = 0;
6266            mResolveInfo.match = 0;
6267            mResolveComponentName = mCustomResolverComponentName;
6268            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6269                    mResolveComponentName);
6270        }
6271    }
6272
6273    private static String calculateBundledApkRoot(final String codePathString) {
6274        final File codePath = new File(codePathString);
6275        final File codeRoot;
6276        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6277            codeRoot = Environment.getRootDirectory();
6278        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6279            codeRoot = Environment.getOemDirectory();
6280        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6281            codeRoot = Environment.getVendorDirectory();
6282        } else {
6283            // Unrecognized code path; take its top real segment as the apk root:
6284            // e.g. /something/app/blah.apk => /something
6285            try {
6286                File f = codePath.getCanonicalFile();
6287                File parent = f.getParentFile();    // non-null because codePath is a file
6288                File tmp;
6289                while ((tmp = parent.getParentFile()) != null) {
6290                    f = parent;
6291                    parent = tmp;
6292                }
6293                codeRoot = f;
6294                Slog.w(TAG, "Unrecognized code path "
6295                        + codePath + " - using " + codeRoot);
6296            } catch (IOException e) {
6297                // Can't canonicalize the code path -- shenanigans?
6298                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6299                return Environment.getRootDirectory().getPath();
6300            }
6301        }
6302        return codeRoot.getPath();
6303    }
6304
6305    /**
6306     * Derive and set the location of native libraries for the given package,
6307     * which varies depending on where and how the package was installed.
6308     */
6309    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6310        final ApplicationInfo info = pkg.applicationInfo;
6311        final String codePath = pkg.codePath;
6312        final File codeFile = new File(codePath);
6313        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6314        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6315
6316        info.nativeLibraryRootDir = null;
6317        info.nativeLibraryRootRequiresIsa = false;
6318        info.nativeLibraryDir = null;
6319        info.secondaryNativeLibraryDir = null;
6320
6321        if (isApkFile(codeFile)) {
6322            // Monolithic install
6323            if (bundledApp) {
6324                // If "/system/lib64/apkname" exists, assume that is the per-package
6325                // native library directory to use; otherwise use "/system/lib/apkname".
6326                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6327                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6328                        getPrimaryInstructionSet(info));
6329
6330                // This is a bundled system app so choose the path based on the ABI.
6331                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6332                // is just the default path.
6333                final String apkName = deriveCodePathName(codePath);
6334                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6335                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6336                        apkName).getAbsolutePath();
6337
6338                if (info.secondaryCpuAbi != null) {
6339                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6340                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6341                            secondaryLibDir, apkName).getAbsolutePath();
6342                }
6343            } else if (asecApp) {
6344                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6345                        .getAbsolutePath();
6346            } else {
6347                final String apkName = deriveCodePathName(codePath);
6348                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6349                        .getAbsolutePath();
6350            }
6351
6352            info.nativeLibraryRootRequiresIsa = false;
6353            info.nativeLibraryDir = info.nativeLibraryRootDir;
6354        } else {
6355            // Cluster install
6356            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6357            info.nativeLibraryRootRequiresIsa = true;
6358
6359            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6360                    getPrimaryInstructionSet(info)).getAbsolutePath();
6361
6362            if (info.secondaryCpuAbi != null) {
6363                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6364                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6365            }
6366        }
6367    }
6368
6369    /**
6370     * Calculate the abis and roots for a bundled app. These can uniquely
6371     * be determined from the contents of the system partition, i.e whether
6372     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6373     * of this information, and instead assume that the system was built
6374     * sensibly.
6375     */
6376    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6377                                           PackageSetting pkgSetting) {
6378        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6379
6380        // If "/system/lib64/apkname" exists, assume that is the per-package
6381        // native library directory to use; otherwise use "/system/lib/apkname".
6382        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6383        setBundledAppAbi(pkg, apkRoot, apkName);
6384        // pkgSetting might be null during rescan following uninstall of updates
6385        // to a bundled app, so accommodate that possibility.  The settings in
6386        // that case will be established later from the parsed package.
6387        //
6388        // If the settings aren't null, sync them up with what we've just derived.
6389        // note that apkRoot isn't stored in the package settings.
6390        if (pkgSetting != null) {
6391            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6392            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6393        }
6394    }
6395
6396    /**
6397     * Deduces the ABI of a bundled app and sets the relevant fields on the
6398     * parsed pkg object.
6399     *
6400     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6401     *        under which system libraries are installed.
6402     * @param apkName the name of the installed package.
6403     */
6404    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6405        final File codeFile = new File(pkg.codePath);
6406
6407        final boolean has64BitLibs;
6408        final boolean has32BitLibs;
6409        if (isApkFile(codeFile)) {
6410            // Monolithic install
6411            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6412            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6413        } else {
6414            // Cluster install
6415            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6416            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6417                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6418                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6419                has64BitLibs = (new File(rootDir, isa)).exists();
6420            } else {
6421                has64BitLibs = false;
6422            }
6423            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6424                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6425                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6426                has32BitLibs = (new File(rootDir, isa)).exists();
6427            } else {
6428                has32BitLibs = false;
6429            }
6430        }
6431
6432        if (has64BitLibs && !has32BitLibs) {
6433            // The package has 64 bit libs, but not 32 bit libs. Its primary
6434            // ABI should be 64 bit. We can safely assume here that the bundled
6435            // native libraries correspond to the most preferred ABI in the list.
6436
6437            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6438            pkg.applicationInfo.secondaryCpuAbi = null;
6439        } else if (has32BitLibs && !has64BitLibs) {
6440            // The package has 32 bit libs but not 64 bit libs. Its primary
6441            // ABI should be 32 bit.
6442
6443            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6444            pkg.applicationInfo.secondaryCpuAbi = null;
6445        } else if (has32BitLibs && has64BitLibs) {
6446            // The application has both 64 and 32 bit bundled libraries. We check
6447            // here that the app declares multiArch support, and warn if it doesn't.
6448            //
6449            // We will be lenient here and record both ABIs. The primary will be the
6450            // ABI that's higher on the list, i.e, a device that's configured to prefer
6451            // 64 bit apps will see a 64 bit primary ABI,
6452
6453            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6454                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6455            }
6456
6457            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6458                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6459                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6460            } else {
6461                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6462                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6463            }
6464        } else {
6465            pkg.applicationInfo.primaryCpuAbi = null;
6466            pkg.applicationInfo.secondaryCpuAbi = null;
6467        }
6468    }
6469
6470    private void killApplication(String pkgName, int appId, String reason) {
6471        // Request the ActivityManager to kill the process(only for existing packages)
6472        // so that we do not end up in a confused state while the user is still using the older
6473        // version of the application while the new one gets installed.
6474        IActivityManager am = ActivityManagerNative.getDefault();
6475        if (am != null) {
6476            try {
6477                am.killApplicationWithAppId(pkgName, appId, reason);
6478            } catch (RemoteException e) {
6479            }
6480        }
6481    }
6482
6483    void removePackageLI(PackageSetting ps, boolean chatty) {
6484        if (DEBUG_INSTALL) {
6485            if (chatty)
6486                Log.d(TAG, "Removing package " + ps.name);
6487        }
6488
6489        // writer
6490        synchronized (mPackages) {
6491            mPackages.remove(ps.name);
6492            final PackageParser.Package pkg = ps.pkg;
6493            if (pkg != null) {
6494                cleanPackageDataStructuresLILPw(pkg, chatty);
6495            }
6496        }
6497    }
6498
6499    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6500        if (DEBUG_INSTALL) {
6501            if (chatty)
6502                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6503        }
6504
6505        // writer
6506        synchronized (mPackages) {
6507            mPackages.remove(pkg.applicationInfo.packageName);
6508            cleanPackageDataStructuresLILPw(pkg, chatty);
6509        }
6510    }
6511
6512    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6513        int N = pkg.providers.size();
6514        StringBuilder r = null;
6515        int i;
6516        for (i=0; i<N; i++) {
6517            PackageParser.Provider p = pkg.providers.get(i);
6518            mProviders.removeProvider(p);
6519            if (p.info.authority == null) {
6520
6521                /* There was another ContentProvider with this authority when
6522                 * this app was installed so this authority is null,
6523                 * Ignore it as we don't have to unregister the provider.
6524                 */
6525                continue;
6526            }
6527            String names[] = p.info.authority.split(";");
6528            for (int j = 0; j < names.length; j++) {
6529                if (mProvidersByAuthority.get(names[j]) == p) {
6530                    mProvidersByAuthority.remove(names[j]);
6531                    if (DEBUG_REMOVE) {
6532                        if (chatty)
6533                            Log.d(TAG, "Unregistered content provider: " + names[j]
6534                                    + ", className = " + p.info.name + ", isSyncable = "
6535                                    + p.info.isSyncable);
6536                    }
6537                }
6538            }
6539            if (DEBUG_REMOVE && chatty) {
6540                if (r == null) {
6541                    r = new StringBuilder(256);
6542                } else {
6543                    r.append(' ');
6544                }
6545                r.append(p.info.name);
6546            }
6547        }
6548        if (r != null) {
6549            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6550        }
6551
6552        N = pkg.services.size();
6553        r = null;
6554        for (i=0; i<N; i++) {
6555            PackageParser.Service s = pkg.services.get(i);
6556            mServices.removeService(s);
6557            if (chatty) {
6558                if (r == null) {
6559                    r = new StringBuilder(256);
6560                } else {
6561                    r.append(' ');
6562                }
6563                r.append(s.info.name);
6564            }
6565        }
6566        if (r != null) {
6567            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6568        }
6569
6570        N = pkg.receivers.size();
6571        r = null;
6572        for (i=0; i<N; i++) {
6573            PackageParser.Activity a = pkg.receivers.get(i);
6574            mReceivers.removeActivity(a, "receiver");
6575            if (DEBUG_REMOVE && chatty) {
6576                if (r == null) {
6577                    r = new StringBuilder(256);
6578                } else {
6579                    r.append(' ');
6580                }
6581                r.append(a.info.name);
6582            }
6583        }
6584        if (r != null) {
6585            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6586        }
6587
6588        N = pkg.activities.size();
6589        r = null;
6590        for (i=0; i<N; i++) {
6591            PackageParser.Activity a = pkg.activities.get(i);
6592            mActivities.removeActivity(a, "activity");
6593            if (DEBUG_REMOVE && chatty) {
6594                if (r == null) {
6595                    r = new StringBuilder(256);
6596                } else {
6597                    r.append(' ');
6598                }
6599                r.append(a.info.name);
6600            }
6601        }
6602        if (r != null) {
6603            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6604        }
6605
6606        N = pkg.permissions.size();
6607        r = null;
6608        for (i=0; i<N; i++) {
6609            PackageParser.Permission p = pkg.permissions.get(i);
6610            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6611            if (bp == null) {
6612                bp = mSettings.mPermissionTrees.get(p.info.name);
6613            }
6614            if (bp != null && bp.perm == p) {
6615                bp.perm = null;
6616                if (DEBUG_REMOVE && chatty) {
6617                    if (r == null) {
6618                        r = new StringBuilder(256);
6619                    } else {
6620                        r.append(' ');
6621                    }
6622                    r.append(p.info.name);
6623                }
6624            }
6625            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6626                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6627                if (appOpPerms != null) {
6628                    appOpPerms.remove(pkg.packageName);
6629                }
6630            }
6631        }
6632        if (r != null) {
6633            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6634        }
6635
6636        N = pkg.requestedPermissions.size();
6637        r = null;
6638        for (i=0; i<N; i++) {
6639            String perm = pkg.requestedPermissions.get(i);
6640            BasePermission bp = mSettings.mPermissions.get(perm);
6641            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6642                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6643                if (appOpPerms != null) {
6644                    appOpPerms.remove(pkg.packageName);
6645                    if (appOpPerms.isEmpty()) {
6646                        mAppOpPermissionPackages.remove(perm);
6647                    }
6648                }
6649            }
6650        }
6651        if (r != null) {
6652            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6653        }
6654
6655        N = pkg.instrumentation.size();
6656        r = null;
6657        for (i=0; i<N; i++) {
6658            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6659            mInstrumentation.remove(a.getComponentName());
6660            if (DEBUG_REMOVE && chatty) {
6661                if (r == null) {
6662                    r = new StringBuilder(256);
6663                } else {
6664                    r.append(' ');
6665                }
6666                r.append(a.info.name);
6667            }
6668        }
6669        if (r != null) {
6670            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6671        }
6672
6673        r = null;
6674        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6675            // Only system apps can hold shared libraries.
6676            if (pkg.libraryNames != null) {
6677                for (i=0; i<pkg.libraryNames.size(); i++) {
6678                    String name = pkg.libraryNames.get(i);
6679                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6680                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6681                        mSharedLibraries.remove(name);
6682                        if (DEBUG_REMOVE && chatty) {
6683                            if (r == null) {
6684                                r = new StringBuilder(256);
6685                            } else {
6686                                r.append(' ');
6687                            }
6688                            r.append(name);
6689                        }
6690                    }
6691                }
6692            }
6693        }
6694        if (r != null) {
6695            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6696        }
6697    }
6698
6699    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6700        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6701            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6702                return true;
6703            }
6704        }
6705        return false;
6706    }
6707
6708    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6709    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6710    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6711
6712    private void updatePermissionsLPw(String changingPkg,
6713            PackageParser.Package pkgInfo, int flags) {
6714        // Make sure there are no dangling permission trees.
6715        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6716        while (it.hasNext()) {
6717            final BasePermission bp = it.next();
6718            if (bp.packageSetting == null) {
6719                // We may not yet have parsed the package, so just see if
6720                // we still know about its settings.
6721                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6722            }
6723            if (bp.packageSetting == null) {
6724                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6725                        + " from package " + bp.sourcePackage);
6726                it.remove();
6727            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6728                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6729                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6730                            + " from package " + bp.sourcePackage);
6731                    flags |= UPDATE_PERMISSIONS_ALL;
6732                    it.remove();
6733                }
6734            }
6735        }
6736
6737        // Make sure all dynamic permissions have been assigned to a package,
6738        // and make sure there are no dangling permissions.
6739        it = mSettings.mPermissions.values().iterator();
6740        while (it.hasNext()) {
6741            final BasePermission bp = it.next();
6742            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6743                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6744                        + bp.name + " pkg=" + bp.sourcePackage
6745                        + " info=" + bp.pendingInfo);
6746                if (bp.packageSetting == null && bp.pendingInfo != null) {
6747                    final BasePermission tree = findPermissionTreeLP(bp.name);
6748                    if (tree != null && tree.perm != null) {
6749                        bp.packageSetting = tree.packageSetting;
6750                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6751                                new PermissionInfo(bp.pendingInfo));
6752                        bp.perm.info.packageName = tree.perm.info.packageName;
6753                        bp.perm.info.name = bp.name;
6754                        bp.uid = tree.uid;
6755                    }
6756                }
6757            }
6758            if (bp.packageSetting == null) {
6759                // We may not yet have parsed the package, so just see if
6760                // we still know about its settings.
6761                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6762            }
6763            if (bp.packageSetting == null) {
6764                Slog.w(TAG, "Removing dangling permission: " + bp.name
6765                        + " from package " + bp.sourcePackage);
6766                it.remove();
6767            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6768                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6769                    Slog.i(TAG, "Removing old permission: " + bp.name
6770                            + " from package " + bp.sourcePackage);
6771                    flags |= UPDATE_PERMISSIONS_ALL;
6772                    it.remove();
6773                }
6774            }
6775        }
6776
6777        // Now update the permissions for all packages, in particular
6778        // replace the granted permissions of the system packages.
6779        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6780            for (PackageParser.Package pkg : mPackages.values()) {
6781                if (pkg != pkgInfo) {
6782                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6783                }
6784            }
6785        }
6786
6787        if (pkgInfo != null) {
6788            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6789        }
6790    }
6791
6792    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6793        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6794        if (ps == null) {
6795            return;
6796        }
6797        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6798        HashSet<String> origPermissions = gp.grantedPermissions;
6799        boolean changedPermission = false;
6800
6801        if (replace) {
6802            ps.permissionsFixed = false;
6803            if (gp == ps) {
6804                origPermissions = new HashSet<String>(gp.grantedPermissions);
6805                gp.grantedPermissions.clear();
6806                gp.gids = mGlobalGids;
6807            }
6808        }
6809
6810        if (gp.gids == null) {
6811            gp.gids = mGlobalGids;
6812        }
6813
6814        final int N = pkg.requestedPermissions.size();
6815        for (int i=0; i<N; i++) {
6816            final String name = pkg.requestedPermissions.get(i);
6817            final boolean required = pkg.requestedPermissionsRequired.get(i);
6818            final BasePermission bp = mSettings.mPermissions.get(name);
6819            if (DEBUG_INSTALL) {
6820                if (gp != ps) {
6821                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6822                }
6823            }
6824
6825            if (bp == null || bp.packageSetting == null) {
6826                Slog.w(TAG, "Unknown permission " + name
6827                        + " in package " + pkg.packageName);
6828                continue;
6829            }
6830
6831            final String perm = bp.name;
6832            boolean allowed;
6833            boolean allowedSig = false;
6834            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6835                // Keep track of app op permissions.
6836                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6837                if (pkgs == null) {
6838                    pkgs = new ArraySet<>();
6839                    mAppOpPermissionPackages.put(bp.name, pkgs);
6840                }
6841                pkgs.add(pkg.packageName);
6842            }
6843            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6844            if (level == PermissionInfo.PROTECTION_NORMAL
6845                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6846                // We grant a normal or dangerous permission if any of the following
6847                // are true:
6848                // 1) The permission is required
6849                // 2) The permission is optional, but was granted in the past
6850                // 3) The permission is optional, but was requested by an
6851                //    app in /system (not /data)
6852                //
6853                // Otherwise, reject the permission.
6854                allowed = (required || origPermissions.contains(perm)
6855                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6856            } else if (bp.packageSetting == null) {
6857                // This permission is invalid; skip it.
6858                allowed = false;
6859            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6860                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6861                if (allowed) {
6862                    allowedSig = true;
6863                }
6864            } else {
6865                allowed = false;
6866            }
6867            if (DEBUG_INSTALL) {
6868                if (gp != ps) {
6869                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6870                }
6871            }
6872            if (allowed) {
6873                if (!isSystemApp(ps) && ps.permissionsFixed) {
6874                    // If this is an existing, non-system package, then
6875                    // we can't add any new permissions to it.
6876                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6877                        // Except...  if this is a permission that was added
6878                        // to the platform (note: need to only do this when
6879                        // updating the platform).
6880                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6881                    }
6882                }
6883                if (allowed) {
6884                    if (!gp.grantedPermissions.contains(perm)) {
6885                        changedPermission = true;
6886                        gp.grantedPermissions.add(perm);
6887                        gp.gids = appendInts(gp.gids, bp.gids);
6888                    } else if (!ps.haveGids) {
6889                        gp.gids = appendInts(gp.gids, bp.gids);
6890                    }
6891                } else {
6892                    Slog.w(TAG, "Not granting permission " + perm
6893                            + " to package " + pkg.packageName
6894                            + " because it was previously installed without");
6895                }
6896            } else {
6897                if (gp.grantedPermissions.remove(perm)) {
6898                    changedPermission = true;
6899                    gp.gids = removeInts(gp.gids, bp.gids);
6900                    Slog.i(TAG, "Un-granting permission " + perm
6901                            + " from package " + pkg.packageName
6902                            + " (protectionLevel=" + bp.protectionLevel
6903                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6904                            + ")");
6905                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6906                    // Don't print warning for app op permissions, since it is fine for them
6907                    // not to be granted, there is a UI for the user to decide.
6908                    Slog.w(TAG, "Not granting permission " + perm
6909                            + " to package " + pkg.packageName
6910                            + " (protectionLevel=" + bp.protectionLevel
6911                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6912                            + ")");
6913                }
6914            }
6915        }
6916
6917        if ((changedPermission || replace) && !ps.permissionsFixed &&
6918                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6919            // This is the first that we have heard about this package, so the
6920            // permissions we have now selected are fixed until explicitly
6921            // changed.
6922            ps.permissionsFixed = true;
6923        }
6924        ps.haveGids = true;
6925    }
6926
6927    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6928        boolean allowed = false;
6929        final int NP = PackageParser.NEW_PERMISSIONS.length;
6930        for (int ip=0; ip<NP; ip++) {
6931            final PackageParser.NewPermissionInfo npi
6932                    = PackageParser.NEW_PERMISSIONS[ip];
6933            if (npi.name.equals(perm)
6934                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6935                allowed = true;
6936                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6937                        + pkg.packageName);
6938                break;
6939            }
6940        }
6941        return allowed;
6942    }
6943
6944    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6945                                          BasePermission bp, HashSet<String> origPermissions) {
6946        boolean allowed;
6947        allowed = (compareSignatures(
6948                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6949                        == PackageManager.SIGNATURE_MATCH)
6950                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6951                        == PackageManager.SIGNATURE_MATCH);
6952        if (!allowed && (bp.protectionLevel
6953                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6954            if (isSystemApp(pkg)) {
6955                // For updated system applications, a system permission
6956                // is granted only if it had been defined by the original application.
6957                if (isUpdatedSystemApp(pkg)) {
6958                    final PackageSetting sysPs = mSettings
6959                            .getDisabledSystemPkgLPr(pkg.packageName);
6960                    final GrantedPermissions origGp = sysPs.sharedUser != null
6961                            ? sysPs.sharedUser : sysPs;
6962
6963                    if (origGp.grantedPermissions.contains(perm)) {
6964                        // If the original was granted this permission, we take
6965                        // that grant decision as read and propagate it to the
6966                        // update.
6967                        allowed = true;
6968                    } else {
6969                        // The system apk may have been updated with an older
6970                        // version of the one on the data partition, but which
6971                        // granted a new system permission that it didn't have
6972                        // before.  In this case we do want to allow the app to
6973                        // now get the new permission if the ancestral apk is
6974                        // privileged to get it.
6975                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6976                            for (int j=0;
6977                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6978                                if (perm.equals(
6979                                        sysPs.pkg.requestedPermissions.get(j))) {
6980                                    allowed = true;
6981                                    break;
6982                                }
6983                            }
6984                        }
6985                    }
6986                } else {
6987                    allowed = isPrivilegedApp(pkg);
6988                }
6989            }
6990        }
6991        if (!allowed && (bp.protectionLevel
6992                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6993            // For development permissions, a development permission
6994            // is granted only if it was already granted.
6995            allowed = origPermissions.contains(perm);
6996        }
6997        return allowed;
6998    }
6999
7000    final class ActivityIntentResolver
7001            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7002        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7003                boolean defaultOnly, int userId) {
7004            if (!sUserManager.exists(userId)) return null;
7005            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7006            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7007        }
7008
7009        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7010                int userId) {
7011            if (!sUserManager.exists(userId)) return null;
7012            mFlags = flags;
7013            return super.queryIntent(intent, resolvedType,
7014                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7015        }
7016
7017        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7018                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7019            if (!sUserManager.exists(userId)) return null;
7020            if (packageActivities == null) {
7021                return null;
7022            }
7023            mFlags = flags;
7024            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7025            final int N = packageActivities.size();
7026            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7027                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7028
7029            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7030            for (int i = 0; i < N; ++i) {
7031                intentFilters = packageActivities.get(i).intents;
7032                if (intentFilters != null && intentFilters.size() > 0) {
7033                    PackageParser.ActivityIntentInfo[] array =
7034                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7035                    intentFilters.toArray(array);
7036                    listCut.add(array);
7037                }
7038            }
7039            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7040        }
7041
7042        public final void addActivity(PackageParser.Activity a, String type) {
7043            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7044            mActivities.put(a.getComponentName(), a);
7045            if (DEBUG_SHOW_INFO)
7046                Log.v(
7047                TAG, "  " + type + " " +
7048                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7049            if (DEBUG_SHOW_INFO)
7050                Log.v(TAG, "    Class=" + a.info.name);
7051            final int NI = a.intents.size();
7052            for (int j=0; j<NI; j++) {
7053                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7054                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7055                    intent.setPriority(0);
7056                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7057                            + a.className + " with priority > 0, forcing to 0");
7058                }
7059                if (DEBUG_SHOW_INFO) {
7060                    Log.v(TAG, "    IntentFilter:");
7061                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7062                }
7063                if (!intent.debugCheck()) {
7064                    Log.w(TAG, "==> For Activity " + a.info.name);
7065                }
7066                addFilter(intent);
7067            }
7068        }
7069
7070        public final void removeActivity(PackageParser.Activity a, String type) {
7071            mActivities.remove(a.getComponentName());
7072            if (DEBUG_SHOW_INFO) {
7073                Log.v(TAG, "  " + type + " "
7074                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7075                                : a.info.name) + ":");
7076                Log.v(TAG, "    Class=" + a.info.name);
7077            }
7078            final int NI = a.intents.size();
7079            for (int j=0; j<NI; j++) {
7080                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7081                if (DEBUG_SHOW_INFO) {
7082                    Log.v(TAG, "    IntentFilter:");
7083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7084                }
7085                removeFilter(intent);
7086            }
7087        }
7088
7089        @Override
7090        protected boolean allowFilterResult(
7091                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7092            ActivityInfo filterAi = filter.activity.info;
7093            for (int i=dest.size()-1; i>=0; i--) {
7094                ActivityInfo destAi = dest.get(i).activityInfo;
7095                if (destAi.name == filterAi.name
7096                        && destAi.packageName == filterAi.packageName) {
7097                    return false;
7098                }
7099            }
7100            return true;
7101        }
7102
7103        @Override
7104        protected ActivityIntentInfo[] newArray(int size) {
7105            return new ActivityIntentInfo[size];
7106        }
7107
7108        @Override
7109        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7110            if (!sUserManager.exists(userId)) return true;
7111            PackageParser.Package p = filter.activity.owner;
7112            if (p != null) {
7113                PackageSetting ps = (PackageSetting)p.mExtras;
7114                if (ps != null) {
7115                    // System apps are never considered stopped for purposes of
7116                    // filtering, because there may be no way for the user to
7117                    // actually re-launch them.
7118                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7119                            && ps.getStopped(userId);
7120                }
7121            }
7122            return false;
7123        }
7124
7125        @Override
7126        protected boolean isPackageForFilter(String packageName,
7127                PackageParser.ActivityIntentInfo info) {
7128            return packageName.equals(info.activity.owner.packageName);
7129        }
7130
7131        @Override
7132        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7133                int match, int userId) {
7134            if (!sUserManager.exists(userId)) return null;
7135            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7136                return null;
7137            }
7138            final PackageParser.Activity activity = info.activity;
7139            if (mSafeMode && (activity.info.applicationInfo.flags
7140                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7141                return null;
7142            }
7143            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7144            if (ps == null) {
7145                return null;
7146            }
7147            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7148                    ps.readUserState(userId), userId);
7149            if (ai == null) {
7150                return null;
7151            }
7152            final ResolveInfo res = new ResolveInfo();
7153            res.activityInfo = ai;
7154            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7155                res.filter = info;
7156            }
7157            res.priority = info.getPriority();
7158            res.preferredOrder = activity.owner.mPreferredOrder;
7159            //System.out.println("Result: " + res.activityInfo.className +
7160            //                   " = " + res.priority);
7161            res.match = match;
7162            res.isDefault = info.hasDefault;
7163            res.labelRes = info.labelRes;
7164            res.nonLocalizedLabel = info.nonLocalizedLabel;
7165            if (userNeedsBadging(userId)) {
7166                res.noResourceId = true;
7167            } else {
7168                res.icon = info.icon;
7169            }
7170            res.system = isSystemApp(res.activityInfo.applicationInfo);
7171            return res;
7172        }
7173
7174        @Override
7175        protected void sortResults(List<ResolveInfo> results) {
7176            Collections.sort(results, mResolvePrioritySorter);
7177        }
7178
7179        @Override
7180        protected void dumpFilter(PrintWriter out, String prefix,
7181                PackageParser.ActivityIntentInfo filter) {
7182            out.print(prefix); out.print(
7183                    Integer.toHexString(System.identityHashCode(filter.activity)));
7184                    out.print(' ');
7185                    filter.activity.printComponentShortName(out);
7186                    out.print(" filter ");
7187                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7188        }
7189
7190//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7191//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7192//            final List<ResolveInfo> retList = Lists.newArrayList();
7193//            while (i.hasNext()) {
7194//                final ResolveInfo resolveInfo = i.next();
7195//                if (isEnabledLP(resolveInfo.activityInfo)) {
7196//                    retList.add(resolveInfo);
7197//                }
7198//            }
7199//            return retList;
7200//        }
7201
7202        // Keys are String (activity class name), values are Activity.
7203        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7204                = new HashMap<ComponentName, PackageParser.Activity>();
7205        private int mFlags;
7206    }
7207
7208    private final class ServiceIntentResolver
7209            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7210        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7211                boolean defaultOnly, int userId) {
7212            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7213            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7214        }
7215
7216        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7217                int userId) {
7218            if (!sUserManager.exists(userId)) return null;
7219            mFlags = flags;
7220            return super.queryIntent(intent, resolvedType,
7221                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7222        }
7223
7224        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7225                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7226            if (!sUserManager.exists(userId)) return null;
7227            if (packageServices == null) {
7228                return null;
7229            }
7230            mFlags = flags;
7231            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7232            final int N = packageServices.size();
7233            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7234                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7235
7236            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7237            for (int i = 0; i < N; ++i) {
7238                intentFilters = packageServices.get(i).intents;
7239                if (intentFilters != null && intentFilters.size() > 0) {
7240                    PackageParser.ServiceIntentInfo[] array =
7241                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7242                    intentFilters.toArray(array);
7243                    listCut.add(array);
7244                }
7245            }
7246            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7247        }
7248
7249        public final void addService(PackageParser.Service s) {
7250            mServices.put(s.getComponentName(), s);
7251            if (DEBUG_SHOW_INFO) {
7252                Log.v(TAG, "  "
7253                        + (s.info.nonLocalizedLabel != null
7254                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7255                Log.v(TAG, "    Class=" + s.info.name);
7256            }
7257            final int NI = s.intents.size();
7258            int j;
7259            for (j=0; j<NI; j++) {
7260                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7261                if (DEBUG_SHOW_INFO) {
7262                    Log.v(TAG, "    IntentFilter:");
7263                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7264                }
7265                if (!intent.debugCheck()) {
7266                    Log.w(TAG, "==> For Service " + s.info.name);
7267                }
7268                addFilter(intent);
7269            }
7270        }
7271
7272        public final void removeService(PackageParser.Service s) {
7273            mServices.remove(s.getComponentName());
7274            if (DEBUG_SHOW_INFO) {
7275                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7276                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7277                Log.v(TAG, "    Class=" + s.info.name);
7278            }
7279            final int NI = s.intents.size();
7280            int j;
7281            for (j=0; j<NI; j++) {
7282                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7283                if (DEBUG_SHOW_INFO) {
7284                    Log.v(TAG, "    IntentFilter:");
7285                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7286                }
7287                removeFilter(intent);
7288            }
7289        }
7290
7291        @Override
7292        protected boolean allowFilterResult(
7293                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7294            ServiceInfo filterSi = filter.service.info;
7295            for (int i=dest.size()-1; i>=0; i--) {
7296                ServiceInfo destAi = dest.get(i).serviceInfo;
7297                if (destAi.name == filterSi.name
7298                        && destAi.packageName == filterSi.packageName) {
7299                    return false;
7300                }
7301            }
7302            return true;
7303        }
7304
7305        @Override
7306        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7307            return new PackageParser.ServiceIntentInfo[size];
7308        }
7309
7310        @Override
7311        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7312            if (!sUserManager.exists(userId)) return true;
7313            PackageParser.Package p = filter.service.owner;
7314            if (p != null) {
7315                PackageSetting ps = (PackageSetting)p.mExtras;
7316                if (ps != null) {
7317                    // System apps are never considered stopped for purposes of
7318                    // filtering, because there may be no way for the user to
7319                    // actually re-launch them.
7320                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7321                            && ps.getStopped(userId);
7322                }
7323            }
7324            return false;
7325        }
7326
7327        @Override
7328        protected boolean isPackageForFilter(String packageName,
7329                PackageParser.ServiceIntentInfo info) {
7330            return packageName.equals(info.service.owner.packageName);
7331        }
7332
7333        @Override
7334        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7335                int match, int userId) {
7336            if (!sUserManager.exists(userId)) return null;
7337            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7338            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7339                return null;
7340            }
7341            final PackageParser.Service service = info.service;
7342            if (mSafeMode && (service.info.applicationInfo.flags
7343                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7344                return null;
7345            }
7346            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7347            if (ps == null) {
7348                return null;
7349            }
7350            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7351                    ps.readUserState(userId), userId);
7352            if (si == null) {
7353                return null;
7354            }
7355            final ResolveInfo res = new ResolveInfo();
7356            res.serviceInfo = si;
7357            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7358                res.filter = filter;
7359            }
7360            res.priority = info.getPriority();
7361            res.preferredOrder = service.owner.mPreferredOrder;
7362            //System.out.println("Result: " + res.activityInfo.className +
7363            //                   " = " + res.priority);
7364            res.match = match;
7365            res.isDefault = info.hasDefault;
7366            res.labelRes = info.labelRes;
7367            res.nonLocalizedLabel = info.nonLocalizedLabel;
7368            res.icon = info.icon;
7369            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7370            return res;
7371        }
7372
7373        @Override
7374        protected void sortResults(List<ResolveInfo> results) {
7375            Collections.sort(results, mResolvePrioritySorter);
7376        }
7377
7378        @Override
7379        protected void dumpFilter(PrintWriter out, String prefix,
7380                PackageParser.ServiceIntentInfo filter) {
7381            out.print(prefix); out.print(
7382                    Integer.toHexString(System.identityHashCode(filter.service)));
7383                    out.print(' ');
7384                    filter.service.printComponentShortName(out);
7385                    out.print(" filter ");
7386                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7387        }
7388
7389//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7390//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7391//            final List<ResolveInfo> retList = Lists.newArrayList();
7392//            while (i.hasNext()) {
7393//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7394//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7395//                    retList.add(resolveInfo);
7396//                }
7397//            }
7398//            return retList;
7399//        }
7400
7401        // Keys are String (activity class name), values are Activity.
7402        private final HashMap<ComponentName, PackageParser.Service> mServices
7403                = new HashMap<ComponentName, PackageParser.Service>();
7404        private int mFlags;
7405    };
7406
7407    private final class ProviderIntentResolver
7408            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7409        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7410                boolean defaultOnly, int userId) {
7411            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7412            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7413        }
7414
7415        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7416                int userId) {
7417            if (!sUserManager.exists(userId))
7418                return null;
7419            mFlags = flags;
7420            return super.queryIntent(intent, resolvedType,
7421                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7422        }
7423
7424        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7425                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7426            if (!sUserManager.exists(userId))
7427                return null;
7428            if (packageProviders == null) {
7429                return null;
7430            }
7431            mFlags = flags;
7432            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7433            final int N = packageProviders.size();
7434            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7435                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7436
7437            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7438            for (int i = 0; i < N; ++i) {
7439                intentFilters = packageProviders.get(i).intents;
7440                if (intentFilters != null && intentFilters.size() > 0) {
7441                    PackageParser.ProviderIntentInfo[] array =
7442                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7443                    intentFilters.toArray(array);
7444                    listCut.add(array);
7445                }
7446            }
7447            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7448        }
7449
7450        public final void addProvider(PackageParser.Provider p) {
7451            if (mProviders.containsKey(p.getComponentName())) {
7452                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7453                return;
7454            }
7455
7456            mProviders.put(p.getComponentName(), p);
7457            if (DEBUG_SHOW_INFO) {
7458                Log.v(TAG, "  "
7459                        + (p.info.nonLocalizedLabel != null
7460                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7461                Log.v(TAG, "    Class=" + p.info.name);
7462            }
7463            final int NI = p.intents.size();
7464            int j;
7465            for (j = 0; j < NI; j++) {
7466                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7467                if (DEBUG_SHOW_INFO) {
7468                    Log.v(TAG, "    IntentFilter:");
7469                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7470                }
7471                if (!intent.debugCheck()) {
7472                    Log.w(TAG, "==> For Provider " + p.info.name);
7473                }
7474                addFilter(intent);
7475            }
7476        }
7477
7478        public final void removeProvider(PackageParser.Provider p) {
7479            mProviders.remove(p.getComponentName());
7480            if (DEBUG_SHOW_INFO) {
7481                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7482                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7483                Log.v(TAG, "    Class=" + p.info.name);
7484            }
7485            final int NI = p.intents.size();
7486            int j;
7487            for (j = 0; j < NI; j++) {
7488                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7489                if (DEBUG_SHOW_INFO) {
7490                    Log.v(TAG, "    IntentFilter:");
7491                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7492                }
7493                removeFilter(intent);
7494            }
7495        }
7496
7497        @Override
7498        protected boolean allowFilterResult(
7499                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7500            ProviderInfo filterPi = filter.provider.info;
7501            for (int i = dest.size() - 1; i >= 0; i--) {
7502                ProviderInfo destPi = dest.get(i).providerInfo;
7503                if (destPi.name == filterPi.name
7504                        && destPi.packageName == filterPi.packageName) {
7505                    return false;
7506                }
7507            }
7508            return true;
7509        }
7510
7511        @Override
7512        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7513            return new PackageParser.ProviderIntentInfo[size];
7514        }
7515
7516        @Override
7517        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7518            if (!sUserManager.exists(userId))
7519                return true;
7520            PackageParser.Package p = filter.provider.owner;
7521            if (p != null) {
7522                PackageSetting ps = (PackageSetting) p.mExtras;
7523                if (ps != null) {
7524                    // System apps are never considered stopped for purposes of
7525                    // filtering, because there may be no way for the user to
7526                    // actually re-launch them.
7527                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7528                            && ps.getStopped(userId);
7529                }
7530            }
7531            return false;
7532        }
7533
7534        @Override
7535        protected boolean isPackageForFilter(String packageName,
7536                PackageParser.ProviderIntentInfo info) {
7537            return packageName.equals(info.provider.owner.packageName);
7538        }
7539
7540        @Override
7541        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7542                int match, int userId) {
7543            if (!sUserManager.exists(userId))
7544                return null;
7545            final PackageParser.ProviderIntentInfo info = filter;
7546            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7547                return null;
7548            }
7549            final PackageParser.Provider provider = info.provider;
7550            if (mSafeMode && (provider.info.applicationInfo.flags
7551                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7552                return null;
7553            }
7554            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7555            if (ps == null) {
7556                return null;
7557            }
7558            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7559                    ps.readUserState(userId), userId);
7560            if (pi == null) {
7561                return null;
7562            }
7563            final ResolveInfo res = new ResolveInfo();
7564            res.providerInfo = pi;
7565            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7566                res.filter = filter;
7567            }
7568            res.priority = info.getPriority();
7569            res.preferredOrder = provider.owner.mPreferredOrder;
7570            res.match = match;
7571            res.isDefault = info.hasDefault;
7572            res.labelRes = info.labelRes;
7573            res.nonLocalizedLabel = info.nonLocalizedLabel;
7574            res.icon = info.icon;
7575            res.system = isSystemApp(res.providerInfo.applicationInfo);
7576            return res;
7577        }
7578
7579        @Override
7580        protected void sortResults(List<ResolveInfo> results) {
7581            Collections.sort(results, mResolvePrioritySorter);
7582        }
7583
7584        @Override
7585        protected void dumpFilter(PrintWriter out, String prefix,
7586                PackageParser.ProviderIntentInfo filter) {
7587            out.print(prefix);
7588            out.print(
7589                    Integer.toHexString(System.identityHashCode(filter.provider)));
7590            out.print(' ');
7591            filter.provider.printComponentShortName(out);
7592            out.print(" filter ");
7593            out.println(Integer.toHexString(System.identityHashCode(filter)));
7594        }
7595
7596        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7597                = new HashMap<ComponentName, PackageParser.Provider>();
7598        private int mFlags;
7599    };
7600
7601    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7602            new Comparator<ResolveInfo>() {
7603        public int compare(ResolveInfo r1, ResolveInfo r2) {
7604            int v1 = r1.priority;
7605            int v2 = r2.priority;
7606            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7607            if (v1 != v2) {
7608                return (v1 > v2) ? -1 : 1;
7609            }
7610            v1 = r1.preferredOrder;
7611            v2 = r2.preferredOrder;
7612            if (v1 != v2) {
7613                return (v1 > v2) ? -1 : 1;
7614            }
7615            if (r1.isDefault != r2.isDefault) {
7616                return r1.isDefault ? -1 : 1;
7617            }
7618            v1 = r1.match;
7619            v2 = r2.match;
7620            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7621            if (v1 != v2) {
7622                return (v1 > v2) ? -1 : 1;
7623            }
7624            if (r1.system != r2.system) {
7625                return r1.system ? -1 : 1;
7626            }
7627            return 0;
7628        }
7629    };
7630
7631    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7632            new Comparator<ProviderInfo>() {
7633        public int compare(ProviderInfo p1, ProviderInfo p2) {
7634            final int v1 = p1.initOrder;
7635            final int v2 = p2.initOrder;
7636            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7637        }
7638    };
7639
7640    static final void sendPackageBroadcast(String action, String pkg,
7641            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7642            int[] userIds) {
7643        IActivityManager am = ActivityManagerNative.getDefault();
7644        if (am != null) {
7645            try {
7646                if (userIds == null) {
7647                    userIds = am.getRunningUserIds();
7648                }
7649                for (int id : userIds) {
7650                    final Intent intent = new Intent(action,
7651                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7652                    if (extras != null) {
7653                        intent.putExtras(extras);
7654                    }
7655                    if (targetPkg != null) {
7656                        intent.setPackage(targetPkg);
7657                    }
7658                    // Modify the UID when posting to other users
7659                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7660                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7661                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7662                        intent.putExtra(Intent.EXTRA_UID, uid);
7663                    }
7664                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7665                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7666                    if (DEBUG_BROADCASTS) {
7667                        RuntimeException here = new RuntimeException("here");
7668                        here.fillInStackTrace();
7669                        Slog.d(TAG, "Sending to user " + id + ": "
7670                                + intent.toShortString(false, true, false, false)
7671                                + " " + intent.getExtras(), here);
7672                    }
7673                    am.broadcastIntent(null, intent, null, finishedReceiver,
7674                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7675                            finishedReceiver != null, false, id);
7676                }
7677            } catch (RemoteException ex) {
7678            }
7679        }
7680    }
7681
7682    /**
7683     * Check if the external storage media is available. This is true if there
7684     * is a mounted external storage medium or if the external storage is
7685     * emulated.
7686     */
7687    private boolean isExternalMediaAvailable() {
7688        return mMediaMounted || Environment.isExternalStorageEmulated();
7689    }
7690
7691    @Override
7692    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7693        // writer
7694        synchronized (mPackages) {
7695            if (!isExternalMediaAvailable()) {
7696                // If the external storage is no longer mounted at this point,
7697                // the caller may not have been able to delete all of this
7698                // packages files and can not delete any more.  Bail.
7699                return null;
7700            }
7701            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7702            if (lastPackage != null) {
7703                pkgs.remove(lastPackage);
7704            }
7705            if (pkgs.size() > 0) {
7706                return pkgs.get(0);
7707            }
7708        }
7709        return null;
7710    }
7711
7712    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7713        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7714                userId, andCode ? 1 : 0, packageName);
7715        if (mSystemReady) {
7716            msg.sendToTarget();
7717        } else {
7718            if (mPostSystemReadyMessages == null) {
7719                mPostSystemReadyMessages = new ArrayList<>();
7720            }
7721            mPostSystemReadyMessages.add(msg);
7722        }
7723    }
7724
7725    void startCleaningPackages() {
7726        // reader
7727        synchronized (mPackages) {
7728            if (!isExternalMediaAvailable()) {
7729                return;
7730            }
7731            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7732                return;
7733            }
7734        }
7735        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7736        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7737        IActivityManager am = ActivityManagerNative.getDefault();
7738        if (am != null) {
7739            try {
7740                am.startService(null, intent, null, UserHandle.USER_OWNER);
7741            } catch (RemoteException e) {
7742            }
7743        }
7744    }
7745
7746    @Override
7747    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7748            int installFlags, String installerPackageName, VerificationParams verificationParams,
7749            String packageAbiOverride) {
7750        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7751                packageAbiOverride, UserHandle.getCallingUserId());
7752    }
7753
7754    @Override
7755    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7756            int installFlags, String installerPackageName, VerificationParams verificationParams,
7757            String packageAbiOverride, int userId) {
7758        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7759                null);
7760        if (UserHandle.getCallingUserId() != userId) {
7761            mContext.enforceCallingOrSelfPermission(
7762                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7763                    "installPackage " + userId);
7764        }
7765
7766        final File originFile = new File(originPath);
7767        final int uid = Binder.getCallingUid();
7768        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7769            try {
7770                if (observer != null) {
7771                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7772                }
7773            } catch (RemoteException re) {
7774            }
7775            return;
7776        }
7777
7778        UserHandle user;
7779        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7780            user = UserHandle.ALL;
7781        } else {
7782            user = new UserHandle(userId);
7783        }
7784
7785        final int filteredInstallFlags;
7786        if (uid == Process.SHELL_UID || uid == 0) {
7787            if (DEBUG_INSTALL) {
7788                Slog.v(TAG, "Install from ADB");
7789            }
7790            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7791        } else {
7792            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7793        }
7794
7795        verificationParams.setInstallerUid(uid);
7796
7797        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7798
7799        final Message msg = mHandler.obtainMessage(INIT_COPY);
7800        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7801                installerPackageName, verificationParams, user, packageAbiOverride);
7802        mHandler.sendMessage(msg);
7803    }
7804
7805    void installStage(String packageName, File stagedDir, String stagedCid,
7806            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7807            String installerPackageName, int installerUid, UserHandle user) {
7808        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7809                params.referrerUri, installerUid, null);
7810
7811        final OriginInfo origin;
7812        if (stagedDir != null) {
7813            origin = OriginInfo.fromStagedFile(stagedDir);
7814        } else {
7815            origin = OriginInfo.fromStagedContainer(stagedCid);
7816        }
7817
7818        final Message msg = mHandler.obtainMessage(INIT_COPY);
7819        msg.obj = new InstallParams(origin, observer, params.installFlags,
7820                installerPackageName, verifParams, user, params.abiOverride);
7821        mHandler.sendMessage(msg);
7822    }
7823
7824    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7825        Bundle extras = new Bundle(1);
7826        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7827
7828        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7829                packageName, extras, null, null, new int[] {userId});
7830        try {
7831            IActivityManager am = ActivityManagerNative.getDefault();
7832            final boolean isSystem =
7833                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7834            if (isSystem && am.isUserRunning(userId, false)) {
7835                // The just-installed/enabled app is bundled on the system, so presumed
7836                // to be able to run automatically without needing an explicit launch.
7837                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7838                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7839                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7840                        .setPackage(packageName);
7841                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7842                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7843            }
7844        } catch (RemoteException e) {
7845            // shouldn't happen
7846            Slog.w(TAG, "Unable to bootstrap installed package", e);
7847        }
7848    }
7849
7850    @Override
7851    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7852            int userId) {
7853        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7854        PackageSetting pkgSetting;
7855        final int uid = Binder.getCallingUid();
7856        enforceCrossUserPermission(uid, userId, true, true,
7857                "setApplicationHiddenSetting for user " + userId);
7858
7859        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7860            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7861            return false;
7862        }
7863
7864        long callingId = Binder.clearCallingIdentity();
7865        try {
7866            boolean sendAdded = false;
7867            boolean sendRemoved = false;
7868            // writer
7869            synchronized (mPackages) {
7870                pkgSetting = mSettings.mPackages.get(packageName);
7871                if (pkgSetting == null) {
7872                    return false;
7873                }
7874                if (pkgSetting.getHidden(userId) != hidden) {
7875                    pkgSetting.setHidden(hidden, userId);
7876                    mSettings.writePackageRestrictionsLPr(userId);
7877                    if (hidden) {
7878                        sendRemoved = true;
7879                    } else {
7880                        sendAdded = true;
7881                    }
7882                }
7883            }
7884            if (sendAdded) {
7885                sendPackageAddedForUser(packageName, pkgSetting, userId);
7886                return true;
7887            }
7888            if (sendRemoved) {
7889                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7890                        "hiding pkg");
7891                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7892            }
7893        } finally {
7894            Binder.restoreCallingIdentity(callingId);
7895        }
7896        return false;
7897    }
7898
7899    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7900            int userId) {
7901        final PackageRemovedInfo info = new PackageRemovedInfo();
7902        info.removedPackage = packageName;
7903        info.removedUsers = new int[] {userId};
7904        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7905        info.sendBroadcast(false, false, false);
7906    }
7907
7908    /**
7909     * Returns true if application is not found or there was an error. Otherwise it returns
7910     * the hidden state of the package for the given user.
7911     */
7912    @Override
7913    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7914        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7915        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7916                false, "getApplicationHidden for user " + userId);
7917        PackageSetting pkgSetting;
7918        long callingId = Binder.clearCallingIdentity();
7919        try {
7920            // writer
7921            synchronized (mPackages) {
7922                pkgSetting = mSettings.mPackages.get(packageName);
7923                if (pkgSetting == null) {
7924                    return true;
7925                }
7926                return pkgSetting.getHidden(userId);
7927            }
7928        } finally {
7929            Binder.restoreCallingIdentity(callingId);
7930        }
7931    }
7932
7933    /**
7934     * @hide
7935     */
7936    @Override
7937    public int installExistingPackageAsUser(String packageName, int userId) {
7938        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7939                null);
7940        PackageSetting pkgSetting;
7941        final int uid = Binder.getCallingUid();
7942        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7943                + userId);
7944        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7945            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7946        }
7947
7948        long callingId = Binder.clearCallingIdentity();
7949        try {
7950            boolean sendAdded = false;
7951            Bundle extras = new Bundle(1);
7952
7953            // writer
7954            synchronized (mPackages) {
7955                pkgSetting = mSettings.mPackages.get(packageName);
7956                if (pkgSetting == null) {
7957                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7958                }
7959                if (!pkgSetting.getInstalled(userId)) {
7960                    pkgSetting.setInstalled(true, userId);
7961                    pkgSetting.setHidden(false, userId);
7962                    mSettings.writePackageRestrictionsLPr(userId);
7963                    sendAdded = true;
7964                }
7965            }
7966
7967            if (sendAdded) {
7968                sendPackageAddedForUser(packageName, pkgSetting, userId);
7969            }
7970        } finally {
7971            Binder.restoreCallingIdentity(callingId);
7972        }
7973
7974        return PackageManager.INSTALL_SUCCEEDED;
7975    }
7976
7977    boolean isUserRestricted(int userId, String restrictionKey) {
7978        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7979        if (restrictions.getBoolean(restrictionKey, false)) {
7980            Log.w(TAG, "User is restricted: " + restrictionKey);
7981            return true;
7982        }
7983        return false;
7984    }
7985
7986    @Override
7987    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7988        mContext.enforceCallingOrSelfPermission(
7989                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7990                "Only package verification agents can verify applications");
7991
7992        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7993        final PackageVerificationResponse response = new PackageVerificationResponse(
7994                verificationCode, Binder.getCallingUid());
7995        msg.arg1 = id;
7996        msg.obj = response;
7997        mHandler.sendMessage(msg);
7998    }
7999
8000    @Override
8001    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8002            long millisecondsToDelay) {
8003        mContext.enforceCallingOrSelfPermission(
8004                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8005                "Only package verification agents can extend verification timeouts");
8006
8007        final PackageVerificationState state = mPendingVerification.get(id);
8008        final PackageVerificationResponse response = new PackageVerificationResponse(
8009                verificationCodeAtTimeout, Binder.getCallingUid());
8010
8011        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8012            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8013        }
8014        if (millisecondsToDelay < 0) {
8015            millisecondsToDelay = 0;
8016        }
8017        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8018                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8019            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8020        }
8021
8022        if ((state != null) && !state.timeoutExtended()) {
8023            state.extendTimeout();
8024
8025            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8026            msg.arg1 = id;
8027            msg.obj = response;
8028            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8029        }
8030    }
8031
8032    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8033            int verificationCode, UserHandle user) {
8034        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8035        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8036        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8037        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8038        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8039
8040        mContext.sendBroadcastAsUser(intent, user,
8041                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8042    }
8043
8044    private ComponentName matchComponentForVerifier(String packageName,
8045            List<ResolveInfo> receivers) {
8046        ActivityInfo targetReceiver = null;
8047
8048        final int NR = receivers.size();
8049        for (int i = 0; i < NR; i++) {
8050            final ResolveInfo info = receivers.get(i);
8051            if (info.activityInfo == null) {
8052                continue;
8053            }
8054
8055            if (packageName.equals(info.activityInfo.packageName)) {
8056                targetReceiver = info.activityInfo;
8057                break;
8058            }
8059        }
8060
8061        if (targetReceiver == null) {
8062            return null;
8063        }
8064
8065        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8066    }
8067
8068    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8069            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8070        if (pkgInfo.verifiers.length == 0) {
8071            return null;
8072        }
8073
8074        final int N = pkgInfo.verifiers.length;
8075        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8076        for (int i = 0; i < N; i++) {
8077            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8078
8079            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8080                    receivers);
8081            if (comp == null) {
8082                continue;
8083            }
8084
8085            final int verifierUid = getUidForVerifier(verifierInfo);
8086            if (verifierUid == -1) {
8087                continue;
8088            }
8089
8090            if (DEBUG_VERIFY) {
8091                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8092                        + " with the correct signature");
8093            }
8094            sufficientVerifiers.add(comp);
8095            verificationState.addSufficientVerifier(verifierUid);
8096        }
8097
8098        return sufficientVerifiers;
8099    }
8100
8101    private int getUidForVerifier(VerifierInfo verifierInfo) {
8102        synchronized (mPackages) {
8103            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8104            if (pkg == null) {
8105                return -1;
8106            } else if (pkg.mSignatures.length != 1) {
8107                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8108                        + " has more than one signature; ignoring");
8109                return -1;
8110            }
8111
8112            /*
8113             * If the public key of the package's signature does not match
8114             * our expected public key, then this is a different package and
8115             * we should skip.
8116             */
8117
8118            final byte[] expectedPublicKey;
8119            try {
8120                final Signature verifierSig = pkg.mSignatures[0];
8121                final PublicKey publicKey = verifierSig.getPublicKey();
8122                expectedPublicKey = publicKey.getEncoded();
8123            } catch (CertificateException e) {
8124                return -1;
8125            }
8126
8127            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8128
8129            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8130                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8131                        + " does not have the expected public key; ignoring");
8132                return -1;
8133            }
8134
8135            return pkg.applicationInfo.uid;
8136        }
8137    }
8138
8139    @Override
8140    public void finishPackageInstall(int token) {
8141        enforceSystemOrRoot("Only the system is allowed to finish installs");
8142
8143        if (DEBUG_INSTALL) {
8144            Slog.v(TAG, "BM finishing package install for " + token);
8145        }
8146
8147        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8148        mHandler.sendMessage(msg);
8149    }
8150
8151    /**
8152     * Get the verification agent timeout.
8153     *
8154     * @return verification timeout in milliseconds
8155     */
8156    private long getVerificationTimeout() {
8157        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8158                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8159                DEFAULT_VERIFICATION_TIMEOUT);
8160    }
8161
8162    /**
8163     * Get the default verification agent response code.
8164     *
8165     * @return default verification response code
8166     */
8167    private int getDefaultVerificationResponse() {
8168        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8169                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8170                DEFAULT_VERIFICATION_RESPONSE);
8171    }
8172
8173    /**
8174     * Check whether or not package verification has been enabled.
8175     *
8176     * @return true if verification should be performed
8177     */
8178    private boolean isVerificationEnabled(int userId, int installFlags) {
8179        if (!DEFAULT_VERIFY_ENABLE) {
8180            return false;
8181        }
8182
8183        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8184
8185        // Check if installing from ADB
8186        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8187            // Do not run verification in a test harness environment
8188            if (ActivityManager.isRunningInTestHarness()) {
8189                return false;
8190            }
8191            if (ensureVerifyAppsEnabled) {
8192                return true;
8193            }
8194            // Check if the developer does not want package verification for ADB installs
8195            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8196                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8197                return false;
8198            }
8199        }
8200
8201        if (ensureVerifyAppsEnabled) {
8202            return true;
8203        }
8204
8205        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8206                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8207    }
8208
8209    /**
8210     * Get the "allow unknown sources" setting.
8211     *
8212     * @return the current "allow unknown sources" setting
8213     */
8214    private int getUnknownSourcesSettings() {
8215        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8216                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8217                -1);
8218    }
8219
8220    @Override
8221    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8222        final int uid = Binder.getCallingUid();
8223        // writer
8224        synchronized (mPackages) {
8225            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8226            if (targetPackageSetting == null) {
8227                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8228            }
8229
8230            PackageSetting installerPackageSetting;
8231            if (installerPackageName != null) {
8232                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8233                if (installerPackageSetting == null) {
8234                    throw new IllegalArgumentException("Unknown installer package: "
8235                            + installerPackageName);
8236                }
8237            } else {
8238                installerPackageSetting = null;
8239            }
8240
8241            Signature[] callerSignature;
8242            Object obj = mSettings.getUserIdLPr(uid);
8243            if (obj != null) {
8244                if (obj instanceof SharedUserSetting) {
8245                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8246                } else if (obj instanceof PackageSetting) {
8247                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8248                } else {
8249                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8250                }
8251            } else {
8252                throw new SecurityException("Unknown calling uid " + uid);
8253            }
8254
8255            // Verify: can't set installerPackageName to a package that is
8256            // not signed with the same cert as the caller.
8257            if (installerPackageSetting != null) {
8258                if (compareSignatures(callerSignature,
8259                        installerPackageSetting.signatures.mSignatures)
8260                        != PackageManager.SIGNATURE_MATCH) {
8261                    throw new SecurityException(
8262                            "Caller does not have same cert as new installer package "
8263                            + installerPackageName);
8264                }
8265            }
8266
8267            // Verify: if target already has an installer package, it must
8268            // be signed with the same cert as the caller.
8269            if (targetPackageSetting.installerPackageName != null) {
8270                PackageSetting setting = mSettings.mPackages.get(
8271                        targetPackageSetting.installerPackageName);
8272                // If the currently set package isn't valid, then it's always
8273                // okay to change it.
8274                if (setting != null) {
8275                    if (compareSignatures(callerSignature,
8276                            setting.signatures.mSignatures)
8277                            != PackageManager.SIGNATURE_MATCH) {
8278                        throw new SecurityException(
8279                                "Caller does not have same cert as old installer package "
8280                                + targetPackageSetting.installerPackageName);
8281                    }
8282                }
8283            }
8284
8285            // Okay!
8286            targetPackageSetting.installerPackageName = installerPackageName;
8287            scheduleWriteSettingsLocked();
8288        }
8289    }
8290
8291    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8292        // Queue up an async operation since the package installation may take a little while.
8293        mHandler.post(new Runnable() {
8294            public void run() {
8295                mHandler.removeCallbacks(this);
8296                 // Result object to be returned
8297                PackageInstalledInfo res = new PackageInstalledInfo();
8298                res.returnCode = currentStatus;
8299                res.uid = -1;
8300                res.pkg = null;
8301                res.removedInfo = new PackageRemovedInfo();
8302                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8303                    args.doPreInstall(res.returnCode);
8304                    synchronized (mInstallLock) {
8305                        installPackageLI(args, res);
8306                    }
8307                    args.doPostInstall(res.returnCode, res.uid);
8308                }
8309
8310                // A restore should be performed at this point if (a) the install
8311                // succeeded, (b) the operation is not an update, and (c) the new
8312                // package has not opted out of backup participation.
8313                final boolean update = res.removedInfo.removedPackage != null;
8314                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8315                boolean doRestore = !update
8316                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8317
8318                // Set up the post-install work request bookkeeping.  This will be used
8319                // and cleaned up by the post-install event handling regardless of whether
8320                // there's a restore pass performed.  Token values are >= 1.
8321                int token;
8322                if (mNextInstallToken < 0) mNextInstallToken = 1;
8323                token = mNextInstallToken++;
8324
8325                PostInstallData data = new PostInstallData(args, res);
8326                mRunningInstalls.put(token, data);
8327                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8328
8329                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8330                    // Pass responsibility to the Backup Manager.  It will perform a
8331                    // restore if appropriate, then pass responsibility back to the
8332                    // Package Manager to run the post-install observer callbacks
8333                    // and broadcasts.
8334                    IBackupManager bm = IBackupManager.Stub.asInterface(
8335                            ServiceManager.getService(Context.BACKUP_SERVICE));
8336                    if (bm != null) {
8337                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8338                                + " to BM for possible restore");
8339                        try {
8340                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8341                        } catch (RemoteException e) {
8342                            // can't happen; the backup manager is local
8343                        } catch (Exception e) {
8344                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8345                            doRestore = false;
8346                        }
8347                    } else {
8348                        Slog.e(TAG, "Backup Manager not found!");
8349                        doRestore = false;
8350                    }
8351                }
8352
8353                if (!doRestore) {
8354                    // No restore possible, or the Backup Manager was mysteriously not
8355                    // available -- just fire the post-install work request directly.
8356                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8357                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8358                    mHandler.sendMessage(msg);
8359                }
8360            }
8361        });
8362    }
8363
8364    private abstract class HandlerParams {
8365        private static final int MAX_RETRIES = 4;
8366
8367        /**
8368         * Number of times startCopy() has been attempted and had a non-fatal
8369         * error.
8370         */
8371        private int mRetries = 0;
8372
8373        /** User handle for the user requesting the information or installation. */
8374        private final UserHandle mUser;
8375
8376        HandlerParams(UserHandle user) {
8377            mUser = user;
8378        }
8379
8380        UserHandle getUser() {
8381            return mUser;
8382        }
8383
8384        final boolean startCopy() {
8385            boolean res;
8386            try {
8387                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8388
8389                if (++mRetries > MAX_RETRIES) {
8390                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8391                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8392                    handleServiceError();
8393                    return false;
8394                } else {
8395                    handleStartCopy();
8396                    res = true;
8397                }
8398            } catch (RemoteException e) {
8399                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8400                mHandler.sendEmptyMessage(MCS_RECONNECT);
8401                res = false;
8402            }
8403            handleReturnCode();
8404            return res;
8405        }
8406
8407        final void serviceError() {
8408            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8409            handleServiceError();
8410            handleReturnCode();
8411        }
8412
8413        abstract void handleStartCopy() throws RemoteException;
8414        abstract void handleServiceError();
8415        abstract void handleReturnCode();
8416    }
8417
8418    class MeasureParams extends HandlerParams {
8419        private final PackageStats mStats;
8420        private boolean mSuccess;
8421
8422        private final IPackageStatsObserver mObserver;
8423
8424        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8425            super(new UserHandle(stats.userHandle));
8426            mObserver = observer;
8427            mStats = stats;
8428        }
8429
8430        @Override
8431        public String toString() {
8432            return "MeasureParams{"
8433                + Integer.toHexString(System.identityHashCode(this))
8434                + " " + mStats.packageName + "}";
8435        }
8436
8437        @Override
8438        void handleStartCopy() throws RemoteException {
8439            synchronized (mInstallLock) {
8440                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8441            }
8442
8443            if (mSuccess) {
8444                final boolean mounted;
8445                if (Environment.isExternalStorageEmulated()) {
8446                    mounted = true;
8447                } else {
8448                    final String status = Environment.getExternalStorageState();
8449                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8450                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8451                }
8452
8453                if (mounted) {
8454                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8455
8456                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8457                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8458
8459                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8460                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8461
8462                    // Always subtract cache size, since it's a subdirectory
8463                    mStats.externalDataSize -= mStats.externalCacheSize;
8464
8465                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8466                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8467
8468                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8469                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8470                }
8471            }
8472        }
8473
8474        @Override
8475        void handleReturnCode() {
8476            if (mObserver != null) {
8477                try {
8478                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8479                } catch (RemoteException e) {
8480                    Slog.i(TAG, "Observer no longer exists.");
8481                }
8482            }
8483        }
8484
8485        @Override
8486        void handleServiceError() {
8487            Slog.e(TAG, "Could not measure application " + mStats.packageName
8488                            + " external storage");
8489        }
8490    }
8491
8492    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8493            throws RemoteException {
8494        long result = 0;
8495        for (File path : paths) {
8496            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8497        }
8498        return result;
8499    }
8500
8501    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8502        for (File path : paths) {
8503            try {
8504                mcs.clearDirectory(path.getAbsolutePath());
8505            } catch (RemoteException e) {
8506            }
8507        }
8508    }
8509
8510    static class OriginInfo {
8511        /**
8512         * Location where install is coming from, before it has been
8513         * copied/renamed into place. This could be a single monolithic APK
8514         * file, or a cluster directory. This location may be untrusted.
8515         */
8516        final File file;
8517        final String cid;
8518
8519        /**
8520         * Flag indicating that {@link #file} or {@link #cid} has already been
8521         * staged, meaning downstream users don't need to defensively copy the
8522         * contents.
8523         */
8524        final boolean staged;
8525
8526        /**
8527         * Flag indicating that {@link #file} or {@link #cid} is an already
8528         * installed app that is being moved.
8529         */
8530        final boolean existing;
8531
8532        final String resolvedPath;
8533        final File resolvedFile;
8534
8535        static OriginInfo fromNothing() {
8536            return new OriginInfo(null, null, false, false);
8537        }
8538
8539        static OriginInfo fromUntrustedFile(File file) {
8540            return new OriginInfo(file, null, false, false);
8541        }
8542
8543        static OriginInfo fromExistingFile(File file) {
8544            return new OriginInfo(file, null, false, true);
8545        }
8546
8547        static OriginInfo fromStagedFile(File file) {
8548            return new OriginInfo(file, null, true, false);
8549        }
8550
8551        static OriginInfo fromStagedContainer(String cid) {
8552            return new OriginInfo(null, cid, true, false);
8553        }
8554
8555        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8556            this.file = file;
8557            this.cid = cid;
8558            this.staged = staged;
8559            this.existing = existing;
8560
8561            if (cid != null) {
8562                resolvedPath = PackageHelper.getSdDir(cid);
8563                resolvedFile = new File(resolvedPath);
8564            } else if (file != null) {
8565                resolvedPath = file.getAbsolutePath();
8566                resolvedFile = file;
8567            } else {
8568                resolvedPath = null;
8569                resolvedFile = null;
8570            }
8571        }
8572    }
8573
8574    class InstallParams extends HandlerParams {
8575        final OriginInfo origin;
8576        final IPackageInstallObserver2 observer;
8577        int installFlags;
8578        final String installerPackageName;
8579        final VerificationParams verificationParams;
8580        private InstallArgs mArgs;
8581        private int mRet;
8582        final String packageAbiOverride;
8583
8584        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8585                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8586                String packageAbiOverride) {
8587            super(user);
8588            this.origin = origin;
8589            this.observer = observer;
8590            this.installFlags = installFlags;
8591            this.installerPackageName = installerPackageName;
8592            this.verificationParams = verificationParams;
8593            this.packageAbiOverride = packageAbiOverride;
8594        }
8595
8596        @Override
8597        public String toString() {
8598            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8599                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8600        }
8601
8602        public ManifestDigest getManifestDigest() {
8603            if (verificationParams == null) {
8604                return null;
8605            }
8606            return verificationParams.getManifestDigest();
8607        }
8608
8609        private int installLocationPolicy(PackageInfoLite pkgLite) {
8610            String packageName = pkgLite.packageName;
8611            int installLocation = pkgLite.installLocation;
8612            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8613            // reader
8614            synchronized (mPackages) {
8615                PackageParser.Package pkg = mPackages.get(packageName);
8616                if (pkg != null) {
8617                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8618                        // Check for downgrading.
8619                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8620                            if (pkgLite.versionCode < pkg.mVersionCode) {
8621                                Slog.w(TAG, "Can't install update of " + packageName
8622                                        + " update version " + pkgLite.versionCode
8623                                        + " is older than installed version "
8624                                        + pkg.mVersionCode);
8625                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8626                            }
8627                        }
8628                        // Check for updated system application.
8629                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8630                            if (onSd) {
8631                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8632                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8633                            }
8634                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8635                        } else {
8636                            if (onSd) {
8637                                // Install flag overrides everything.
8638                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8639                            }
8640                            // If current upgrade specifies particular preference
8641                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8642                                // Application explicitly specified internal.
8643                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8644                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8645                                // App explictly prefers external. Let policy decide
8646                            } else {
8647                                // Prefer previous location
8648                                if (isExternal(pkg)) {
8649                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8650                                }
8651                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8652                            }
8653                        }
8654                    } else {
8655                        // Invalid install. Return error code
8656                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8657                    }
8658                }
8659            }
8660            // All the special cases have been taken care of.
8661            // Return result based on recommended install location.
8662            if (onSd) {
8663                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8664            }
8665            return pkgLite.recommendedInstallLocation;
8666        }
8667
8668        /*
8669         * Invoke remote method to get package information and install
8670         * location values. Override install location based on default
8671         * policy if needed and then create install arguments based
8672         * on the install location.
8673         */
8674        public void handleStartCopy() throws RemoteException {
8675            int ret = PackageManager.INSTALL_SUCCEEDED;
8676
8677            // If we're already staged, we've firmly committed to an install location
8678            if (origin.staged) {
8679                if (origin.file != null) {
8680                    installFlags |= PackageManager.INSTALL_INTERNAL;
8681                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8682                } else if (origin.cid != null) {
8683                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8684                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8685                } else {
8686                    throw new IllegalStateException("Invalid stage location");
8687                }
8688            }
8689
8690            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8691            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8692
8693            PackageInfoLite pkgLite = null;
8694
8695            if (onInt && onSd) {
8696                // Check if both bits are set.
8697                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8698                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8699            } else {
8700                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8701                        packageAbiOverride);
8702
8703                /*
8704                 * If we have too little free space, try to free cache
8705                 * before giving up.
8706                 */
8707                if (!origin.staged && pkgLite.recommendedInstallLocation
8708                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8709                    // TODO: focus freeing disk space on the target device
8710                    final StorageManager storage = StorageManager.from(mContext);
8711                    final long lowThreshold = storage.getStorageLowBytes(
8712                            Environment.getDataDirectory());
8713
8714                    final long sizeBytes = mContainerService.calculateInstalledSize(
8715                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8716
8717                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8718                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8719                                installFlags, packageAbiOverride);
8720                    }
8721
8722                    /*
8723                     * The cache free must have deleted the file we
8724                     * downloaded to install.
8725                     *
8726                     * TODO: fix the "freeCache" call to not delete
8727                     *       the file we care about.
8728                     */
8729                    if (pkgLite.recommendedInstallLocation
8730                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8731                        pkgLite.recommendedInstallLocation
8732                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8733                    }
8734                }
8735            }
8736
8737            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8738                int loc = pkgLite.recommendedInstallLocation;
8739                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8740                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8741                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8742                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8743                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8744                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8745                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8746                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8747                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8748                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8749                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8750                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8751                } else {
8752                    // Override with defaults if needed.
8753                    loc = installLocationPolicy(pkgLite);
8754                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8755                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8756                    } else if (!onSd && !onInt) {
8757                        // Override install location with flags
8758                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8759                            // Set the flag to install on external media.
8760                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8761                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8762                        } else {
8763                            // Make sure the flag for installing on external
8764                            // media is unset
8765                            installFlags |= PackageManager.INSTALL_INTERNAL;
8766                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8767                        }
8768                    }
8769                }
8770            }
8771
8772            final InstallArgs args = createInstallArgs(this);
8773            mArgs = args;
8774
8775            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8776                 /*
8777                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8778                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8779                 */
8780                int userIdentifier = getUser().getIdentifier();
8781                if (userIdentifier == UserHandle.USER_ALL
8782                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8783                    userIdentifier = UserHandle.USER_OWNER;
8784                }
8785
8786                /*
8787                 * Determine if we have any installed package verifiers. If we
8788                 * do, then we'll defer to them to verify the packages.
8789                 */
8790                final int requiredUid = mRequiredVerifierPackage == null ? -1
8791                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8792                if (!origin.existing && requiredUid != -1
8793                        && isVerificationEnabled(userIdentifier, installFlags)) {
8794                    final Intent verification = new Intent(
8795                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8796                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8797                            PACKAGE_MIME_TYPE);
8798                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8799
8800                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8801                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8802                            0 /* TODO: Which userId? */);
8803
8804                    if (DEBUG_VERIFY) {
8805                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8806                                + verification.toString() + " with " + pkgLite.verifiers.length
8807                                + " optional verifiers");
8808                    }
8809
8810                    final int verificationId = mPendingVerificationToken++;
8811
8812                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8813
8814                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8815                            installerPackageName);
8816
8817                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8818                            installFlags);
8819
8820                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8821                            pkgLite.packageName);
8822
8823                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8824                            pkgLite.versionCode);
8825
8826                    if (verificationParams != null) {
8827                        if (verificationParams.getVerificationURI() != null) {
8828                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8829                                 verificationParams.getVerificationURI());
8830                        }
8831                        if (verificationParams.getOriginatingURI() != null) {
8832                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8833                                  verificationParams.getOriginatingURI());
8834                        }
8835                        if (verificationParams.getReferrer() != null) {
8836                            verification.putExtra(Intent.EXTRA_REFERRER,
8837                                  verificationParams.getReferrer());
8838                        }
8839                        if (verificationParams.getOriginatingUid() >= 0) {
8840                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8841                                  verificationParams.getOriginatingUid());
8842                        }
8843                        if (verificationParams.getInstallerUid() >= 0) {
8844                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8845                                  verificationParams.getInstallerUid());
8846                        }
8847                    }
8848
8849                    final PackageVerificationState verificationState = new PackageVerificationState(
8850                            requiredUid, args);
8851
8852                    mPendingVerification.append(verificationId, verificationState);
8853
8854                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8855                            receivers, verificationState);
8856
8857                    /*
8858                     * If any sufficient verifiers were listed in the package
8859                     * manifest, attempt to ask them.
8860                     */
8861                    if (sufficientVerifiers != null) {
8862                        final int N = sufficientVerifiers.size();
8863                        if (N == 0) {
8864                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8865                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8866                        } else {
8867                            for (int i = 0; i < N; i++) {
8868                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8869
8870                                final Intent sufficientIntent = new Intent(verification);
8871                                sufficientIntent.setComponent(verifierComponent);
8872
8873                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8874                            }
8875                        }
8876                    }
8877
8878                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8879                            mRequiredVerifierPackage, receivers);
8880                    if (ret == PackageManager.INSTALL_SUCCEEDED
8881                            && mRequiredVerifierPackage != null) {
8882                        /*
8883                         * Send the intent to the required verification agent,
8884                         * but only start the verification timeout after the
8885                         * target BroadcastReceivers have run.
8886                         */
8887                        verification.setComponent(requiredVerifierComponent);
8888                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8889                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8890                                new BroadcastReceiver() {
8891                                    @Override
8892                                    public void onReceive(Context context, Intent intent) {
8893                                        final Message msg = mHandler
8894                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8895                                        msg.arg1 = verificationId;
8896                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8897                                    }
8898                                }, null, 0, null, null);
8899
8900                        /*
8901                         * We don't want the copy to proceed until verification
8902                         * succeeds, so null out this field.
8903                         */
8904                        mArgs = null;
8905                    }
8906                } else {
8907                    /*
8908                     * No package verification is enabled, so immediately start
8909                     * the remote call to initiate copy using temporary file.
8910                     */
8911                    ret = args.copyApk(mContainerService, true);
8912                }
8913            }
8914
8915            mRet = ret;
8916        }
8917
8918        @Override
8919        void handleReturnCode() {
8920            // If mArgs is null, then MCS couldn't be reached. When it
8921            // reconnects, it will try again to install. At that point, this
8922            // will succeed.
8923            if (mArgs != null) {
8924                processPendingInstall(mArgs, mRet);
8925            }
8926        }
8927
8928        @Override
8929        void handleServiceError() {
8930            mArgs = createInstallArgs(this);
8931            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8932        }
8933
8934        public boolean isForwardLocked() {
8935            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8936        }
8937    }
8938
8939    /**
8940     * Used during creation of InstallArgs
8941     *
8942     * @param installFlags package installation flags
8943     * @return true if should be installed on external storage
8944     */
8945    private static boolean installOnSd(int installFlags) {
8946        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8947            return false;
8948        }
8949        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8950            return true;
8951        }
8952        return false;
8953    }
8954
8955    /**
8956     * Used during creation of InstallArgs
8957     *
8958     * @param installFlags package installation flags
8959     * @return true if should be installed as forward locked
8960     */
8961    private static boolean installForwardLocked(int installFlags) {
8962        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8963    }
8964
8965    private InstallArgs createInstallArgs(InstallParams params) {
8966        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8967            return new AsecInstallArgs(params);
8968        } else {
8969            return new FileInstallArgs(params);
8970        }
8971    }
8972
8973    /**
8974     * Create args that describe an existing installed package. Typically used
8975     * when cleaning up old installs, or used as a move source.
8976     */
8977    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8978            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8979        final boolean isInAsec;
8980        if (installOnSd(installFlags)) {
8981            /* Apps on SD card are always in ASEC containers. */
8982            isInAsec = true;
8983        } else if (installForwardLocked(installFlags)
8984                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8985            /*
8986             * Forward-locked apps are only in ASEC containers if they're the
8987             * new style
8988             */
8989            isInAsec = true;
8990        } else {
8991            isInAsec = false;
8992        }
8993
8994        if (isInAsec) {
8995            return new AsecInstallArgs(codePath, instructionSets,
8996                    installOnSd(installFlags), installForwardLocked(installFlags));
8997        } else {
8998            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8999                    instructionSets);
9000        }
9001    }
9002
9003    static abstract class InstallArgs {
9004        /** @see InstallParams#origin */
9005        final OriginInfo origin;
9006
9007        final IPackageInstallObserver2 observer;
9008        // Always refers to PackageManager flags only
9009        final int installFlags;
9010        final String installerPackageName;
9011        final ManifestDigest manifestDigest;
9012        final UserHandle user;
9013        final String abiOverride;
9014
9015        // The list of instruction sets supported by this app. This is currently
9016        // only used during the rmdex() phase to clean up resources. We can get rid of this
9017        // if we move dex files under the common app path.
9018        /* nullable */ String[] instructionSets;
9019
9020        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9021                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9022                String[] instructionSets, String abiOverride) {
9023            this.origin = origin;
9024            this.installFlags = installFlags;
9025            this.observer = observer;
9026            this.installerPackageName = installerPackageName;
9027            this.manifestDigest = manifestDigest;
9028            this.user = user;
9029            this.instructionSets = instructionSets;
9030            this.abiOverride = abiOverride;
9031        }
9032
9033        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9034        abstract int doPreInstall(int status);
9035
9036        /**
9037         * Rename package into final resting place. All paths on the given
9038         * scanned package should be updated to reflect the rename.
9039         */
9040        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9041        abstract int doPostInstall(int status, int uid);
9042
9043        /** @see PackageSettingBase#codePathString */
9044        abstract String getCodePath();
9045        /** @see PackageSettingBase#resourcePathString */
9046        abstract String getResourcePath();
9047        abstract String getLegacyNativeLibraryPath();
9048
9049        // Need installer lock especially for dex file removal.
9050        abstract void cleanUpResourcesLI();
9051        abstract boolean doPostDeleteLI(boolean delete);
9052        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9053
9054        /**
9055         * Called before the source arguments are copied. This is used mostly
9056         * for MoveParams when it needs to read the source file to put it in the
9057         * destination.
9058         */
9059        int doPreCopy() {
9060            return PackageManager.INSTALL_SUCCEEDED;
9061        }
9062
9063        /**
9064         * Called after the source arguments are copied. This is used mostly for
9065         * MoveParams when it needs to read the source file to put it in the
9066         * destination.
9067         *
9068         * @return
9069         */
9070        int doPostCopy(int uid) {
9071            return PackageManager.INSTALL_SUCCEEDED;
9072        }
9073
9074        protected boolean isFwdLocked() {
9075            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9076        }
9077
9078        protected boolean isExternal() {
9079            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9080        }
9081
9082        UserHandle getUser() {
9083            return user;
9084        }
9085    }
9086
9087    /**
9088     * Logic to handle installation of non-ASEC applications, including copying
9089     * and renaming logic.
9090     */
9091    class FileInstallArgs extends InstallArgs {
9092        private File codeFile;
9093        private File resourceFile;
9094        private File legacyNativeLibraryPath;
9095
9096        // Example topology:
9097        // /data/app/com.example/base.apk
9098        // /data/app/com.example/split_foo.apk
9099        // /data/app/com.example/lib/arm/libfoo.so
9100        // /data/app/com.example/lib/arm64/libfoo.so
9101        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9102
9103        /** New install */
9104        FileInstallArgs(InstallParams params) {
9105            super(params.origin, params.observer, params.installFlags,
9106                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9107                    null /* instruction sets */, params.packageAbiOverride);
9108            if (isFwdLocked()) {
9109                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9110            }
9111        }
9112
9113        /** Existing install */
9114        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9115                String[] instructionSets) {
9116            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9117            this.codeFile = (codePath != null) ? new File(codePath) : null;
9118            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9119            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9120                    new File(legacyNativeLibraryPath) : null;
9121        }
9122
9123        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9124            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9125                    isFwdLocked(), abiOverride);
9126
9127            final StorageManager storage = StorageManager.from(mContext);
9128            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9129        }
9130
9131        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9132            if (origin.staged) {
9133                Slog.d(TAG, origin.file + " already staged; skipping copy");
9134                codeFile = origin.file;
9135                resourceFile = origin.file;
9136                return PackageManager.INSTALL_SUCCEEDED;
9137            }
9138
9139            try {
9140                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9141                codeFile = tempDir;
9142                resourceFile = tempDir;
9143            } catch (IOException e) {
9144                Slog.w(TAG, "Failed to create copy file: " + e);
9145                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9146            }
9147
9148            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9149                @Override
9150                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9151                    if (!FileUtils.isValidExtFilename(name)) {
9152                        throw new IllegalArgumentException("Invalid filename: " + name);
9153                    }
9154                    try {
9155                        final File file = new File(codeFile, name);
9156                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9157                                O_RDWR | O_CREAT, 0644);
9158                        Os.chmod(file.getAbsolutePath(), 0644);
9159                        return new ParcelFileDescriptor(fd);
9160                    } catch (ErrnoException e) {
9161                        throw new RemoteException("Failed to open: " + e.getMessage());
9162                    }
9163                }
9164            };
9165
9166            int ret = PackageManager.INSTALL_SUCCEEDED;
9167            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9168            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9169                Slog.e(TAG, "Failed to copy package");
9170                return ret;
9171            }
9172
9173            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9174            NativeLibraryHelper.Handle handle = null;
9175            try {
9176                handle = NativeLibraryHelper.Handle.create(codeFile);
9177                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9178                        abiOverride);
9179            } catch (IOException e) {
9180                Slog.e(TAG, "Copying native libraries failed", e);
9181                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9182            } finally {
9183                IoUtils.closeQuietly(handle);
9184            }
9185
9186            return ret;
9187        }
9188
9189        int doPreInstall(int status) {
9190            if (status != PackageManager.INSTALL_SUCCEEDED) {
9191                cleanUp();
9192            }
9193            return status;
9194        }
9195
9196        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9197            if (status != PackageManager.INSTALL_SUCCEEDED) {
9198                cleanUp();
9199                return false;
9200            } else {
9201                final File beforeCodeFile = codeFile;
9202                final File afterCodeFile = getNextCodePath(pkg.packageName);
9203
9204                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9205                try {
9206                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9207                } catch (ErrnoException e) {
9208                    Slog.d(TAG, "Failed to rename", e);
9209                    return false;
9210                }
9211
9212                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9213                    Slog.d(TAG, "Failed to restorecon");
9214                    return false;
9215                }
9216
9217                // Reflect the rename internally
9218                codeFile = afterCodeFile;
9219                resourceFile = afterCodeFile;
9220
9221                // Reflect the rename in scanned details
9222                pkg.codePath = afterCodeFile.getAbsolutePath();
9223                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9224                        pkg.baseCodePath);
9225                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9226                        pkg.splitCodePaths);
9227
9228                // Reflect the rename in app info
9229                pkg.applicationInfo.setCodePath(pkg.codePath);
9230                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9231                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9232                pkg.applicationInfo.setResourcePath(pkg.codePath);
9233                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9234                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9235
9236                return true;
9237            }
9238        }
9239
9240        int doPostInstall(int status, int uid) {
9241            if (status != PackageManager.INSTALL_SUCCEEDED) {
9242                cleanUp();
9243            }
9244            return status;
9245        }
9246
9247        @Override
9248        String getCodePath() {
9249            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9250        }
9251
9252        @Override
9253        String getResourcePath() {
9254            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9255        }
9256
9257        @Override
9258        String getLegacyNativeLibraryPath() {
9259            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9260        }
9261
9262        private boolean cleanUp() {
9263            if (codeFile == null || !codeFile.exists()) {
9264                return false;
9265            }
9266
9267            if (codeFile.isDirectory()) {
9268                FileUtils.deleteContents(codeFile);
9269            }
9270            codeFile.delete();
9271
9272            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9273                resourceFile.delete();
9274            }
9275
9276            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9277                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9278                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9279                }
9280                legacyNativeLibraryPath.delete();
9281            }
9282
9283            return true;
9284        }
9285
9286        void cleanUpResourcesLI() {
9287            // Try enumerating all code paths before deleting
9288            List<String> allCodePaths = Collections.EMPTY_LIST;
9289            if (codeFile != null && codeFile.exists()) {
9290                try {
9291                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9292                    allCodePaths = pkg.getAllCodePaths();
9293                } catch (PackageParserException e) {
9294                    // Ignored; we tried our best
9295                }
9296            }
9297
9298            cleanUp();
9299
9300            if (!allCodePaths.isEmpty()) {
9301                if (instructionSets == null) {
9302                    throw new IllegalStateException("instructionSet == null");
9303                }
9304                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9305                for (String codePath : allCodePaths) {
9306                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9307                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9308                        if (retCode < 0) {
9309                            Slog.w(TAG, "Couldn't remove dex file for package: "
9310                                    + " at location " + codePath + ", retcode=" + retCode);
9311                            // we don't consider this to be a failure of the core package deletion
9312                        }
9313                    }
9314                }
9315            }
9316        }
9317
9318        boolean doPostDeleteLI(boolean delete) {
9319            // XXX err, shouldn't we respect the delete flag?
9320            cleanUpResourcesLI();
9321            return true;
9322        }
9323    }
9324
9325    private boolean isAsecExternal(String cid) {
9326        final String asecPath = PackageHelper.getSdFilesystem(cid);
9327        return !asecPath.startsWith(mAsecInternalPath);
9328    }
9329
9330    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9331            PackageManagerException {
9332        if (copyRet < 0) {
9333            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9334                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9335                throw new PackageManagerException(copyRet, message);
9336            }
9337        }
9338    }
9339
9340    /**
9341     * Extract the MountService "container ID" from the full code path of an
9342     * .apk.
9343     */
9344    static String cidFromCodePath(String fullCodePath) {
9345        int eidx = fullCodePath.lastIndexOf("/");
9346        String subStr1 = fullCodePath.substring(0, eidx);
9347        int sidx = subStr1.lastIndexOf("/");
9348        return subStr1.substring(sidx+1, eidx);
9349    }
9350
9351    /**
9352     * Logic to handle installation of ASEC applications, including copying and
9353     * renaming logic.
9354     */
9355    class AsecInstallArgs extends InstallArgs {
9356        static final String RES_FILE_NAME = "pkg.apk";
9357        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9358
9359        String cid;
9360        String packagePath;
9361        String resourcePath;
9362        String legacyNativeLibraryDir;
9363
9364        /** New install */
9365        AsecInstallArgs(InstallParams params) {
9366            super(params.origin, params.observer, params.installFlags,
9367                    params.installerPackageName, params.getManifestDigest(),
9368                    params.getUser(), null /* instruction sets */,
9369                    params.packageAbiOverride);
9370        }
9371
9372        /** Existing install */
9373        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9374                        boolean isExternal, boolean isForwardLocked) {
9375            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9376                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9377                    instructionSets, null);
9378            // Hackily pretend we're still looking at a full code path
9379            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9380                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9381            }
9382
9383            // Extract cid from fullCodePath
9384            int eidx = fullCodePath.lastIndexOf("/");
9385            String subStr1 = fullCodePath.substring(0, eidx);
9386            int sidx = subStr1.lastIndexOf("/");
9387            cid = subStr1.substring(sidx+1, eidx);
9388            setMountPath(subStr1);
9389        }
9390
9391        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9392            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9393                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9394                    instructionSets, null);
9395            this.cid = cid;
9396            setMountPath(PackageHelper.getSdDir(cid));
9397        }
9398
9399        void createCopyFile() {
9400            cid = mInstallerService.allocateExternalStageCidLegacy();
9401        }
9402
9403        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9404            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9405                    abiOverride);
9406
9407            final File target;
9408            if (isExternal()) {
9409                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9410            } else {
9411                target = Environment.getDataDirectory();
9412            }
9413
9414            final StorageManager storage = StorageManager.from(mContext);
9415            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9416        }
9417
9418        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9419            if (origin.staged) {
9420                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9421                cid = origin.cid;
9422                setMountPath(PackageHelper.getSdDir(cid));
9423                return PackageManager.INSTALL_SUCCEEDED;
9424            }
9425
9426            if (temp) {
9427                createCopyFile();
9428            } else {
9429                /*
9430                 * Pre-emptively destroy the container since it's destroyed if
9431                 * copying fails due to it existing anyway.
9432                 */
9433                PackageHelper.destroySdDir(cid);
9434            }
9435
9436            final String newMountPath = imcs.copyPackageToContainer(
9437                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9438                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9439
9440            if (newMountPath != null) {
9441                setMountPath(newMountPath);
9442                return PackageManager.INSTALL_SUCCEEDED;
9443            } else {
9444                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9445            }
9446        }
9447
9448        @Override
9449        String getCodePath() {
9450            return packagePath;
9451        }
9452
9453        @Override
9454        String getResourcePath() {
9455            return resourcePath;
9456        }
9457
9458        @Override
9459        String getLegacyNativeLibraryPath() {
9460            return legacyNativeLibraryDir;
9461        }
9462
9463        int doPreInstall(int status) {
9464            if (status != PackageManager.INSTALL_SUCCEEDED) {
9465                // Destroy container
9466                PackageHelper.destroySdDir(cid);
9467            } else {
9468                boolean mounted = PackageHelper.isContainerMounted(cid);
9469                if (!mounted) {
9470                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9471                            Process.SYSTEM_UID);
9472                    if (newMountPath != null) {
9473                        setMountPath(newMountPath);
9474                    } else {
9475                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9476                    }
9477                }
9478            }
9479            return status;
9480        }
9481
9482        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9483            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9484            String newMountPath = null;
9485            if (PackageHelper.isContainerMounted(cid)) {
9486                // Unmount the container
9487                if (!PackageHelper.unMountSdDir(cid)) {
9488                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9489                    return false;
9490                }
9491            }
9492            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9493                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9494                        " which might be stale. Will try to clean up.");
9495                // Clean up the stale container and proceed to recreate.
9496                if (!PackageHelper.destroySdDir(newCacheId)) {
9497                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9498                    return false;
9499                }
9500                // Successfully cleaned up stale container. Try to rename again.
9501                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9502                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9503                            + " inspite of cleaning it up.");
9504                    return false;
9505                }
9506            }
9507            if (!PackageHelper.isContainerMounted(newCacheId)) {
9508                Slog.w(TAG, "Mounting container " + newCacheId);
9509                newMountPath = PackageHelper.mountSdDir(newCacheId,
9510                        getEncryptKey(), Process.SYSTEM_UID);
9511            } else {
9512                newMountPath = PackageHelper.getSdDir(newCacheId);
9513            }
9514            if (newMountPath == null) {
9515                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9516                return false;
9517            }
9518            Log.i(TAG, "Succesfully renamed " + cid +
9519                    " to " + newCacheId +
9520                    " at new path: " + newMountPath);
9521            cid = newCacheId;
9522
9523            final File beforeCodeFile = new File(packagePath);
9524            setMountPath(newMountPath);
9525            final File afterCodeFile = new File(packagePath);
9526
9527            // Reflect the rename in scanned details
9528            pkg.codePath = afterCodeFile.getAbsolutePath();
9529            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9530                    pkg.baseCodePath);
9531            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9532                    pkg.splitCodePaths);
9533
9534            // Reflect the rename in app info
9535            pkg.applicationInfo.setCodePath(pkg.codePath);
9536            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9537            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9538            pkg.applicationInfo.setResourcePath(pkg.codePath);
9539            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9540            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9541
9542            return true;
9543        }
9544
9545        private void setMountPath(String mountPath) {
9546            final File mountFile = new File(mountPath);
9547
9548            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9549            if (monolithicFile.exists()) {
9550                packagePath = monolithicFile.getAbsolutePath();
9551                if (isFwdLocked()) {
9552                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9553                } else {
9554                    resourcePath = packagePath;
9555                }
9556            } else {
9557                packagePath = mountFile.getAbsolutePath();
9558                resourcePath = packagePath;
9559            }
9560
9561            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9562        }
9563
9564        int doPostInstall(int status, int uid) {
9565            if (status != PackageManager.INSTALL_SUCCEEDED) {
9566                cleanUp();
9567            } else {
9568                final int groupOwner;
9569                final String protectedFile;
9570                if (isFwdLocked()) {
9571                    groupOwner = UserHandle.getSharedAppGid(uid);
9572                    protectedFile = RES_FILE_NAME;
9573                } else {
9574                    groupOwner = -1;
9575                    protectedFile = null;
9576                }
9577
9578                if (uid < Process.FIRST_APPLICATION_UID
9579                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9580                    Slog.e(TAG, "Failed to finalize " + cid);
9581                    PackageHelper.destroySdDir(cid);
9582                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9583                }
9584
9585                boolean mounted = PackageHelper.isContainerMounted(cid);
9586                if (!mounted) {
9587                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9588                }
9589            }
9590            return status;
9591        }
9592
9593        private void cleanUp() {
9594            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9595
9596            // Destroy secure container
9597            PackageHelper.destroySdDir(cid);
9598        }
9599
9600        private List<String> getAllCodePaths() {
9601            final File codeFile = new File(getCodePath());
9602            if (codeFile != null && codeFile.exists()) {
9603                try {
9604                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9605                    return pkg.getAllCodePaths();
9606                } catch (PackageParserException e) {
9607                    // Ignored; we tried our best
9608                }
9609            }
9610            return Collections.EMPTY_LIST;
9611        }
9612
9613        void cleanUpResourcesLI() {
9614            // Enumerate all code paths before deleting
9615            cleanUpResourcesLI(getAllCodePaths());
9616        }
9617
9618        private void cleanUpResourcesLI(List<String> allCodePaths) {
9619            cleanUp();
9620
9621            if (!allCodePaths.isEmpty()) {
9622                if (instructionSets == null) {
9623                    throw new IllegalStateException("instructionSet == null");
9624                }
9625                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9626                for (String codePath : allCodePaths) {
9627                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9628                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9629                        if (retCode < 0) {
9630                            Slog.w(TAG, "Couldn't remove dex file for package: "
9631                                    + " at location " + codePath + ", retcode=" + retCode);
9632                            // we don't consider this to be a failure of the core package deletion
9633                        }
9634                    }
9635                }
9636            }
9637        }
9638
9639        boolean matchContainer(String app) {
9640            if (cid.startsWith(app)) {
9641                return true;
9642            }
9643            return false;
9644        }
9645
9646        String getPackageName() {
9647            return getAsecPackageName(cid);
9648        }
9649
9650        boolean doPostDeleteLI(boolean delete) {
9651            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9652            final List<String> allCodePaths = getAllCodePaths();
9653            boolean mounted = PackageHelper.isContainerMounted(cid);
9654            if (mounted) {
9655                // Unmount first
9656                if (PackageHelper.unMountSdDir(cid)) {
9657                    mounted = false;
9658                }
9659            }
9660            if (!mounted && delete) {
9661                cleanUpResourcesLI(allCodePaths);
9662            }
9663            return !mounted;
9664        }
9665
9666        @Override
9667        int doPreCopy() {
9668            if (isFwdLocked()) {
9669                if (!PackageHelper.fixSdPermissions(cid,
9670                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9671                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9672                }
9673            }
9674
9675            return PackageManager.INSTALL_SUCCEEDED;
9676        }
9677
9678        @Override
9679        int doPostCopy(int uid) {
9680            if (isFwdLocked()) {
9681                if (uid < Process.FIRST_APPLICATION_UID
9682                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9683                                RES_FILE_NAME)) {
9684                    Slog.e(TAG, "Failed to finalize " + cid);
9685                    PackageHelper.destroySdDir(cid);
9686                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9687                }
9688            }
9689
9690            return PackageManager.INSTALL_SUCCEEDED;
9691        }
9692    }
9693
9694    static String getAsecPackageName(String packageCid) {
9695        int idx = packageCid.lastIndexOf("-");
9696        if (idx == -1) {
9697            return packageCid;
9698        }
9699        return packageCid.substring(0, idx);
9700    }
9701
9702    // Utility method used to create code paths based on package name and available index.
9703    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9704        String idxStr = "";
9705        int idx = 1;
9706        // Fall back to default value of idx=1 if prefix is not
9707        // part of oldCodePath
9708        if (oldCodePath != null) {
9709            String subStr = oldCodePath;
9710            // Drop the suffix right away
9711            if (suffix != null && subStr.endsWith(suffix)) {
9712                subStr = subStr.substring(0, subStr.length() - suffix.length());
9713            }
9714            // If oldCodePath already contains prefix find out the
9715            // ending index to either increment or decrement.
9716            int sidx = subStr.lastIndexOf(prefix);
9717            if (sidx != -1) {
9718                subStr = subStr.substring(sidx + prefix.length());
9719                if (subStr != null) {
9720                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9721                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9722                    }
9723                    try {
9724                        idx = Integer.parseInt(subStr);
9725                        if (idx <= 1) {
9726                            idx++;
9727                        } else {
9728                            idx--;
9729                        }
9730                    } catch(NumberFormatException e) {
9731                    }
9732                }
9733            }
9734        }
9735        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9736        return prefix + idxStr;
9737    }
9738
9739    private File getNextCodePath(String packageName) {
9740        int suffix = 1;
9741        File result;
9742        do {
9743            result = new File(mAppInstallDir, packageName + "-" + suffix);
9744            suffix++;
9745        } while (result.exists());
9746        return result;
9747    }
9748
9749    // Utility method used to ignore ADD/REMOVE events
9750    // by directory observer.
9751    private static boolean ignoreCodePath(String fullPathStr) {
9752        String apkName = deriveCodePathName(fullPathStr);
9753        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9754        if (idx != -1 && ((idx+1) < apkName.length())) {
9755            // Make sure the package ends with a numeral
9756            String version = apkName.substring(idx+1);
9757            try {
9758                Integer.parseInt(version);
9759                return true;
9760            } catch (NumberFormatException e) {}
9761        }
9762        return false;
9763    }
9764
9765    // Utility method that returns the relative package path with respect
9766    // to the installation directory. Like say for /data/data/com.test-1.apk
9767    // string com.test-1 is returned.
9768    static String deriveCodePathName(String codePath) {
9769        if (codePath == null) {
9770            return null;
9771        }
9772        final File codeFile = new File(codePath);
9773        final String name = codeFile.getName();
9774        if (codeFile.isDirectory()) {
9775            return name;
9776        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9777            final int lastDot = name.lastIndexOf('.');
9778            return name.substring(0, lastDot);
9779        } else {
9780            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9781            return null;
9782        }
9783    }
9784
9785    class PackageInstalledInfo {
9786        String name;
9787        int uid;
9788        // The set of users that originally had this package installed.
9789        int[] origUsers;
9790        // The set of users that now have this package installed.
9791        int[] newUsers;
9792        PackageParser.Package pkg;
9793        int returnCode;
9794        String returnMsg;
9795        PackageRemovedInfo removedInfo;
9796
9797        public void setError(int code, String msg) {
9798            returnCode = code;
9799            returnMsg = msg;
9800            Slog.w(TAG, msg);
9801        }
9802
9803        public void setError(String msg, PackageParserException e) {
9804            returnCode = e.error;
9805            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9806            Slog.w(TAG, msg, e);
9807        }
9808
9809        public void setError(String msg, PackageManagerException e) {
9810            returnCode = e.error;
9811            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9812            Slog.w(TAG, msg, e);
9813        }
9814
9815        // In some error cases we want to convey more info back to the observer
9816        String origPackage;
9817        String origPermission;
9818    }
9819
9820    /*
9821     * Install a non-existing package.
9822     */
9823    private void installNewPackageLI(PackageParser.Package pkg,
9824            int parseFlags, int scanFlags, UserHandle user,
9825            String installerPackageName, PackageInstalledInfo res) {
9826        // Remember this for later, in case we need to rollback this install
9827        String pkgName = pkg.packageName;
9828
9829        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9830        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9831        synchronized(mPackages) {
9832            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9833                // A package with the same name is already installed, though
9834                // it has been renamed to an older name.  The package we
9835                // are trying to install should be installed as an update to
9836                // the existing one, but that has not been requested, so bail.
9837                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9838                        + " without first uninstalling package running as "
9839                        + mSettings.mRenamedPackages.get(pkgName));
9840                return;
9841            }
9842            if (mPackages.containsKey(pkgName)) {
9843                // Don't allow installation over an existing package with the same name.
9844                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9845                        + " without first uninstalling.");
9846                return;
9847            }
9848        }
9849
9850        try {
9851            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9852                    System.currentTimeMillis(), user);
9853
9854            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9855            // delete the partially installed application. the data directory will have to be
9856            // restored if it was already existing
9857            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9858                // remove package from internal structures.  Note that we want deletePackageX to
9859                // delete the package data and cache directories that it created in
9860                // scanPackageLocked, unless those directories existed before we even tried to
9861                // install.
9862                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9863                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9864                                res.removedInfo, true);
9865            }
9866
9867        } catch (PackageManagerException e) {
9868            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9869        }
9870    }
9871
9872    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9873        // Upgrade keysets are being used.  Determine if new package has a superset of the
9874        // required keys.
9875        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9876        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9877        for (int i = 0; i < upgradeKeySets.length; i++) {
9878            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9879            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9880                return true;
9881            }
9882        }
9883        return false;
9884    }
9885
9886    private void replacePackageLI(PackageParser.Package pkg,
9887            int parseFlags, int scanFlags, UserHandle user,
9888            String installerPackageName, PackageInstalledInfo res) {
9889        PackageParser.Package oldPackage;
9890        String pkgName = pkg.packageName;
9891        int[] allUsers;
9892        boolean[] perUserInstalled;
9893
9894        // First find the old package info and check signatures
9895        synchronized(mPackages) {
9896            oldPackage = mPackages.get(pkgName);
9897            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9898            PackageSetting ps = mSettings.mPackages.get(pkgName);
9899            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9900                // default to original signature matching
9901                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9902                    != PackageManager.SIGNATURE_MATCH) {
9903                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9904                            "New package has a different signature: " + pkgName);
9905                    return;
9906                }
9907            } else {
9908                if(!checkUpgradeKeySetLP(ps, pkg)) {
9909                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9910                            "New package not signed by keys specified by upgrade-keysets: "
9911                            + pkgName);
9912                    return;
9913                }
9914            }
9915
9916            // In case of rollback, remember per-user/profile install state
9917            allUsers = sUserManager.getUserIds();
9918            perUserInstalled = new boolean[allUsers.length];
9919            for (int i = 0; i < allUsers.length; i++) {
9920                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9921            }
9922        }
9923
9924        boolean sysPkg = (isSystemApp(oldPackage));
9925        if (sysPkg) {
9926            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9927                    user, allUsers, perUserInstalled, installerPackageName, res);
9928        } else {
9929            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9930                    user, allUsers, perUserInstalled, installerPackageName, res);
9931        }
9932    }
9933
9934    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9935            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9936            int[] allUsers, boolean[] perUserInstalled,
9937            String installerPackageName, PackageInstalledInfo res) {
9938        String pkgName = deletedPackage.packageName;
9939        boolean deletedPkg = true;
9940        boolean updatedSettings = false;
9941
9942        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9943                + deletedPackage);
9944        long origUpdateTime;
9945        if (pkg.mExtras != null) {
9946            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9947        } else {
9948            origUpdateTime = 0;
9949        }
9950
9951        // First delete the existing package while retaining the data directory
9952        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9953                res.removedInfo, true)) {
9954            // If the existing package wasn't successfully deleted
9955            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9956            deletedPkg = false;
9957        } else {
9958            // Successfully deleted the old package; proceed with replace.
9959
9960            // If deleted package lived in a container, give users a chance to
9961            // relinquish resources before killing.
9962            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9963                if (DEBUG_INSTALL) {
9964                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9965                }
9966                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9967                final ArrayList<String> pkgList = new ArrayList<String>(1);
9968                pkgList.add(deletedPackage.applicationInfo.packageName);
9969                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9970            }
9971
9972            deleteCodeCacheDirsLI(pkgName);
9973            try {
9974                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9975                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9976                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9977                updatedSettings = true;
9978            } catch (PackageManagerException e) {
9979                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9980            }
9981        }
9982
9983        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9984            // remove package from internal structures.  Note that we want deletePackageX to
9985            // delete the package data and cache directories that it created in
9986            // scanPackageLocked, unless those directories existed before we even tried to
9987            // install.
9988            if(updatedSettings) {
9989                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9990                deletePackageLI(
9991                        pkgName, null, true, allUsers, perUserInstalled,
9992                        PackageManager.DELETE_KEEP_DATA,
9993                                res.removedInfo, true);
9994            }
9995            // Since we failed to install the new package we need to restore the old
9996            // package that we deleted.
9997            if (deletedPkg) {
9998                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9999                File restoreFile = new File(deletedPackage.codePath);
10000                // Parse old package
10001                boolean oldOnSd = isExternal(deletedPackage);
10002                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10003                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10004                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10005                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10006                try {
10007                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10008                } catch (PackageManagerException e) {
10009                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10010                            + e.getMessage());
10011                    return;
10012                }
10013                // Restore of old package succeeded. Update permissions.
10014                // writer
10015                synchronized (mPackages) {
10016                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10017                            UPDATE_PERMISSIONS_ALL);
10018                    // can downgrade to reader
10019                    mSettings.writeLPr();
10020                }
10021                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10022            }
10023        }
10024    }
10025
10026    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10027            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10028            int[] allUsers, boolean[] perUserInstalled,
10029            String installerPackageName, PackageInstalledInfo res) {
10030        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10031                + ", old=" + deletedPackage);
10032        boolean updatedSettings = false;
10033        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10034        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10035            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10036        }
10037        String packageName = deletedPackage.packageName;
10038        if (packageName == null) {
10039            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10040                    "Attempt to delete null packageName.");
10041            return;
10042        }
10043        PackageParser.Package oldPkg;
10044        PackageSetting oldPkgSetting;
10045        // reader
10046        synchronized (mPackages) {
10047            oldPkg = mPackages.get(packageName);
10048            oldPkgSetting = mSettings.mPackages.get(packageName);
10049            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10050                    (oldPkgSetting == null)) {
10051                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10052                        "Couldn't find package:" + packageName + " information");
10053                return;
10054            }
10055        }
10056
10057        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10058
10059        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10060        res.removedInfo.removedPackage = packageName;
10061        // Remove existing system package
10062        removePackageLI(oldPkgSetting, true);
10063        // writer
10064        synchronized (mPackages) {
10065            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10066                // We didn't need to disable the .apk as a current system package,
10067                // which means we are replacing another update that is already
10068                // installed.  We need to make sure to delete the older one's .apk.
10069                res.removedInfo.args = createInstallArgsForExisting(0,
10070                        deletedPackage.applicationInfo.getCodePath(),
10071                        deletedPackage.applicationInfo.getResourcePath(),
10072                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10073                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10074            } else {
10075                res.removedInfo.args = null;
10076            }
10077        }
10078
10079        // Successfully disabled the old package. Now proceed with re-installation
10080        deleteCodeCacheDirsLI(packageName);
10081
10082        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10083        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10084
10085        PackageParser.Package newPackage = null;
10086        try {
10087            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10088            if (newPackage.mExtras != null) {
10089                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10090                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10091                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10092
10093                // is the update attempting to change shared user? that isn't going to work...
10094                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10095                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10096                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10097                            + " to " + newPkgSetting.sharedUser);
10098                    updatedSettings = true;
10099                }
10100            }
10101
10102            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10103                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10104                updatedSettings = true;
10105            }
10106
10107        } catch (PackageManagerException e) {
10108            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10109        }
10110
10111        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10112            // Re installation failed. Restore old information
10113            // Remove new pkg information
10114            if (newPackage != null) {
10115                removeInstalledPackageLI(newPackage, true);
10116            }
10117            // Add back the old system package
10118            try {
10119                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10120            } catch (PackageManagerException e) {
10121                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10122            }
10123            // Restore the old system information in Settings
10124            synchronized(mPackages) {
10125                if (updatedSettings) {
10126                    mSettings.enableSystemPackageLPw(packageName);
10127                    mSettings.setInstallerPackageName(packageName,
10128                            oldPkgSetting.installerPackageName);
10129                }
10130                mSettings.writeLPr();
10131            }
10132        }
10133    }
10134
10135    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10136            int[] allUsers, boolean[] perUserInstalled,
10137            PackageInstalledInfo res) {
10138        String pkgName = newPackage.packageName;
10139        synchronized (mPackages) {
10140            //write settings. the installStatus will be incomplete at this stage.
10141            //note that the new package setting would have already been
10142            //added to mPackages. It hasn't been persisted yet.
10143            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10144            mSettings.writeLPr();
10145        }
10146
10147        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10148
10149        synchronized (mPackages) {
10150            updatePermissionsLPw(newPackage.packageName, newPackage,
10151                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10152                            ? UPDATE_PERMISSIONS_ALL : 0));
10153            // For system-bundled packages, we assume that installing an upgraded version
10154            // of the package implies that the user actually wants to run that new code,
10155            // so we enable the package.
10156            if (isSystemApp(newPackage)) {
10157                // NB: implicit assumption that system package upgrades apply to all users
10158                if (DEBUG_INSTALL) {
10159                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10160                }
10161                PackageSetting ps = mSettings.mPackages.get(pkgName);
10162                if (ps != null) {
10163                    if (res.origUsers != null) {
10164                        for (int userHandle : res.origUsers) {
10165                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10166                                    userHandle, installerPackageName);
10167                        }
10168                    }
10169                    // Also convey the prior install/uninstall state
10170                    if (allUsers != null && perUserInstalled != null) {
10171                        for (int i = 0; i < allUsers.length; i++) {
10172                            if (DEBUG_INSTALL) {
10173                                Slog.d(TAG, "    user " + allUsers[i]
10174                                        + " => " + perUserInstalled[i]);
10175                            }
10176                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10177                        }
10178                        // these install state changes will be persisted in the
10179                        // upcoming call to mSettings.writeLPr().
10180                    }
10181                }
10182            }
10183            res.name = pkgName;
10184            res.uid = newPackage.applicationInfo.uid;
10185            res.pkg = newPackage;
10186            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10187            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10188            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10189            //to update install status
10190            mSettings.writeLPr();
10191        }
10192    }
10193
10194    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10195        final int installFlags = args.installFlags;
10196        String installerPackageName = args.installerPackageName;
10197        File tmpPackageFile = new File(args.getCodePath());
10198        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10199        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10200        boolean replace = false;
10201        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10202        // Result object to be returned
10203        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10204
10205        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10206        // Retrieve PackageSettings and parse package
10207        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10208                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10209                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10210        PackageParser pp = new PackageParser();
10211        pp.setSeparateProcesses(mSeparateProcesses);
10212        pp.setDisplayMetrics(mMetrics);
10213
10214        final PackageParser.Package pkg;
10215        try {
10216            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10217        } catch (PackageParserException e) {
10218            res.setError("Failed parse during installPackageLI", e);
10219            return;
10220        }
10221
10222        // Mark that we have an install time CPU ABI override.
10223        pkg.cpuAbiOverride = args.abiOverride;
10224
10225        String pkgName = res.name = pkg.packageName;
10226        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10227            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10228                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10229                return;
10230            }
10231        }
10232
10233        try {
10234            pp.collectCertificates(pkg, parseFlags);
10235            pp.collectManifestDigest(pkg);
10236        } catch (PackageParserException e) {
10237            res.setError("Failed collect during installPackageLI", e);
10238            return;
10239        }
10240
10241        /* If the installer passed in a manifest digest, compare it now. */
10242        if (args.manifestDigest != null) {
10243            if (DEBUG_INSTALL) {
10244                final String parsedManifest = pkg.manifestDigest == null ? "null"
10245                        : pkg.manifestDigest.toString();
10246                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10247                        + parsedManifest);
10248            }
10249
10250            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10251                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10252                return;
10253            }
10254        } else if (DEBUG_INSTALL) {
10255            final String parsedManifest = pkg.manifestDigest == null
10256                    ? "null" : pkg.manifestDigest.toString();
10257            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10258        }
10259
10260        // Get rid of all references to package scan path via parser.
10261        pp = null;
10262        String oldCodePath = null;
10263        boolean systemApp = false;
10264        synchronized (mPackages) {
10265            // Check whether the newly-scanned package wants to define an already-defined perm
10266            int N = pkg.permissions.size();
10267            for (int i = N-1; i >= 0; i--) {
10268                PackageParser.Permission perm = pkg.permissions.get(i);
10269                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10270                if (bp != null) {
10271                    // If the defining package is signed with our cert, it's okay.  This
10272                    // also includes the "updating the same package" case, of course.
10273                    // "updating same package" could also involve key-rotation.
10274                    final boolean sigsOk;
10275                    if (!bp.sourcePackage.equals(pkg.packageName)
10276                            || !(bp.packageSetting instanceof PackageSetting)
10277                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10278                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10279                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10280                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10281                    } else {
10282                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10283                    }
10284                    if (!sigsOk) {
10285                        // If the owning package is the system itself, we log but allow
10286                        // install to proceed; we fail the install on all other permission
10287                        // redefinitions.
10288                        if (!bp.sourcePackage.equals("android")) {
10289                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10290                                    + pkg.packageName + " attempting to redeclare permission "
10291                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10292                            res.origPermission = perm.info.name;
10293                            res.origPackage = bp.sourcePackage;
10294                            return;
10295                        } else {
10296                            Slog.w(TAG, "Package " + pkg.packageName
10297                                    + " attempting to redeclare system permission "
10298                                    + perm.info.name + "; ignoring new declaration");
10299                            pkg.permissions.remove(i);
10300                        }
10301                    }
10302                }
10303            }
10304
10305            // Check if installing already existing package
10306            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10307                String oldName = mSettings.mRenamedPackages.get(pkgName);
10308                if (pkg.mOriginalPackages != null
10309                        && pkg.mOriginalPackages.contains(oldName)
10310                        && mPackages.containsKey(oldName)) {
10311                    // This package is derived from an original package,
10312                    // and this device has been updating from that original
10313                    // name.  We must continue using the original name, so
10314                    // rename the new package here.
10315                    pkg.setPackageName(oldName);
10316                    pkgName = pkg.packageName;
10317                    replace = true;
10318                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10319                            + oldName + " pkgName=" + pkgName);
10320                } else if (mPackages.containsKey(pkgName)) {
10321                    // This package, under its official name, already exists
10322                    // on the device; we should replace it.
10323                    replace = true;
10324                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10325                }
10326            }
10327            PackageSetting ps = mSettings.mPackages.get(pkgName);
10328            if (ps != null) {
10329                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10330                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10331                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10332                    systemApp = (ps.pkg.applicationInfo.flags &
10333                            ApplicationInfo.FLAG_SYSTEM) != 0;
10334                }
10335                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10336            }
10337        }
10338
10339        if (systemApp && onSd) {
10340            // Disable updates to system apps on sdcard
10341            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10342                    "Cannot install updates to system apps on sdcard");
10343            return;
10344        }
10345
10346        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10347            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10348            return;
10349        }
10350
10351        if (replace) {
10352            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10353                    installerPackageName, res);
10354        } else {
10355            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10356                    args.user, installerPackageName, res);
10357        }
10358        synchronized (mPackages) {
10359            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10360            if (ps != null) {
10361                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10362            }
10363        }
10364    }
10365
10366    private static boolean isForwardLocked(PackageParser.Package pkg) {
10367        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10368    }
10369
10370    private static boolean isForwardLocked(ApplicationInfo info) {
10371        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10372    }
10373
10374    private boolean isForwardLocked(PackageSetting ps) {
10375        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10376    }
10377
10378    private static boolean isMultiArch(PackageSetting ps) {
10379        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10380    }
10381
10382    private static boolean isMultiArch(ApplicationInfo info) {
10383        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10384    }
10385
10386    private static boolean isExternal(PackageParser.Package pkg) {
10387        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10388    }
10389
10390    private static boolean isExternal(PackageSetting ps) {
10391        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10392    }
10393
10394    private static boolean isExternal(ApplicationInfo info) {
10395        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10396    }
10397
10398    private static boolean isSystemApp(PackageParser.Package pkg) {
10399        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10400    }
10401
10402    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10403        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10404    }
10405
10406    private static boolean isSystemApp(ApplicationInfo info) {
10407        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10408    }
10409
10410    private static boolean isSystemApp(PackageSetting ps) {
10411        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10412    }
10413
10414    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10415        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10416    }
10417
10418    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10419        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10420    }
10421
10422    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10423        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10424    }
10425
10426    private int packageFlagsToInstallFlags(PackageSetting ps) {
10427        int installFlags = 0;
10428        if (isExternal(ps)) {
10429            installFlags |= PackageManager.INSTALL_EXTERNAL;
10430        }
10431        if (isForwardLocked(ps)) {
10432            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10433        }
10434        return installFlags;
10435    }
10436
10437    private void deleteTempPackageFiles() {
10438        final FilenameFilter filter = new FilenameFilter() {
10439            public boolean accept(File dir, String name) {
10440                return name.startsWith("vmdl") && name.endsWith(".tmp");
10441            }
10442        };
10443        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10444            file.delete();
10445        }
10446    }
10447
10448    @Override
10449    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10450            int flags) {
10451        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10452                flags);
10453    }
10454
10455    @Override
10456    public void deletePackage(final String packageName,
10457            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10458        mContext.enforceCallingOrSelfPermission(
10459                android.Manifest.permission.DELETE_PACKAGES, null);
10460        final int uid = Binder.getCallingUid();
10461        if (UserHandle.getUserId(uid) != userId) {
10462            mContext.enforceCallingPermission(
10463                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10464                    "deletePackage for user " + userId);
10465        }
10466        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10467            try {
10468                observer.onPackageDeleted(packageName,
10469                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10470            } catch (RemoteException re) {
10471            }
10472            return;
10473        }
10474
10475        boolean uninstallBlocked = false;
10476        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10477            int[] users = sUserManager.getUserIds();
10478            for (int i = 0; i < users.length; ++i) {
10479                if (getBlockUninstallForUser(packageName, users[i])) {
10480                    uninstallBlocked = true;
10481                    break;
10482                }
10483            }
10484        } else {
10485            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10486        }
10487        if (uninstallBlocked) {
10488            try {
10489                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10490                        null);
10491            } catch (RemoteException re) {
10492            }
10493            return;
10494        }
10495
10496        if (DEBUG_REMOVE) {
10497            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10498        }
10499        // Queue up an async operation since the package deletion may take a little while.
10500        mHandler.post(new Runnable() {
10501            public void run() {
10502                mHandler.removeCallbacks(this);
10503                final int returnCode = deletePackageX(packageName, userId, flags);
10504                if (observer != null) {
10505                    try {
10506                        observer.onPackageDeleted(packageName, returnCode, null);
10507                    } catch (RemoteException e) {
10508                        Log.i(TAG, "Observer no longer exists.");
10509                    } //end catch
10510                } //end if
10511            } //end run
10512        });
10513    }
10514
10515    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10516        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10517                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10518        try {
10519            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10520                    || dpm.isDeviceOwner(packageName))) {
10521                return true;
10522            }
10523        } catch (RemoteException e) {
10524        }
10525        return false;
10526    }
10527
10528    /**
10529     *  This method is an internal method that could be get invoked either
10530     *  to delete an installed package or to clean up a failed installation.
10531     *  After deleting an installed package, a broadcast is sent to notify any
10532     *  listeners that the package has been installed. For cleaning up a failed
10533     *  installation, the broadcast is not necessary since the package's
10534     *  installation wouldn't have sent the initial broadcast either
10535     *  The key steps in deleting a package are
10536     *  deleting the package information in internal structures like mPackages,
10537     *  deleting the packages base directories through installd
10538     *  updating mSettings to reflect current status
10539     *  persisting settings for later use
10540     *  sending a broadcast if necessary
10541     */
10542    private int deletePackageX(String packageName, int userId, int flags) {
10543        final PackageRemovedInfo info = new PackageRemovedInfo();
10544        final boolean res;
10545
10546        if (isPackageDeviceAdmin(packageName, userId)) {
10547            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10548            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10549        }
10550
10551        boolean removedForAllUsers = false;
10552        boolean systemUpdate = false;
10553
10554        // for the uninstall-updates case and restricted profiles, remember the per-
10555        // userhandle installed state
10556        int[] allUsers;
10557        boolean[] perUserInstalled;
10558        synchronized (mPackages) {
10559            PackageSetting ps = mSettings.mPackages.get(packageName);
10560            allUsers = sUserManager.getUserIds();
10561            perUserInstalled = new boolean[allUsers.length];
10562            for (int i = 0; i < allUsers.length; i++) {
10563                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10564            }
10565        }
10566
10567        synchronized (mInstallLock) {
10568            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10569            res = deletePackageLI(packageName,
10570                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10571                            ? UserHandle.ALL : new UserHandle(userId),
10572                    true, allUsers, perUserInstalled,
10573                    flags | REMOVE_CHATTY, info, true);
10574            systemUpdate = info.isRemovedPackageSystemUpdate;
10575            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10576                removedForAllUsers = true;
10577            }
10578            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10579                    + " removedForAllUsers=" + removedForAllUsers);
10580        }
10581
10582        if (res) {
10583            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10584
10585            // If the removed package was a system update, the old system package
10586            // was re-enabled; we need to broadcast this information
10587            if (systemUpdate) {
10588                Bundle extras = new Bundle(1);
10589                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10590                        ? info.removedAppId : info.uid);
10591                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10592
10593                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10594                        extras, null, null, null);
10595                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10596                        extras, null, null, null);
10597                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10598                        null, packageName, null, null);
10599            }
10600        }
10601        // Force a gc here.
10602        Runtime.getRuntime().gc();
10603        // Delete the resources here after sending the broadcast to let
10604        // other processes clean up before deleting resources.
10605        if (info.args != null) {
10606            synchronized (mInstallLock) {
10607                info.args.doPostDeleteLI(true);
10608            }
10609        }
10610
10611        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10612    }
10613
10614    static class PackageRemovedInfo {
10615        String removedPackage;
10616        int uid = -1;
10617        int removedAppId = -1;
10618        int[] removedUsers = null;
10619        boolean isRemovedPackageSystemUpdate = false;
10620        // Clean up resources deleted packages.
10621        InstallArgs args = null;
10622
10623        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10624            Bundle extras = new Bundle(1);
10625            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10626            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10627            if (replacing) {
10628                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10629            }
10630            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10631            if (removedPackage != null) {
10632                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10633                        extras, null, null, removedUsers);
10634                if (fullRemove && !replacing) {
10635                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10636                            extras, null, null, removedUsers);
10637                }
10638            }
10639            if (removedAppId >= 0) {
10640                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10641                        removedUsers);
10642            }
10643        }
10644    }
10645
10646    /*
10647     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10648     * flag is not set, the data directory is removed as well.
10649     * make sure this flag is set for partially installed apps. If not its meaningless to
10650     * delete a partially installed application.
10651     */
10652    private void removePackageDataLI(PackageSetting ps,
10653            int[] allUserHandles, boolean[] perUserInstalled,
10654            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10655        String packageName = ps.name;
10656        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10657        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10658        // Retrieve object to delete permissions for shared user later on
10659        final PackageSetting deletedPs;
10660        // reader
10661        synchronized (mPackages) {
10662            deletedPs = mSettings.mPackages.get(packageName);
10663            if (outInfo != null) {
10664                outInfo.removedPackage = packageName;
10665                outInfo.removedUsers = deletedPs != null
10666                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10667                        : null;
10668            }
10669        }
10670        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10671            removeDataDirsLI(packageName);
10672            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10673        }
10674        // writer
10675        synchronized (mPackages) {
10676            if (deletedPs != null) {
10677                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10678                    if (outInfo != null) {
10679                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10680                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10681                    }
10682                    if (deletedPs != null) {
10683                        updatePermissionsLPw(deletedPs.name, null, 0);
10684                        if (deletedPs.sharedUser != null) {
10685                            // remove permissions associated with package
10686                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10687                        }
10688                    }
10689                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10690                }
10691                // make sure to preserve per-user disabled state if this removal was just
10692                // a downgrade of a system app to the factory package
10693                if (allUserHandles != null && perUserInstalled != null) {
10694                    if (DEBUG_REMOVE) {
10695                        Slog.d(TAG, "Propagating install state across downgrade");
10696                    }
10697                    for (int i = 0; i < allUserHandles.length; i++) {
10698                        if (DEBUG_REMOVE) {
10699                            Slog.d(TAG, "    user " + allUserHandles[i]
10700                                    + " => " + perUserInstalled[i]);
10701                        }
10702                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10703                    }
10704                }
10705            }
10706            // can downgrade to reader
10707            if (writeSettings) {
10708                // Save settings now
10709                mSettings.writeLPr();
10710            }
10711        }
10712        if (outInfo != null) {
10713            // A user ID was deleted here. Go through all users and remove it
10714            // from KeyStore.
10715            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10716        }
10717    }
10718
10719    static boolean locationIsPrivileged(File path) {
10720        try {
10721            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10722                    .getCanonicalPath();
10723            return path.getCanonicalPath().startsWith(privilegedAppDir);
10724        } catch (IOException e) {
10725            Slog.e(TAG, "Unable to access code path " + path);
10726        }
10727        return false;
10728    }
10729
10730    /*
10731     * Tries to delete system package.
10732     */
10733    private boolean deleteSystemPackageLI(PackageSetting newPs,
10734            int[] allUserHandles, boolean[] perUserInstalled,
10735            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10736        final boolean applyUserRestrictions
10737                = (allUserHandles != null) && (perUserInstalled != null);
10738        PackageSetting disabledPs = null;
10739        // Confirm if the system package has been updated
10740        // An updated system app can be deleted. This will also have to restore
10741        // the system pkg from system partition
10742        // reader
10743        synchronized (mPackages) {
10744            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10745        }
10746        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10747                + " disabledPs=" + disabledPs);
10748        if (disabledPs == null) {
10749            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10750            return false;
10751        } else if (DEBUG_REMOVE) {
10752            Slog.d(TAG, "Deleting system pkg from data partition");
10753        }
10754        if (DEBUG_REMOVE) {
10755            if (applyUserRestrictions) {
10756                Slog.d(TAG, "Remembering install states:");
10757                for (int i = 0; i < allUserHandles.length; i++) {
10758                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10759                }
10760            }
10761        }
10762        // Delete the updated package
10763        outInfo.isRemovedPackageSystemUpdate = true;
10764        if (disabledPs.versionCode < newPs.versionCode) {
10765            // Delete data for downgrades
10766            flags &= ~PackageManager.DELETE_KEEP_DATA;
10767        } else {
10768            // Preserve data by setting flag
10769            flags |= PackageManager.DELETE_KEEP_DATA;
10770        }
10771        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10772                allUserHandles, perUserInstalled, outInfo, writeSettings);
10773        if (!ret) {
10774            return false;
10775        }
10776        // writer
10777        synchronized (mPackages) {
10778            // Reinstate the old system package
10779            mSettings.enableSystemPackageLPw(newPs.name);
10780            // Remove any native libraries from the upgraded package.
10781            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10782        }
10783        // Install the system package
10784        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10785        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10786        if (locationIsPrivileged(disabledPs.codePath)) {
10787            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10788        }
10789
10790        final PackageParser.Package newPkg;
10791        try {
10792            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10793        } catch (PackageManagerException e) {
10794            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10795            return false;
10796        }
10797
10798        // writer
10799        synchronized (mPackages) {
10800            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10801            updatePermissionsLPw(newPkg.packageName, newPkg,
10802                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10803            if (applyUserRestrictions) {
10804                if (DEBUG_REMOVE) {
10805                    Slog.d(TAG, "Propagating install state across reinstall");
10806                }
10807                for (int i = 0; i < allUserHandles.length; i++) {
10808                    if (DEBUG_REMOVE) {
10809                        Slog.d(TAG, "    user " + allUserHandles[i]
10810                                + " => " + perUserInstalled[i]);
10811                    }
10812                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10813                }
10814                // Regardless of writeSettings we need to ensure that this restriction
10815                // state propagation is persisted
10816                mSettings.writeAllUsersPackageRestrictionsLPr();
10817            }
10818            // can downgrade to reader here
10819            if (writeSettings) {
10820                mSettings.writeLPr();
10821            }
10822        }
10823        return true;
10824    }
10825
10826    private boolean deleteInstalledPackageLI(PackageSetting ps,
10827            boolean deleteCodeAndResources, int flags,
10828            int[] allUserHandles, boolean[] perUserInstalled,
10829            PackageRemovedInfo outInfo, boolean writeSettings) {
10830        if (outInfo != null) {
10831            outInfo.uid = ps.appId;
10832        }
10833
10834        // Delete package data from internal structures and also remove data if flag is set
10835        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10836
10837        // Delete application code and resources
10838        if (deleteCodeAndResources && (outInfo != null)) {
10839            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10840                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10841                    getAppDexInstructionSets(ps));
10842            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10843        }
10844        return true;
10845    }
10846
10847    @Override
10848    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10849            int userId) {
10850        mContext.enforceCallingOrSelfPermission(
10851                android.Manifest.permission.DELETE_PACKAGES, null);
10852        synchronized (mPackages) {
10853            PackageSetting ps = mSettings.mPackages.get(packageName);
10854            if (ps == null) {
10855                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10856                return false;
10857            }
10858            if (!ps.getInstalled(userId)) {
10859                // Can't block uninstall for an app that is not installed or enabled.
10860                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10861                return false;
10862            }
10863            ps.setBlockUninstall(blockUninstall, userId);
10864            mSettings.writePackageRestrictionsLPr(userId);
10865        }
10866        return true;
10867    }
10868
10869    @Override
10870    public boolean getBlockUninstallForUser(String packageName, int userId) {
10871        synchronized (mPackages) {
10872            PackageSetting ps = mSettings.mPackages.get(packageName);
10873            if (ps == null) {
10874                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10875                return false;
10876            }
10877            return ps.getBlockUninstall(userId);
10878        }
10879    }
10880
10881    /*
10882     * This method handles package deletion in general
10883     */
10884    private boolean deletePackageLI(String packageName, UserHandle user,
10885            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10886            int flags, PackageRemovedInfo outInfo,
10887            boolean writeSettings) {
10888        if (packageName == null) {
10889            Slog.w(TAG, "Attempt to delete null packageName.");
10890            return false;
10891        }
10892        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10893        PackageSetting ps;
10894        boolean dataOnly = false;
10895        int removeUser = -1;
10896        int appId = -1;
10897        synchronized (mPackages) {
10898            ps = mSettings.mPackages.get(packageName);
10899            if (ps == null) {
10900                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10901                return false;
10902            }
10903            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10904                    && user.getIdentifier() != UserHandle.USER_ALL) {
10905                // The caller is asking that the package only be deleted for a single
10906                // user.  To do this, we just mark its uninstalled state and delete
10907                // its data.  If this is a system app, we only allow this to happen if
10908                // they have set the special DELETE_SYSTEM_APP which requests different
10909                // semantics than normal for uninstalling system apps.
10910                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10911                ps.setUserState(user.getIdentifier(),
10912                        COMPONENT_ENABLED_STATE_DEFAULT,
10913                        false, //installed
10914                        true,  //stopped
10915                        true,  //notLaunched
10916                        false, //hidden
10917                        null, null, null,
10918                        false // blockUninstall
10919                        );
10920                if (!isSystemApp(ps)) {
10921                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10922                        // Other user still have this package installed, so all
10923                        // we need to do is clear this user's data and save that
10924                        // it is uninstalled.
10925                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10926                        removeUser = user.getIdentifier();
10927                        appId = ps.appId;
10928                        mSettings.writePackageRestrictionsLPr(removeUser);
10929                    } else {
10930                        // We need to set it back to 'installed' so the uninstall
10931                        // broadcasts will be sent correctly.
10932                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10933                        ps.setInstalled(true, user.getIdentifier());
10934                    }
10935                } else {
10936                    // This is a system app, so we assume that the
10937                    // other users still have this package installed, so all
10938                    // we need to do is clear this user's data and save that
10939                    // it is uninstalled.
10940                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10941                    removeUser = user.getIdentifier();
10942                    appId = ps.appId;
10943                    mSettings.writePackageRestrictionsLPr(removeUser);
10944                }
10945            }
10946        }
10947
10948        if (removeUser >= 0) {
10949            // From above, we determined that we are deleting this only
10950            // for a single user.  Continue the work here.
10951            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10952            if (outInfo != null) {
10953                outInfo.removedPackage = packageName;
10954                outInfo.removedAppId = appId;
10955                outInfo.removedUsers = new int[] {removeUser};
10956            }
10957            mInstaller.clearUserData(packageName, removeUser);
10958            removeKeystoreDataIfNeeded(removeUser, appId);
10959            schedulePackageCleaning(packageName, removeUser, false);
10960            return true;
10961        }
10962
10963        if (dataOnly) {
10964            // Delete application data first
10965            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10966            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10967            return true;
10968        }
10969
10970        boolean ret = false;
10971        if (isSystemApp(ps)) {
10972            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10973            // When an updated system application is deleted we delete the existing resources as well and
10974            // fall back to existing code in system partition
10975            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10976                    flags, outInfo, writeSettings);
10977        } else {
10978            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10979            // Kill application pre-emptively especially for apps on sd.
10980            killApplication(packageName, ps.appId, "uninstall pkg");
10981            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10982                    allUserHandles, perUserInstalled,
10983                    outInfo, writeSettings);
10984        }
10985
10986        return ret;
10987    }
10988
10989    private final class ClearStorageConnection implements ServiceConnection {
10990        IMediaContainerService mContainerService;
10991
10992        @Override
10993        public void onServiceConnected(ComponentName name, IBinder service) {
10994            synchronized (this) {
10995                mContainerService = IMediaContainerService.Stub.asInterface(service);
10996                notifyAll();
10997            }
10998        }
10999
11000        @Override
11001        public void onServiceDisconnected(ComponentName name) {
11002        }
11003    }
11004
11005    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11006        final boolean mounted;
11007        if (Environment.isExternalStorageEmulated()) {
11008            mounted = true;
11009        } else {
11010            final String status = Environment.getExternalStorageState();
11011
11012            mounted = status.equals(Environment.MEDIA_MOUNTED)
11013                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11014        }
11015
11016        if (!mounted) {
11017            return;
11018        }
11019
11020        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11021        int[] users;
11022        if (userId == UserHandle.USER_ALL) {
11023            users = sUserManager.getUserIds();
11024        } else {
11025            users = new int[] { userId };
11026        }
11027        final ClearStorageConnection conn = new ClearStorageConnection();
11028        if (mContext.bindServiceAsUser(
11029                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11030            try {
11031                for (int curUser : users) {
11032                    long timeout = SystemClock.uptimeMillis() + 5000;
11033                    synchronized (conn) {
11034                        long now = SystemClock.uptimeMillis();
11035                        while (conn.mContainerService == null && now < timeout) {
11036                            try {
11037                                conn.wait(timeout - now);
11038                            } catch (InterruptedException e) {
11039                            }
11040                        }
11041                    }
11042                    if (conn.mContainerService == null) {
11043                        return;
11044                    }
11045
11046                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11047                    clearDirectory(conn.mContainerService,
11048                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11049                    if (allData) {
11050                        clearDirectory(conn.mContainerService,
11051                                userEnv.buildExternalStorageAppDataDirs(packageName));
11052                        clearDirectory(conn.mContainerService,
11053                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11054                    }
11055                }
11056            } finally {
11057                mContext.unbindService(conn);
11058            }
11059        }
11060    }
11061
11062    @Override
11063    public void clearApplicationUserData(final String packageName,
11064            final IPackageDataObserver observer, final int userId) {
11065        mContext.enforceCallingOrSelfPermission(
11066                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11067        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11068        // Queue up an async operation since the package deletion may take a little while.
11069        mHandler.post(new Runnable() {
11070            public void run() {
11071                mHandler.removeCallbacks(this);
11072                final boolean succeeded;
11073                synchronized (mInstallLock) {
11074                    succeeded = clearApplicationUserDataLI(packageName, userId);
11075                }
11076                clearExternalStorageDataSync(packageName, userId, true);
11077                if (succeeded) {
11078                    // invoke DeviceStorageMonitor's update method to clear any notifications
11079                    DeviceStorageMonitorInternal
11080                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11081                    if (dsm != null) {
11082                        dsm.checkMemory();
11083                    }
11084                }
11085                if(observer != null) {
11086                    try {
11087                        observer.onRemoveCompleted(packageName, succeeded);
11088                    } catch (RemoteException e) {
11089                        Log.i(TAG, "Observer no longer exists.");
11090                    }
11091                } //end if observer
11092            } //end run
11093        });
11094    }
11095
11096    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11097        if (packageName == null) {
11098            Slog.w(TAG, "Attempt to delete null packageName.");
11099            return false;
11100        }
11101        PackageParser.Package pkg;
11102        boolean dataOnly = false;
11103        final int appId;
11104        synchronized (mPackages) {
11105            pkg = mPackages.get(packageName);
11106            if (pkg == null) {
11107                dataOnly = true;
11108                PackageSetting ps = mSettings.mPackages.get(packageName);
11109                if ((ps == null) || (ps.pkg == null)) {
11110                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11111                    return false;
11112                }
11113                pkg = ps.pkg;
11114            }
11115            if (!dataOnly) {
11116                // need to check this only for fully installed applications
11117                if (pkg == null) {
11118                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11119                    return false;
11120                }
11121                final ApplicationInfo applicationInfo = pkg.applicationInfo;
11122                if (applicationInfo == null) {
11123                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11124                    return false;
11125                }
11126            }
11127            if (pkg != null && pkg.applicationInfo != null) {
11128                appId = pkg.applicationInfo.uid;
11129            } else {
11130                appId = -1;
11131            }
11132        }
11133        int retCode = mInstaller.clearUserData(packageName, userId);
11134        if (retCode < 0) {
11135            Slog.w(TAG, "Couldn't remove cache files for package: "
11136                    + packageName);
11137            return false;
11138        }
11139        removeKeystoreDataIfNeeded(userId, appId);
11140
11141        // Create a native library symlink only if we have native libraries
11142        // and if the native libraries are 32 bit libraries. We do not provide
11143        // this symlink for 64 bit libraries.
11144        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11145                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11146            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11147            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11148                Slog.w(TAG, "Failed linking native library dir");
11149                return false;
11150            }
11151        }
11152
11153        return true;
11154    }
11155
11156    /**
11157     * Remove entries from the keystore daemon. Will only remove it if the
11158     * {@code appId} is valid.
11159     */
11160    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11161        if (appId < 0) {
11162            return;
11163        }
11164
11165        final KeyStore keyStore = KeyStore.getInstance();
11166        if (keyStore != null) {
11167            if (userId == UserHandle.USER_ALL) {
11168                for (final int individual : sUserManager.getUserIds()) {
11169                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11170                }
11171            } else {
11172                keyStore.clearUid(UserHandle.getUid(userId, appId));
11173            }
11174        } else {
11175            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11176        }
11177    }
11178
11179    @Override
11180    public void deleteApplicationCacheFiles(final String packageName,
11181            final IPackageDataObserver observer) {
11182        mContext.enforceCallingOrSelfPermission(
11183                android.Manifest.permission.DELETE_CACHE_FILES, null);
11184        // Queue up an async operation since the package deletion may take a little while.
11185        final int userId = UserHandle.getCallingUserId();
11186        mHandler.post(new Runnable() {
11187            public void run() {
11188                mHandler.removeCallbacks(this);
11189                final boolean succeded;
11190                synchronized (mInstallLock) {
11191                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11192                }
11193                clearExternalStorageDataSync(packageName, userId, false);
11194                if(observer != null) {
11195                    try {
11196                        observer.onRemoveCompleted(packageName, succeded);
11197                    } catch (RemoteException e) {
11198                        Log.i(TAG, "Observer no longer exists.");
11199                    }
11200                } //end if observer
11201            } //end run
11202        });
11203    }
11204
11205    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11206        if (packageName == null) {
11207            Slog.w(TAG, "Attempt to delete null packageName.");
11208            return false;
11209        }
11210        PackageParser.Package p;
11211        synchronized (mPackages) {
11212            p = mPackages.get(packageName);
11213        }
11214        if (p == null) {
11215            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11216            return false;
11217        }
11218        final ApplicationInfo applicationInfo = p.applicationInfo;
11219        if (applicationInfo == null) {
11220            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11221            return false;
11222        }
11223        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11224        if (retCode < 0) {
11225            Slog.w(TAG, "Couldn't remove cache files for package: "
11226                       + packageName + " u" + userId);
11227            return false;
11228        }
11229        return true;
11230    }
11231
11232    @Override
11233    public void getPackageSizeInfo(final String packageName, int userHandle,
11234            final IPackageStatsObserver observer) {
11235        mContext.enforceCallingOrSelfPermission(
11236                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11237        if (packageName == null) {
11238            throw new IllegalArgumentException("Attempt to get size of null packageName");
11239        }
11240
11241        PackageStats stats = new PackageStats(packageName, userHandle);
11242
11243        /*
11244         * Queue up an async operation since the package measurement may take a
11245         * little while.
11246         */
11247        Message msg = mHandler.obtainMessage(INIT_COPY);
11248        msg.obj = new MeasureParams(stats, observer);
11249        mHandler.sendMessage(msg);
11250    }
11251
11252    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11253            PackageStats pStats) {
11254        if (packageName == null) {
11255            Slog.w(TAG, "Attempt to get size of null packageName.");
11256            return false;
11257        }
11258        PackageParser.Package p;
11259        boolean dataOnly = false;
11260        String libDirRoot = null;
11261        String asecPath = null;
11262        PackageSetting ps = null;
11263        synchronized (mPackages) {
11264            p = mPackages.get(packageName);
11265            ps = mSettings.mPackages.get(packageName);
11266            if(p == null) {
11267                dataOnly = true;
11268                if((ps == null) || (ps.pkg == null)) {
11269                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11270                    return false;
11271                }
11272                p = ps.pkg;
11273            }
11274            if (ps != null) {
11275                libDirRoot = ps.legacyNativeLibraryPathString;
11276            }
11277            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11278                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11279                if (secureContainerId != null) {
11280                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11281                }
11282            }
11283        }
11284        String publicSrcDir = null;
11285        if(!dataOnly) {
11286            final ApplicationInfo applicationInfo = p.applicationInfo;
11287            if (applicationInfo == null) {
11288                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11289                return false;
11290            }
11291            if (isForwardLocked(p)) {
11292                publicSrcDir = applicationInfo.getBaseResourcePath();
11293            }
11294        }
11295        // TODO: extend to measure size of split APKs
11296        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11297        // not just the first level.
11298        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11299        // just the primary.
11300        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11301        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11302                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11303        if (res < 0) {
11304            return false;
11305        }
11306
11307        // Fix-up for forward-locked applications in ASEC containers.
11308        if (!isExternal(p)) {
11309            pStats.codeSize += pStats.externalCodeSize;
11310            pStats.externalCodeSize = 0L;
11311        }
11312
11313        return true;
11314    }
11315
11316
11317    @Override
11318    public void addPackageToPreferred(String packageName) {
11319        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11320    }
11321
11322    @Override
11323    public void removePackageFromPreferred(String packageName) {
11324        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11325    }
11326
11327    @Override
11328    public List<PackageInfo> getPreferredPackages(int flags) {
11329        return new ArrayList<PackageInfo>();
11330    }
11331
11332    private int getUidTargetSdkVersionLockedLPr(int uid) {
11333        Object obj = mSettings.getUserIdLPr(uid);
11334        if (obj instanceof SharedUserSetting) {
11335            final SharedUserSetting sus = (SharedUserSetting) obj;
11336            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11337            final Iterator<PackageSetting> it = sus.packages.iterator();
11338            while (it.hasNext()) {
11339                final PackageSetting ps = it.next();
11340                if (ps.pkg != null) {
11341                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11342                    if (v < vers) vers = v;
11343                }
11344            }
11345            return vers;
11346        } else if (obj instanceof PackageSetting) {
11347            final PackageSetting ps = (PackageSetting) obj;
11348            if (ps.pkg != null) {
11349                return ps.pkg.applicationInfo.targetSdkVersion;
11350            }
11351        }
11352        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11353    }
11354
11355    @Override
11356    public void addPreferredActivity(IntentFilter filter, int match,
11357            ComponentName[] set, ComponentName activity, int userId) {
11358        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11359                "Adding preferred");
11360    }
11361
11362    private void addPreferredActivityInternal(IntentFilter filter, int match,
11363            ComponentName[] set, ComponentName activity, boolean always, int userId,
11364            String opname) {
11365        // writer
11366        int callingUid = Binder.getCallingUid();
11367        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11368        if (filter.countActions() == 0) {
11369            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11370            return;
11371        }
11372        synchronized (mPackages) {
11373            if (mContext.checkCallingOrSelfPermission(
11374                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11375                    != PackageManager.PERMISSION_GRANTED) {
11376                if (getUidTargetSdkVersionLockedLPr(callingUid)
11377                        < Build.VERSION_CODES.FROYO) {
11378                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11379                            + callingUid);
11380                    return;
11381                }
11382                mContext.enforceCallingOrSelfPermission(
11383                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11384            }
11385
11386            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11387            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11388                    + userId + ":");
11389            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11390            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11391            mSettings.writePackageRestrictionsLPr(userId);
11392        }
11393    }
11394
11395    @Override
11396    public void replacePreferredActivity(IntentFilter filter, int match,
11397            ComponentName[] set, ComponentName activity, int userId) {
11398        if (filter.countActions() != 1) {
11399            throw new IllegalArgumentException(
11400                    "replacePreferredActivity expects filter to have only 1 action.");
11401        }
11402        if (filter.countDataAuthorities() != 0
11403                || filter.countDataPaths() != 0
11404                || filter.countDataSchemes() > 1
11405                || filter.countDataTypes() != 0) {
11406            throw new IllegalArgumentException(
11407                    "replacePreferredActivity expects filter to have no data authorities, " +
11408                    "paths, or types; and at most one scheme.");
11409        }
11410
11411        final int callingUid = Binder.getCallingUid();
11412        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11413        synchronized (mPackages) {
11414            if (mContext.checkCallingOrSelfPermission(
11415                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11416                    != PackageManager.PERMISSION_GRANTED) {
11417                if (getUidTargetSdkVersionLockedLPr(callingUid)
11418                        < Build.VERSION_CODES.FROYO) {
11419                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11420                            + Binder.getCallingUid());
11421                    return;
11422                }
11423                mContext.enforceCallingOrSelfPermission(
11424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11425            }
11426
11427            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11428            if (pir != null) {
11429                // Get all of the existing entries that exactly match this filter.
11430                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11431                if (existing != null && existing.size() == 1) {
11432                    PreferredActivity cur = existing.get(0);
11433                    if (DEBUG_PREFERRED) {
11434                        Slog.i(TAG, "Checking replace of preferred:");
11435                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11436                        if (!cur.mPref.mAlways) {
11437                            Slog.i(TAG, "  -- CUR; not mAlways!");
11438                        } else {
11439                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11440                            Slog.i(TAG, "  -- CUR: mSet="
11441                                    + Arrays.toString(cur.mPref.mSetComponents));
11442                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11443                            Slog.i(TAG, "  -- NEW: mMatch="
11444                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11445                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11446                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11447                        }
11448                    }
11449                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11450                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11451                            && cur.mPref.sameSet(set)) {
11452                        if (DEBUG_PREFERRED) {
11453                            Slog.i(TAG, "Replacing with same preferred activity "
11454                                    + cur.mPref.mShortComponent + " for user "
11455                                    + userId + ":");
11456                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11457                        } else {
11458                            Slog.i(TAG, "Replacing with same preferred activity "
11459                                    + cur.mPref.mShortComponent + " for user "
11460                                    + userId);
11461                        }
11462                        return;
11463                    }
11464                }
11465
11466                if (existing != null) {
11467                    if (DEBUG_PREFERRED) {
11468                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11469                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11470                    }
11471                    for (int i = 0; i < existing.size(); i++) {
11472                        PreferredActivity pa = existing.get(i);
11473                        if (DEBUG_PREFERRED) {
11474                            Slog.i(TAG, "Removing existing preferred activity "
11475                                    + pa.mPref.mComponent + ":");
11476                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11477                        }
11478                        pir.removeFilter(pa);
11479                    }
11480                }
11481            }
11482            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11483                    "Replacing preferred");
11484        }
11485    }
11486
11487    @Override
11488    public void clearPackagePreferredActivities(String packageName) {
11489        final int uid = Binder.getCallingUid();
11490        // writer
11491        synchronized (mPackages) {
11492            PackageParser.Package pkg = mPackages.get(packageName);
11493            if (pkg == null || pkg.applicationInfo.uid != uid) {
11494                if (mContext.checkCallingOrSelfPermission(
11495                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11496                        != PackageManager.PERMISSION_GRANTED) {
11497                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11498                            < Build.VERSION_CODES.FROYO) {
11499                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11500                                + Binder.getCallingUid());
11501                        return;
11502                    }
11503                    mContext.enforceCallingOrSelfPermission(
11504                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11505                }
11506            }
11507
11508            int user = UserHandle.getCallingUserId();
11509            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11510                mSettings.writePackageRestrictionsLPr(user);
11511                scheduleWriteSettingsLocked();
11512            }
11513        }
11514    }
11515
11516    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11517    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11518        ArrayList<PreferredActivity> removed = null;
11519        boolean changed = false;
11520        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11521            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11522            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11523            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11524                continue;
11525            }
11526            Iterator<PreferredActivity> it = pir.filterIterator();
11527            while (it.hasNext()) {
11528                PreferredActivity pa = it.next();
11529                // Mark entry for removal only if it matches the package name
11530                // and the entry is of type "always".
11531                if (packageName == null ||
11532                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11533                                && pa.mPref.mAlways)) {
11534                    if (removed == null) {
11535                        removed = new ArrayList<PreferredActivity>();
11536                    }
11537                    removed.add(pa);
11538                }
11539            }
11540            if (removed != null) {
11541                for (int j=0; j<removed.size(); j++) {
11542                    PreferredActivity pa = removed.get(j);
11543                    pir.removeFilter(pa);
11544                }
11545                changed = true;
11546            }
11547        }
11548        return changed;
11549    }
11550
11551    @Override
11552    public void resetPreferredActivities(int userId) {
11553        /* TODO: Actually use userId. Why is it being passed in? */
11554        mContext.enforceCallingOrSelfPermission(
11555                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11556        // writer
11557        synchronized (mPackages) {
11558            int user = UserHandle.getCallingUserId();
11559            clearPackagePreferredActivitiesLPw(null, user);
11560            mSettings.readDefaultPreferredAppsLPw(this, user);
11561            mSettings.writePackageRestrictionsLPr(user);
11562            scheduleWriteSettingsLocked();
11563        }
11564    }
11565
11566    @Override
11567    public int getPreferredActivities(List<IntentFilter> outFilters,
11568            List<ComponentName> outActivities, String packageName) {
11569
11570        int num = 0;
11571        final int userId = UserHandle.getCallingUserId();
11572        // reader
11573        synchronized (mPackages) {
11574            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11575            if (pir != null) {
11576                final Iterator<PreferredActivity> it = pir.filterIterator();
11577                while (it.hasNext()) {
11578                    final PreferredActivity pa = it.next();
11579                    if (packageName == null
11580                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11581                                    && pa.mPref.mAlways)) {
11582                        if (outFilters != null) {
11583                            outFilters.add(new IntentFilter(pa));
11584                        }
11585                        if (outActivities != null) {
11586                            outActivities.add(pa.mPref.mComponent);
11587                        }
11588                    }
11589                }
11590            }
11591        }
11592
11593        return num;
11594    }
11595
11596    @Override
11597    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11598            int userId) {
11599        int callingUid = Binder.getCallingUid();
11600        if (callingUid != Process.SYSTEM_UID) {
11601            throw new SecurityException(
11602                    "addPersistentPreferredActivity can only be run by the system");
11603        }
11604        if (filter.countActions() == 0) {
11605            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11606            return;
11607        }
11608        synchronized (mPackages) {
11609            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11610                    " :");
11611            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11612            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11613                    new PersistentPreferredActivity(filter, activity));
11614            mSettings.writePackageRestrictionsLPr(userId);
11615        }
11616    }
11617
11618    @Override
11619    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11620        int callingUid = Binder.getCallingUid();
11621        if (callingUid != Process.SYSTEM_UID) {
11622            throw new SecurityException(
11623                    "clearPackagePersistentPreferredActivities can only be run by the system");
11624        }
11625        ArrayList<PersistentPreferredActivity> removed = null;
11626        boolean changed = false;
11627        synchronized (mPackages) {
11628            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11629                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11630                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11631                        .valueAt(i);
11632                if (userId != thisUserId) {
11633                    continue;
11634                }
11635                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11636                while (it.hasNext()) {
11637                    PersistentPreferredActivity ppa = it.next();
11638                    // Mark entry for removal only if it matches the package name.
11639                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11640                        if (removed == null) {
11641                            removed = new ArrayList<PersistentPreferredActivity>();
11642                        }
11643                        removed.add(ppa);
11644                    }
11645                }
11646                if (removed != null) {
11647                    for (int j=0; j<removed.size(); j++) {
11648                        PersistentPreferredActivity ppa = removed.get(j);
11649                        ppir.removeFilter(ppa);
11650                    }
11651                    changed = true;
11652                }
11653            }
11654
11655            if (changed) {
11656                mSettings.writePackageRestrictionsLPr(userId);
11657            }
11658        }
11659    }
11660
11661    @Override
11662    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11663            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11664        mContext.enforceCallingOrSelfPermission(
11665                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11666        int callingUid = Binder.getCallingUid();
11667        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11668        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11669        if (intentFilter.countActions() == 0) {
11670            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11671            return;
11672        }
11673        synchronized (mPackages) {
11674            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11675                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11676            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11677            mSettings.writePackageRestrictionsLPr(sourceUserId);
11678        }
11679    }
11680
11681    @Override
11682    public void addCrossProfileIntentsForPackage(String packageName,
11683            int sourceUserId, int targetUserId) {
11684        mContext.enforceCallingOrSelfPermission(
11685                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11686        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11687        mSettings.writePackageRestrictionsLPr(sourceUserId);
11688    }
11689
11690    @Override
11691    public void removeCrossProfileIntentsForPackage(String packageName,
11692            int sourceUserId, int targetUserId) {
11693        mContext.enforceCallingOrSelfPermission(
11694                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11695        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11696        mSettings.writePackageRestrictionsLPr(sourceUserId);
11697    }
11698
11699    @Override
11700    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11701            int ownerUserId) {
11702        mContext.enforceCallingOrSelfPermission(
11703                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11704        int callingUid = Binder.getCallingUid();
11705        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11706        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11707        int callingUserId = UserHandle.getUserId(callingUid);
11708        synchronized (mPackages) {
11709            CrossProfileIntentResolver resolver =
11710                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11711            HashSet<CrossProfileIntentFilter> set =
11712                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11713            for (CrossProfileIntentFilter filter : set) {
11714                if (filter.getOwnerPackage().equals(ownerPackage)
11715                        && filter.getOwnerUserId() == callingUserId) {
11716                    resolver.removeFilter(filter);
11717                }
11718            }
11719            mSettings.writePackageRestrictionsLPr(sourceUserId);
11720        }
11721    }
11722
11723    // Enforcing that callingUid is owning pkg on userId
11724    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11725        // The system owns everything.
11726        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11727            return;
11728        }
11729        int callingUserId = UserHandle.getUserId(callingUid);
11730        if (callingUserId != userId) {
11731            throw new SecurityException("calling uid " + callingUid
11732                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11733                    + callingUserId);
11734        }
11735        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11736        if (pi == null) {
11737            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11738                    + callingUserId);
11739        }
11740        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11741            throw new SecurityException("Calling uid " + callingUid
11742                    + " does not own package " + pkg);
11743        }
11744    }
11745
11746    @Override
11747    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11748        Intent intent = new Intent(Intent.ACTION_MAIN);
11749        intent.addCategory(Intent.CATEGORY_HOME);
11750
11751        final int callingUserId = UserHandle.getCallingUserId();
11752        List<ResolveInfo> list = queryIntentActivities(intent, null,
11753                PackageManager.GET_META_DATA, callingUserId);
11754        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11755                true, false, false, callingUserId);
11756
11757        allHomeCandidates.clear();
11758        if (list != null) {
11759            for (ResolveInfo ri : list) {
11760                allHomeCandidates.add(ri);
11761            }
11762        }
11763        return (preferred == null || preferred.activityInfo == null)
11764                ? null
11765                : new ComponentName(preferred.activityInfo.packageName,
11766                        preferred.activityInfo.name);
11767    }
11768
11769    @Override
11770    public void setApplicationEnabledSetting(String appPackageName,
11771            int newState, int flags, int userId, String callingPackage) {
11772        if (!sUserManager.exists(userId)) return;
11773        if (callingPackage == null) {
11774            callingPackage = Integer.toString(Binder.getCallingUid());
11775        }
11776        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11777    }
11778
11779    @Override
11780    public void setComponentEnabledSetting(ComponentName componentName,
11781            int newState, int flags, int userId) {
11782        if (!sUserManager.exists(userId)) return;
11783        setEnabledSetting(componentName.getPackageName(),
11784                componentName.getClassName(), newState, flags, userId, null);
11785    }
11786
11787    private void setEnabledSetting(final String packageName, String className, int newState,
11788            final int flags, int userId, String callingPackage) {
11789        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11790              || newState == COMPONENT_ENABLED_STATE_ENABLED
11791              || newState == COMPONENT_ENABLED_STATE_DISABLED
11792              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11793              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11794            throw new IllegalArgumentException("Invalid new component state: "
11795                    + newState);
11796        }
11797        PackageSetting pkgSetting;
11798        final int uid = Binder.getCallingUid();
11799        final int permission = mContext.checkCallingOrSelfPermission(
11800                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11801        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11802        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11803        boolean sendNow = false;
11804        boolean isApp = (className == null);
11805        String componentName = isApp ? packageName : className;
11806        int packageUid = -1;
11807        ArrayList<String> components;
11808
11809        // writer
11810        synchronized (mPackages) {
11811            pkgSetting = mSettings.mPackages.get(packageName);
11812            if (pkgSetting == null) {
11813                if (className == null) {
11814                    throw new IllegalArgumentException(
11815                            "Unknown package: " + packageName);
11816                }
11817                throw new IllegalArgumentException(
11818                        "Unknown component: " + packageName
11819                        + "/" + className);
11820            }
11821            // Allow root and verify that userId is not being specified by a different user
11822            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11823                throw new SecurityException(
11824                        "Permission Denial: attempt to change component state from pid="
11825                        + Binder.getCallingPid()
11826                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11827            }
11828            if (className == null) {
11829                // We're dealing with an application/package level state change
11830                if (pkgSetting.getEnabled(userId) == newState) {
11831                    // Nothing to do
11832                    return;
11833                }
11834                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11835                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11836                    // Don't care about who enables an app.
11837                    callingPackage = null;
11838                }
11839                pkgSetting.setEnabled(newState, userId, callingPackage);
11840                // pkgSetting.pkg.mSetEnabled = newState;
11841            } else {
11842                // We're dealing with a component level state change
11843                // First, verify that this is a valid class name.
11844                PackageParser.Package pkg = pkgSetting.pkg;
11845                if (pkg == null || !pkg.hasComponentClassName(className)) {
11846                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11847                        throw new IllegalArgumentException("Component class " + className
11848                                + " does not exist in " + packageName);
11849                    } else {
11850                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11851                                + className + " does not exist in " + packageName);
11852                    }
11853                }
11854                switch (newState) {
11855                case COMPONENT_ENABLED_STATE_ENABLED:
11856                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11857                        return;
11858                    }
11859                    break;
11860                case COMPONENT_ENABLED_STATE_DISABLED:
11861                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11862                        return;
11863                    }
11864                    break;
11865                case COMPONENT_ENABLED_STATE_DEFAULT:
11866                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11867                        return;
11868                    }
11869                    break;
11870                default:
11871                    Slog.e(TAG, "Invalid new component state: " + newState);
11872                    return;
11873                }
11874            }
11875            mSettings.writePackageRestrictionsLPr(userId);
11876            components = mPendingBroadcasts.get(userId, packageName);
11877            final boolean newPackage = components == null;
11878            if (newPackage) {
11879                components = new ArrayList<String>();
11880            }
11881            if (!components.contains(componentName)) {
11882                components.add(componentName);
11883            }
11884            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11885                sendNow = true;
11886                // Purge entry from pending broadcast list if another one exists already
11887                // since we are sending one right away.
11888                mPendingBroadcasts.remove(userId, packageName);
11889            } else {
11890                if (newPackage) {
11891                    mPendingBroadcasts.put(userId, packageName, components);
11892                }
11893                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11894                    // Schedule a message
11895                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11896                }
11897            }
11898        }
11899
11900        long callingId = Binder.clearCallingIdentity();
11901        try {
11902            if (sendNow) {
11903                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11904                sendPackageChangedBroadcast(packageName,
11905                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11906            }
11907        } finally {
11908            Binder.restoreCallingIdentity(callingId);
11909        }
11910    }
11911
11912    private void sendPackageChangedBroadcast(String packageName,
11913            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11914        if (DEBUG_INSTALL)
11915            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11916                    + componentNames);
11917        Bundle extras = new Bundle(4);
11918        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11919        String nameList[] = new String[componentNames.size()];
11920        componentNames.toArray(nameList);
11921        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11922        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11923        extras.putInt(Intent.EXTRA_UID, packageUid);
11924        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11925                new int[] {UserHandle.getUserId(packageUid)});
11926    }
11927
11928    @Override
11929    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11930        if (!sUserManager.exists(userId)) return;
11931        final int uid = Binder.getCallingUid();
11932        final int permission = mContext.checkCallingOrSelfPermission(
11933                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11934        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11935        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11936        // writer
11937        synchronized (mPackages) {
11938            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11939                    uid, userId)) {
11940                scheduleWritePackageRestrictionsLocked(userId);
11941            }
11942        }
11943    }
11944
11945    @Override
11946    public String getInstallerPackageName(String packageName) {
11947        // reader
11948        synchronized (mPackages) {
11949            return mSettings.getInstallerPackageNameLPr(packageName);
11950        }
11951    }
11952
11953    @Override
11954    public int getApplicationEnabledSetting(String packageName, int userId) {
11955        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11956        int uid = Binder.getCallingUid();
11957        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11958        // reader
11959        synchronized (mPackages) {
11960            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11961        }
11962    }
11963
11964    @Override
11965    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11966        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11967        int uid = Binder.getCallingUid();
11968        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11969        // reader
11970        synchronized (mPackages) {
11971            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11972        }
11973    }
11974
11975    @Override
11976    public void enterSafeMode() {
11977        enforceSystemOrRoot("Only the system can request entering safe mode");
11978
11979        if (!mSystemReady) {
11980            mSafeMode = true;
11981        }
11982    }
11983
11984    @Override
11985    public void systemReady() {
11986        mSystemReady = true;
11987
11988        // Read the compatibilty setting when the system is ready.
11989        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11990                mContext.getContentResolver(),
11991                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11992        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11993        if (DEBUG_SETTINGS) {
11994            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11995        }
11996
11997        synchronized (mPackages) {
11998            // Verify that all of the preferred activity components actually
11999            // exist.  It is possible for applications to be updated and at
12000            // that point remove a previously declared activity component that
12001            // had been set as a preferred activity.  We try to clean this up
12002            // the next time we encounter that preferred activity, but it is
12003            // possible for the user flow to never be able to return to that
12004            // situation so here we do a sanity check to make sure we haven't
12005            // left any junk around.
12006            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12007            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12008                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12009                removed.clear();
12010                for (PreferredActivity pa : pir.filterSet()) {
12011                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12012                        removed.add(pa);
12013                    }
12014                }
12015                if (removed.size() > 0) {
12016                    for (int r=0; r<removed.size(); r++) {
12017                        PreferredActivity pa = removed.get(r);
12018                        Slog.w(TAG, "Removing dangling preferred activity: "
12019                                + pa.mPref.mComponent);
12020                        pir.removeFilter(pa);
12021                    }
12022                    mSettings.writePackageRestrictionsLPr(
12023                            mSettings.mPreferredActivities.keyAt(i));
12024                }
12025            }
12026        }
12027        sUserManager.systemReady();
12028
12029        // Kick off any messages waiting for system ready
12030        if (mPostSystemReadyMessages != null) {
12031            for (Message msg : mPostSystemReadyMessages) {
12032                msg.sendToTarget();
12033            }
12034            mPostSystemReadyMessages = null;
12035        }
12036    }
12037
12038    @Override
12039    public boolean isSafeMode() {
12040        return mSafeMode;
12041    }
12042
12043    @Override
12044    public boolean hasSystemUidErrors() {
12045        return mHasSystemUidErrors;
12046    }
12047
12048    static String arrayToString(int[] array) {
12049        StringBuffer buf = new StringBuffer(128);
12050        buf.append('[');
12051        if (array != null) {
12052            for (int i=0; i<array.length; i++) {
12053                if (i > 0) buf.append(", ");
12054                buf.append(array[i]);
12055            }
12056        }
12057        buf.append(']');
12058        return buf.toString();
12059    }
12060
12061    static class DumpState {
12062        public static final int DUMP_LIBS = 1 << 0;
12063        public static final int DUMP_FEATURES = 1 << 1;
12064        public static final int DUMP_RESOLVERS = 1 << 2;
12065        public static final int DUMP_PERMISSIONS = 1 << 3;
12066        public static final int DUMP_PACKAGES = 1 << 4;
12067        public static final int DUMP_SHARED_USERS = 1 << 5;
12068        public static final int DUMP_MESSAGES = 1 << 6;
12069        public static final int DUMP_PROVIDERS = 1 << 7;
12070        public static final int DUMP_VERIFIERS = 1 << 8;
12071        public static final int DUMP_PREFERRED = 1 << 9;
12072        public static final int DUMP_PREFERRED_XML = 1 << 10;
12073        public static final int DUMP_KEYSETS = 1 << 11;
12074        public static final int DUMP_VERSION = 1 << 12;
12075        public static final int DUMP_INSTALLS = 1 << 13;
12076
12077        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12078
12079        private int mTypes;
12080
12081        private int mOptions;
12082
12083        private boolean mTitlePrinted;
12084
12085        private SharedUserSetting mSharedUser;
12086
12087        public boolean isDumping(int type) {
12088            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12089                return true;
12090            }
12091
12092            return (mTypes & type) != 0;
12093        }
12094
12095        public void setDump(int type) {
12096            mTypes |= type;
12097        }
12098
12099        public boolean isOptionEnabled(int option) {
12100            return (mOptions & option) != 0;
12101        }
12102
12103        public void setOptionEnabled(int option) {
12104            mOptions |= option;
12105        }
12106
12107        public boolean onTitlePrinted() {
12108            final boolean printed = mTitlePrinted;
12109            mTitlePrinted = true;
12110            return printed;
12111        }
12112
12113        public boolean getTitlePrinted() {
12114            return mTitlePrinted;
12115        }
12116
12117        public void setTitlePrinted(boolean enabled) {
12118            mTitlePrinted = enabled;
12119        }
12120
12121        public SharedUserSetting getSharedUser() {
12122            return mSharedUser;
12123        }
12124
12125        public void setSharedUser(SharedUserSetting user) {
12126            mSharedUser = user;
12127        }
12128    }
12129
12130    @Override
12131    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12132        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12133                != PackageManager.PERMISSION_GRANTED) {
12134            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12135                    + Binder.getCallingPid()
12136                    + ", uid=" + Binder.getCallingUid()
12137                    + " without permission "
12138                    + android.Manifest.permission.DUMP);
12139            return;
12140        }
12141
12142        DumpState dumpState = new DumpState();
12143        boolean fullPreferred = false;
12144        boolean checkin = false;
12145
12146        String packageName = null;
12147
12148        int opti = 0;
12149        while (opti < args.length) {
12150            String opt = args[opti];
12151            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12152                break;
12153            }
12154            opti++;
12155            if ("-a".equals(opt)) {
12156                // Right now we only know how to print all.
12157            } else if ("-h".equals(opt)) {
12158                pw.println("Package manager dump options:");
12159                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12160                pw.println("    --checkin: dump for a checkin");
12161                pw.println("    -f: print details of intent filters");
12162                pw.println("    -h: print this help");
12163                pw.println("  cmd may be one of:");
12164                pw.println("    l[ibraries]: list known shared libraries");
12165                pw.println("    f[ibraries]: list device features");
12166                pw.println("    k[eysets]: print known keysets");
12167                pw.println("    r[esolvers]: dump intent resolvers");
12168                pw.println("    perm[issions]: dump permissions");
12169                pw.println("    pref[erred]: print preferred package settings");
12170                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12171                pw.println("    prov[iders]: dump content providers");
12172                pw.println("    p[ackages]: dump installed packages");
12173                pw.println("    s[hared-users]: dump shared user IDs");
12174                pw.println("    m[essages]: print collected runtime messages");
12175                pw.println("    v[erifiers]: print package verifier info");
12176                pw.println("    version: print database version info");
12177                pw.println("    write: write current settings now");
12178                pw.println("    <package.name>: info about given package");
12179                pw.println("    installs: details about install sessions");
12180                return;
12181            } else if ("--checkin".equals(opt)) {
12182                checkin = true;
12183            } else if ("-f".equals(opt)) {
12184                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12185            } else {
12186                pw.println("Unknown argument: " + opt + "; use -h for help");
12187            }
12188        }
12189
12190        // Is the caller requesting to dump a particular piece of data?
12191        if (opti < args.length) {
12192            String cmd = args[opti];
12193            opti++;
12194            // Is this a package name?
12195            if ("android".equals(cmd) || cmd.contains(".")) {
12196                packageName = cmd;
12197                // When dumping a single package, we always dump all of its
12198                // filter information since the amount of data will be reasonable.
12199                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12200            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12201                dumpState.setDump(DumpState.DUMP_LIBS);
12202            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12203                dumpState.setDump(DumpState.DUMP_FEATURES);
12204            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12205                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12206            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12207                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12208            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12209                dumpState.setDump(DumpState.DUMP_PREFERRED);
12210            } else if ("preferred-xml".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12212                if (opti < args.length && "--full".equals(args[opti])) {
12213                    fullPreferred = true;
12214                    opti++;
12215                }
12216            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12217                dumpState.setDump(DumpState.DUMP_PACKAGES);
12218            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12219                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12220            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12221                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12222            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12223                dumpState.setDump(DumpState.DUMP_MESSAGES);
12224            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12225                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12226            } else if ("version".equals(cmd)) {
12227                dumpState.setDump(DumpState.DUMP_VERSION);
12228            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12229                dumpState.setDump(DumpState.DUMP_KEYSETS);
12230            } else if ("write".equals(cmd)) {
12231                synchronized (mPackages) {
12232                    mSettings.writeLPr();
12233                    pw.println("Settings written.");
12234                    return;
12235                }
12236            } else if ("installs".equals(cmd)) {
12237                dumpState.setDump(DumpState.DUMP_INSTALLS);
12238            }
12239        }
12240
12241        if (checkin) {
12242            pw.println("vers,1");
12243        }
12244
12245        // reader
12246        synchronized (mPackages) {
12247            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12248                if (!checkin) {
12249                    if (dumpState.onTitlePrinted())
12250                        pw.println();
12251                    pw.println("Database versions:");
12252                    pw.print("  SDK Version:");
12253                    pw.print(" internal=");
12254                    pw.print(mSettings.mInternalSdkPlatform);
12255                    pw.print(" external=");
12256                    pw.println(mSettings.mExternalSdkPlatform);
12257                    pw.print("  DB Version:");
12258                    pw.print(" internal=");
12259                    pw.print(mSettings.mInternalDatabaseVersion);
12260                    pw.print(" external=");
12261                    pw.println(mSettings.mExternalDatabaseVersion);
12262                }
12263            }
12264
12265            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12266                if (!checkin) {
12267                    if (dumpState.onTitlePrinted())
12268                        pw.println();
12269                    pw.println("Verifiers:");
12270                    pw.print("  Required: ");
12271                    pw.print(mRequiredVerifierPackage);
12272                    pw.print(" (uid=");
12273                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12274                    pw.println(")");
12275                } else if (mRequiredVerifierPackage != null) {
12276                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12277                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12278                }
12279            }
12280
12281            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12282                boolean printedHeader = false;
12283                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12284                while (it.hasNext()) {
12285                    String name = it.next();
12286                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12287                    if (!checkin) {
12288                        if (!printedHeader) {
12289                            if (dumpState.onTitlePrinted())
12290                                pw.println();
12291                            pw.println("Libraries:");
12292                            printedHeader = true;
12293                        }
12294                        pw.print("  ");
12295                    } else {
12296                        pw.print("lib,");
12297                    }
12298                    pw.print(name);
12299                    if (!checkin) {
12300                        pw.print(" -> ");
12301                    }
12302                    if (ent.path != null) {
12303                        if (!checkin) {
12304                            pw.print("(jar) ");
12305                            pw.print(ent.path);
12306                        } else {
12307                            pw.print(",jar,");
12308                            pw.print(ent.path);
12309                        }
12310                    } else {
12311                        if (!checkin) {
12312                            pw.print("(apk) ");
12313                            pw.print(ent.apk);
12314                        } else {
12315                            pw.print(",apk,");
12316                            pw.print(ent.apk);
12317                        }
12318                    }
12319                    pw.println();
12320                }
12321            }
12322
12323            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12324                if (dumpState.onTitlePrinted())
12325                    pw.println();
12326                if (!checkin) {
12327                    pw.println("Features:");
12328                }
12329                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12330                while (it.hasNext()) {
12331                    String name = it.next();
12332                    if (!checkin) {
12333                        pw.print("  ");
12334                    } else {
12335                        pw.print("feat,");
12336                    }
12337                    pw.println(name);
12338                }
12339            }
12340
12341            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12342                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12343                        : "Activity Resolver Table:", "  ", packageName,
12344                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12345                    dumpState.setTitlePrinted(true);
12346                }
12347                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12348                        : "Receiver Resolver Table:", "  ", packageName,
12349                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12350                    dumpState.setTitlePrinted(true);
12351                }
12352                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12353                        : "Service Resolver Table:", "  ", packageName,
12354                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12355                    dumpState.setTitlePrinted(true);
12356                }
12357                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12358                        : "Provider Resolver Table:", "  ", packageName,
12359                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12360                    dumpState.setTitlePrinted(true);
12361                }
12362            }
12363
12364            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12365                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12366                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12367                    int user = mSettings.mPreferredActivities.keyAt(i);
12368                    if (pir.dump(pw,
12369                            dumpState.getTitlePrinted()
12370                                ? "\nPreferred Activities User " + user + ":"
12371                                : "Preferred Activities User " + user + ":", "  ",
12372                            packageName, true)) {
12373                        dumpState.setTitlePrinted(true);
12374                    }
12375                }
12376            }
12377
12378            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12379                pw.flush();
12380                FileOutputStream fout = new FileOutputStream(fd);
12381                BufferedOutputStream str = new BufferedOutputStream(fout);
12382                XmlSerializer serializer = new FastXmlSerializer();
12383                try {
12384                    serializer.setOutput(str, "utf-8");
12385                    serializer.startDocument(null, true);
12386                    serializer.setFeature(
12387                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12388                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12389                    serializer.endDocument();
12390                    serializer.flush();
12391                } catch (IllegalArgumentException e) {
12392                    pw.println("Failed writing: " + e);
12393                } catch (IllegalStateException e) {
12394                    pw.println("Failed writing: " + e);
12395                } catch (IOException e) {
12396                    pw.println("Failed writing: " + e);
12397                }
12398            }
12399
12400            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12401                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12402                if (packageName == null) {
12403                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12404                        if (iperm == 0) {
12405                            if (dumpState.onTitlePrinted())
12406                                pw.println();
12407                            pw.println("AppOp Permissions:");
12408                        }
12409                        pw.print("  AppOp Permission ");
12410                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12411                        pw.println(":");
12412                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12413                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12414                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12415                        }
12416                    }
12417                }
12418            }
12419
12420            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12421                boolean printedSomething = false;
12422                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12423                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12424                        continue;
12425                    }
12426                    if (!printedSomething) {
12427                        if (dumpState.onTitlePrinted())
12428                            pw.println();
12429                        pw.println("Registered ContentProviders:");
12430                        printedSomething = true;
12431                    }
12432                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12433                    pw.print("    "); pw.println(p.toString());
12434                }
12435                printedSomething = false;
12436                for (Map.Entry<String, PackageParser.Provider> entry :
12437                        mProvidersByAuthority.entrySet()) {
12438                    PackageParser.Provider p = entry.getValue();
12439                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12440                        continue;
12441                    }
12442                    if (!printedSomething) {
12443                        if (dumpState.onTitlePrinted())
12444                            pw.println();
12445                        pw.println("ContentProvider Authorities:");
12446                        printedSomething = true;
12447                    }
12448                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12449                    pw.print("    "); pw.println(p.toString());
12450                    if (p.info != null && p.info.applicationInfo != null) {
12451                        final String appInfo = p.info.applicationInfo.toString();
12452                        pw.print("      applicationInfo="); pw.println(appInfo);
12453                    }
12454                }
12455            }
12456
12457            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12458                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12459            }
12460
12461            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12462                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12463            }
12464
12465            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12466                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12467            }
12468
12469            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12470                if (dumpState.onTitlePrinted()) pw.println();
12471                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12472            }
12473
12474            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12475                if (dumpState.onTitlePrinted()) pw.println();
12476                mSettings.dumpReadMessagesLPr(pw, dumpState);
12477
12478                pw.println();
12479                pw.println("Package warning messages:");
12480                final File fname = getSettingsProblemFile();
12481                FileInputStream in = null;
12482                try {
12483                    in = new FileInputStream(fname);
12484                    final int avail = in.available();
12485                    final byte[] data = new byte[avail];
12486                    in.read(data);
12487                    pw.print(new String(data));
12488                } catch (FileNotFoundException e) {
12489                } catch (IOException e) {
12490                } finally {
12491                    if (in != null) {
12492                        try {
12493                            in.close();
12494                        } catch (IOException e) {
12495                        }
12496                    }
12497                }
12498            }
12499        }
12500    }
12501
12502    // ------- apps on sdcard specific code -------
12503    static final boolean DEBUG_SD_INSTALL = false;
12504
12505    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12506
12507    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12508
12509    private boolean mMediaMounted = false;
12510
12511    static String getEncryptKey() {
12512        try {
12513            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12514                    SD_ENCRYPTION_KEYSTORE_NAME);
12515            if (sdEncKey == null) {
12516                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12517                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12518                if (sdEncKey == null) {
12519                    Slog.e(TAG, "Failed to create encryption keys");
12520                    return null;
12521                }
12522            }
12523            return sdEncKey;
12524        } catch (NoSuchAlgorithmException nsae) {
12525            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12526            return null;
12527        } catch (IOException ioe) {
12528            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12529            return null;
12530        }
12531    }
12532
12533    /*
12534     * Update media status on PackageManager.
12535     */
12536    @Override
12537    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12538        int callingUid = Binder.getCallingUid();
12539        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12540            throw new SecurityException("Media status can only be updated by the system");
12541        }
12542        // reader; this apparently protects mMediaMounted, but should probably
12543        // be a different lock in that case.
12544        synchronized (mPackages) {
12545            Log.i(TAG, "Updating external media status from "
12546                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12547                    + (mediaStatus ? "mounted" : "unmounted"));
12548            if (DEBUG_SD_INSTALL)
12549                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12550                        + ", mMediaMounted=" + mMediaMounted);
12551            if (mediaStatus == mMediaMounted) {
12552                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12553                        : 0, -1);
12554                mHandler.sendMessage(msg);
12555                return;
12556            }
12557            mMediaMounted = mediaStatus;
12558        }
12559        // Queue up an async operation since the package installation may take a
12560        // little while.
12561        mHandler.post(new Runnable() {
12562            public void run() {
12563                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12564            }
12565        });
12566    }
12567
12568    /**
12569     * Called by MountService when the initial ASECs to scan are available.
12570     * Should block until all the ASEC containers are finished being scanned.
12571     */
12572    public void scanAvailableAsecs() {
12573        updateExternalMediaStatusInner(true, false, false);
12574        if (mShouldRestoreconData) {
12575            SELinuxMMAC.setRestoreconDone();
12576            mShouldRestoreconData = false;
12577        }
12578    }
12579
12580    /*
12581     * Collect information of applications on external media, map them against
12582     * existing containers and update information based on current mount status.
12583     * Please note that we always have to report status if reportStatus has been
12584     * set to true especially when unloading packages.
12585     */
12586    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12587            boolean externalStorage) {
12588        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12589        int[] uidArr = EmptyArray.INT;
12590
12591        final String[] list = PackageHelper.getSecureContainerList();
12592        if (ArrayUtils.isEmpty(list)) {
12593            Log.i(TAG, "No secure containers found");
12594        } else {
12595            // Process list of secure containers and categorize them
12596            // as active or stale based on their package internal state.
12597
12598            // reader
12599            synchronized (mPackages) {
12600                for (String cid : list) {
12601                    // Leave stages untouched for now; installer service owns them
12602                    if (PackageInstallerService.isStageName(cid)) continue;
12603
12604                    if (DEBUG_SD_INSTALL)
12605                        Log.i(TAG, "Processing container " + cid);
12606                    String pkgName = getAsecPackageName(cid);
12607                    if (pkgName == null) {
12608                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12609                        continue;
12610                    }
12611                    if (DEBUG_SD_INSTALL)
12612                        Log.i(TAG, "Looking for pkg : " + pkgName);
12613
12614                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12615                    if (ps == null) {
12616                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12617                        continue;
12618                    }
12619
12620                    /*
12621                     * Skip packages that are not external if we're unmounting
12622                     * external storage.
12623                     */
12624                    if (externalStorage && !isMounted && !isExternal(ps)) {
12625                        continue;
12626                    }
12627
12628                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12629                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12630                    // The package status is changed only if the code path
12631                    // matches between settings and the container id.
12632                    if (ps.codePathString != null
12633                            && ps.codePathString.startsWith(args.getCodePath())) {
12634                        if (DEBUG_SD_INSTALL) {
12635                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12636                                    + " at code path: " + ps.codePathString);
12637                        }
12638
12639                        // We do have a valid package installed on sdcard
12640                        processCids.put(args, ps.codePathString);
12641                        final int uid = ps.appId;
12642                        if (uid != -1) {
12643                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12644                        }
12645                    } else {
12646                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12647                                + ps.codePathString);
12648                    }
12649                }
12650            }
12651
12652            Arrays.sort(uidArr);
12653        }
12654
12655        // Process packages with valid entries.
12656        if (isMounted) {
12657            if (DEBUG_SD_INSTALL)
12658                Log.i(TAG, "Loading packages");
12659            loadMediaPackages(processCids, uidArr);
12660            startCleaningPackages();
12661            mInstallerService.onSecureContainersAvailable();
12662        } else {
12663            if (DEBUG_SD_INSTALL)
12664                Log.i(TAG, "Unloading packages");
12665            unloadMediaPackages(processCids, uidArr, reportStatus);
12666        }
12667    }
12668
12669    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12670            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12671        int size = pkgList.size();
12672        if (size > 0) {
12673            // Send broadcasts here
12674            Bundle extras = new Bundle();
12675            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12676                    .toArray(new String[size]));
12677            if (uidArr != null) {
12678                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12679            }
12680            if (replacing) {
12681                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12682            }
12683            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12684                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12685            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12686        }
12687    }
12688
12689   /*
12690     * Look at potentially valid container ids from processCids If package
12691     * information doesn't match the one on record or package scanning fails,
12692     * the cid is added to list of removeCids. We currently don't delete stale
12693     * containers.
12694     */
12695    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12696        ArrayList<String> pkgList = new ArrayList<String>();
12697        Set<AsecInstallArgs> keys = processCids.keySet();
12698
12699        for (AsecInstallArgs args : keys) {
12700            String codePath = processCids.get(args);
12701            if (DEBUG_SD_INSTALL)
12702                Log.i(TAG, "Loading container : " + args.cid);
12703            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12704            try {
12705                // Make sure there are no container errors first.
12706                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12707                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12708                            + " when installing from sdcard");
12709                    continue;
12710                }
12711                // Check code path here.
12712                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12713                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12714                            + " does not match one in settings " + codePath);
12715                    continue;
12716                }
12717                // Parse package
12718                int parseFlags = mDefParseFlags;
12719                if (args.isExternal()) {
12720                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12721                }
12722                if (args.isFwdLocked()) {
12723                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12724                }
12725
12726                synchronized (mInstallLock) {
12727                    PackageParser.Package pkg = null;
12728                    try {
12729                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12730                    } catch (PackageManagerException e) {
12731                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12732                    }
12733                    // Scan the package
12734                    if (pkg != null) {
12735                        /*
12736                         * TODO why is the lock being held? doPostInstall is
12737                         * called in other places without the lock. This needs
12738                         * to be straightened out.
12739                         */
12740                        // writer
12741                        synchronized (mPackages) {
12742                            retCode = PackageManager.INSTALL_SUCCEEDED;
12743                            pkgList.add(pkg.packageName);
12744                            // Post process args
12745                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12746                                    pkg.applicationInfo.uid);
12747                        }
12748                    } else {
12749                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12750                    }
12751                }
12752
12753            } finally {
12754                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12755                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12756                }
12757            }
12758        }
12759        // writer
12760        synchronized (mPackages) {
12761            // If the platform SDK has changed since the last time we booted,
12762            // we need to re-grant app permission to catch any new ones that
12763            // appear. This is really a hack, and means that apps can in some
12764            // cases get permissions that the user didn't initially explicitly
12765            // allow... it would be nice to have some better way to handle
12766            // this situation.
12767            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12768            if (regrantPermissions)
12769                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12770                        + mSdkVersion + "; regranting permissions for external storage");
12771            mSettings.mExternalSdkPlatform = mSdkVersion;
12772
12773            // Make sure group IDs have been assigned, and any permission
12774            // changes in other apps are accounted for
12775            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12776                    | (regrantPermissions
12777                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12778                            : 0));
12779
12780            mSettings.updateExternalDatabaseVersion();
12781
12782            // can downgrade to reader
12783            // Persist settings
12784            mSettings.writeLPr();
12785        }
12786        // Send a broadcast to let everyone know we are done processing
12787        if (pkgList.size() > 0) {
12788            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12789        }
12790    }
12791
12792   /*
12793     * Utility method to unload a list of specified containers
12794     */
12795    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12796        // Just unmount all valid containers.
12797        for (AsecInstallArgs arg : cidArgs) {
12798            synchronized (mInstallLock) {
12799                arg.doPostDeleteLI(false);
12800           }
12801       }
12802   }
12803
12804    /*
12805     * Unload packages mounted on external media. This involves deleting package
12806     * data from internal structures, sending broadcasts about diabled packages,
12807     * gc'ing to free up references, unmounting all secure containers
12808     * corresponding to packages on external media, and posting a
12809     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12810     * that we always have to post this message if status has been requested no
12811     * matter what.
12812     */
12813    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12814            final boolean reportStatus) {
12815        if (DEBUG_SD_INSTALL)
12816            Log.i(TAG, "unloading media packages");
12817        ArrayList<String> pkgList = new ArrayList<String>();
12818        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12819        final Set<AsecInstallArgs> keys = processCids.keySet();
12820        for (AsecInstallArgs args : keys) {
12821            String pkgName = args.getPackageName();
12822            if (DEBUG_SD_INSTALL)
12823                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12824            // Delete package internally
12825            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12826            synchronized (mInstallLock) {
12827                boolean res = deletePackageLI(pkgName, null, false, null, null,
12828                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12829                if (res) {
12830                    pkgList.add(pkgName);
12831                } else {
12832                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12833                    failedList.add(args);
12834                }
12835            }
12836        }
12837
12838        // reader
12839        synchronized (mPackages) {
12840            // We didn't update the settings after removing each package;
12841            // write them now for all packages.
12842            mSettings.writeLPr();
12843        }
12844
12845        // We have to absolutely send UPDATED_MEDIA_STATUS only
12846        // after confirming that all the receivers processed the ordered
12847        // broadcast when packages get disabled, force a gc to clean things up.
12848        // and unload all the containers.
12849        if (pkgList.size() > 0) {
12850            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12851                    new IIntentReceiver.Stub() {
12852                public void performReceive(Intent intent, int resultCode, String data,
12853                        Bundle extras, boolean ordered, boolean sticky,
12854                        int sendingUser) throws RemoteException {
12855                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12856                            reportStatus ? 1 : 0, 1, keys);
12857                    mHandler.sendMessage(msg);
12858                }
12859            });
12860        } else {
12861            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12862                    keys);
12863            mHandler.sendMessage(msg);
12864        }
12865    }
12866
12867    /** Binder call */
12868    @Override
12869    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12870            final int flags) {
12871        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12872        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12873        int returnCode = PackageManager.MOVE_SUCCEEDED;
12874        int currInstallFlags = 0;
12875        int newInstallFlags = 0;
12876
12877        File codeFile = null;
12878        String installerPackageName = null;
12879        String packageAbiOverride = null;
12880
12881        // reader
12882        synchronized (mPackages) {
12883            final PackageParser.Package pkg = mPackages.get(packageName);
12884            final PackageSetting ps = mSettings.mPackages.get(packageName);
12885            if (pkg == null || ps == null) {
12886                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12887            } else {
12888                // Disable moving fwd locked apps and system packages
12889                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12890                    Slog.w(TAG, "Cannot move system application");
12891                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12892                } else if (pkg.mOperationPending) {
12893                    Slog.w(TAG, "Attempt to move package which has pending operations");
12894                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12895                } else {
12896                    // Find install location first
12897                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12898                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12899                        Slog.w(TAG, "Ambigous flags specified for move location.");
12900                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12901                    } else {
12902                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12903                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12904                        currInstallFlags = isExternal(pkg)
12905                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12906
12907                        if (newInstallFlags == currInstallFlags) {
12908                            Slog.w(TAG, "No move required. Trying to move to same location");
12909                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12910                        } else {
12911                            if (isForwardLocked(pkg)) {
12912                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12913                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12914                            }
12915                        }
12916                    }
12917                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12918                        pkg.mOperationPending = true;
12919                    }
12920                }
12921
12922                codeFile = new File(pkg.codePath);
12923                installerPackageName = ps.installerPackageName;
12924                packageAbiOverride = ps.cpuAbiOverrideString;
12925            }
12926        }
12927
12928        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12929            try {
12930                observer.packageMoved(packageName, returnCode);
12931            } catch (RemoteException ignored) {
12932            }
12933            return;
12934        }
12935
12936        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12937            @Override
12938            public void onUserActionRequired(Intent intent) throws RemoteException {
12939                throw new IllegalStateException();
12940            }
12941
12942            @Override
12943            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12944                    Bundle extras) throws RemoteException {
12945                Slog.d(TAG, "Install result for move: "
12946                        + PackageManager.installStatusToString(returnCode, msg));
12947
12948                // We usually have a new package now after the install, but if
12949                // we failed we need to clear the pending flag on the original
12950                // package object.
12951                synchronized (mPackages) {
12952                    final PackageParser.Package pkg = mPackages.get(packageName);
12953                    if (pkg != null) {
12954                        pkg.mOperationPending = false;
12955                    }
12956                }
12957
12958                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12959                switch (status) {
12960                    case PackageInstaller.STATUS_SUCCESS:
12961                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12962                        break;
12963                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12964                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12965                        break;
12966                    default:
12967                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12968                        break;
12969                }
12970            }
12971        };
12972
12973        // Treat a move like reinstalling an existing app, which ensures that we
12974        // process everythign uniformly, like unpacking native libraries.
12975        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12976
12977        final Message msg = mHandler.obtainMessage(INIT_COPY);
12978        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12979        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12980                installerPackageName, null, user, packageAbiOverride);
12981        mHandler.sendMessage(msg);
12982    }
12983
12984    @Override
12985    public boolean setInstallLocation(int loc) {
12986        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12987                null);
12988        if (getInstallLocation() == loc) {
12989            return true;
12990        }
12991        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12992                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12993            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12994                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12995            return true;
12996        }
12997        return false;
12998   }
12999
13000    @Override
13001    public int getInstallLocation() {
13002        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13003                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13004                PackageHelper.APP_INSTALL_AUTO);
13005    }
13006
13007    /** Called by UserManagerService */
13008    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13009        mDirtyUsers.remove(userHandle);
13010        mSettings.removeUserLPw(userHandle);
13011        mPendingBroadcasts.remove(userHandle);
13012        if (mInstaller != null) {
13013            // Technically, we shouldn't be doing this with the package lock
13014            // held.  However, this is very rare, and there is already so much
13015            // other disk I/O going on, that we'll let it slide for now.
13016            mInstaller.removeUserDataDirs(userHandle);
13017        }
13018        mUserNeedsBadging.delete(userHandle);
13019        removeUnusedPackagesLILPw(userManager, userHandle);
13020    }
13021
13022    /**
13023     * We're removing userHandle and would like to remove any downloaded packages
13024     * that are no longer in use by any other user.
13025     * @param userHandle the user being removed
13026     */
13027    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13028        final boolean DEBUG_CLEAN_APKS = false;
13029        int [] users = userManager.getUserIdsLPr();
13030        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13031        while (psit.hasNext()) {
13032            PackageSetting ps = psit.next();
13033            if (ps.pkg == null) {
13034                continue;
13035            }
13036            final String packageName = ps.pkg.packageName;
13037            // Skip over if system app
13038            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13039                continue;
13040            }
13041            if (DEBUG_CLEAN_APKS) {
13042                Slog.i(TAG, "Checking package " + packageName);
13043            }
13044            boolean keep = false;
13045            for (int i = 0; i < users.length; i++) {
13046                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13047                    keep = true;
13048                    if (DEBUG_CLEAN_APKS) {
13049                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13050                                + users[i]);
13051                    }
13052                    break;
13053                }
13054            }
13055            if (!keep) {
13056                if (DEBUG_CLEAN_APKS) {
13057                    Slog.i(TAG, "  Removing package " + packageName);
13058                }
13059                mHandler.post(new Runnable() {
13060                    public void run() {
13061                        deletePackageX(packageName, userHandle, 0);
13062                    } //end run
13063                });
13064            }
13065        }
13066    }
13067
13068    /** Called by UserManagerService */
13069    void createNewUserLILPw(int userHandle, File path) {
13070        if (mInstaller != null) {
13071            mInstaller.createUserConfig(userHandle);
13072            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13073        }
13074    }
13075
13076    @Override
13077    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13078        mContext.enforceCallingOrSelfPermission(
13079                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13080                "Only package verification agents can read the verifier device identity");
13081
13082        synchronized (mPackages) {
13083            return mSettings.getVerifierDeviceIdentityLPw();
13084        }
13085    }
13086
13087    @Override
13088    public void setPermissionEnforced(String permission, boolean enforced) {
13089        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13090        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13091            synchronized (mPackages) {
13092                if (mSettings.mReadExternalStorageEnforced == null
13093                        || mSettings.mReadExternalStorageEnforced != enforced) {
13094                    mSettings.mReadExternalStorageEnforced = enforced;
13095                    mSettings.writeLPr();
13096                }
13097            }
13098            // kill any non-foreground processes so we restart them and
13099            // grant/revoke the GID.
13100            final IActivityManager am = ActivityManagerNative.getDefault();
13101            if (am != null) {
13102                final long token = Binder.clearCallingIdentity();
13103                try {
13104                    am.killProcessesBelowForeground("setPermissionEnforcement");
13105                } catch (RemoteException e) {
13106                } finally {
13107                    Binder.restoreCallingIdentity(token);
13108                }
13109            }
13110        } else {
13111            throw new IllegalArgumentException("No selective enforcement for " + permission);
13112        }
13113    }
13114
13115    @Override
13116    @Deprecated
13117    public boolean isPermissionEnforced(String permission) {
13118        return true;
13119    }
13120
13121    @Override
13122    public boolean isStorageLow() {
13123        final long token = Binder.clearCallingIdentity();
13124        try {
13125            final DeviceStorageMonitorInternal
13126                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13127            if (dsm != null) {
13128                return dsm.isMemoryLow();
13129            } else {
13130                return false;
13131            }
13132        } finally {
13133            Binder.restoreCallingIdentity(token);
13134        }
13135    }
13136
13137    @Override
13138    public IPackageInstaller getPackageInstaller() {
13139        return mInstallerService;
13140    }
13141
13142    private boolean userNeedsBadging(int userId) {
13143        int index = mUserNeedsBadging.indexOfKey(userId);
13144        if (index < 0) {
13145            final UserInfo userInfo;
13146            final long token = Binder.clearCallingIdentity();
13147            try {
13148                userInfo = sUserManager.getUserInfo(userId);
13149            } finally {
13150                Binder.restoreCallingIdentity(token);
13151            }
13152            final boolean b;
13153            if (userInfo != null && userInfo.isManagedProfile()) {
13154                b = true;
13155            } else {
13156                b = false;
13157            }
13158            mUserNeedsBadging.put(userId, b);
13159            return b;
13160        }
13161        return mUserNeedsBadging.valueAt(index);
13162    }
13163
13164    @Override
13165    public KeySet getKeySetByAlias(String packageName, String alias) {
13166        if (packageName == null || alias == null) {
13167            return null;
13168        }
13169        synchronized(mPackages) {
13170            final PackageParser.Package pkg = mPackages.get(packageName);
13171            if (pkg == null) {
13172                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13173                throw new IllegalArgumentException("Unknown package: " + packageName);
13174            }
13175            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13176            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13177        }
13178    }
13179
13180    @Override
13181    public KeySet getSigningKeySet(String packageName) {
13182        if (packageName == null) {
13183            return null;
13184        }
13185        synchronized(mPackages) {
13186            final PackageParser.Package pkg = mPackages.get(packageName);
13187            if (pkg == null) {
13188                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13189                throw new IllegalArgumentException("Unknown package: " + packageName);
13190            }
13191            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13192                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13193                throw new SecurityException("May not access signing KeySet of other apps.");
13194            }
13195            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13196            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13197        }
13198    }
13199
13200    @Override
13201    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13202        if (packageName == null || ks == null) {
13203            return false;
13204        }
13205        synchronized(mPackages) {
13206            final PackageParser.Package pkg = mPackages.get(packageName);
13207            if (pkg == null) {
13208                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13209                throw new IllegalArgumentException("Unknown package: " + packageName);
13210            }
13211            IBinder ksh = ks.getToken();
13212            if (ksh instanceof KeySetHandle) {
13213                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13214                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13215            }
13216            return false;
13217        }
13218    }
13219
13220    @Override
13221    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13222        if (packageName == null || ks == null) {
13223            return false;
13224        }
13225        synchronized(mPackages) {
13226            final PackageParser.Package pkg = mPackages.get(packageName);
13227            if (pkg == null) {
13228                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13229                throw new IllegalArgumentException("Unknown package: " + packageName);
13230            }
13231            IBinder ksh = ks.getToken();
13232            if (ksh instanceof KeySetHandle) {
13233                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13234                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13235            }
13236            return false;
13237        }
13238    }
13239}
13240