PackageManagerService.java revision d68f83cc478a8ec501d0a5a08a2a737355bee89a
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.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.storage.StorageManager;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteException;
149import android.os.SELinux;
150import android.os.ServiceManager;
151import android.os.SystemClock;
152import android.os.SystemProperties;
153import android.os.UserHandle;
154import android.os.UserManager;
155import android.security.KeyStore;
156import android.security.SystemKeyStore;
157import android.system.ErrnoException;
158import android.system.Os;
159import android.system.StructStat;
160import android.text.TextUtils;
161import android.util.ArraySet;
162import android.util.AtomicFile;
163import android.util.DisplayMetrics;
164import android.util.EventLog;
165import android.util.ExceptionUtils;
166import android.util.Log;
167import android.util.LogPrinter;
168import android.util.PrintStreamPrinter;
169import android.util.Slog;
170import android.util.SparseArray;
171import android.util.SparseBooleanArray;
172import android.view.Display;
173
174import java.io.BufferedInputStream;
175import java.io.BufferedOutputStream;
176import java.io.File;
177import java.io.FileDescriptor;
178import java.io.FileInputStream;
179import java.io.FileNotFoundException;
180import java.io.FileOutputStream;
181import java.io.FilenameFilter;
182import java.io.IOException;
183import java.io.InputStream;
184import java.io.PrintWriter;
185import java.nio.charset.StandardCharsets;
186import java.security.NoSuchAlgorithmException;
187import java.security.PublicKey;
188import java.security.cert.CertificateEncodingException;
189import java.security.cert.CertificateException;
190import java.text.SimpleDateFormat;
191import java.util.ArrayList;
192import java.util.Arrays;
193import java.util.Collection;
194import java.util.Collections;
195import java.util.Comparator;
196import java.util.Date;
197import java.util.HashMap;
198import java.util.HashSet;
199import java.util.Iterator;
200import java.util.List;
201import java.util.Map;
202import java.util.Set;
203import java.util.concurrent.atomic.AtomicBoolean;
204import java.util.concurrent.atomic.AtomicLong;
205
206import dalvik.system.DexFile;
207import dalvik.system.StaleDexCacheError;
208import dalvik.system.VMRuntime;
209
210import libcore.io.IoUtils;
211import libcore.util.EmptyArray;
212
213/**
214 * Keep track of all those .apks everywhere.
215 *
216 * This is very central to the platform's security; please run the unit
217 * tests whenever making modifications here:
218 *
219mmm frameworks/base/tests/AndroidTests
220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
222 *
223 * {@hide}
224 */
225public class PackageManagerService extends IPackageManager.Stub {
226    static final String TAG = "PackageManager";
227    static final boolean DEBUG_SETTINGS = false;
228    static final boolean DEBUG_PREFERRED = false;
229    static final boolean DEBUG_UPGRADE = false;
230    private static final boolean DEBUG_INSTALL = false;
231    private static final boolean DEBUG_REMOVE = false;
232    private static final boolean DEBUG_BROADCASTS = false;
233    private static final boolean DEBUG_SHOW_INFO = false;
234    private static final boolean DEBUG_PACKAGE_INFO = false;
235    private static final boolean DEBUG_INTENT_MATCHING = false;
236    private static final boolean DEBUG_PACKAGE_SCANNING = false;
237    private static final boolean DEBUG_VERIFY = false;
238    private static final boolean DEBUG_DEXOPT = false;
239    private static final boolean DEBUG_ABI_SELECTION = false;
240
241    private static final int RADIO_UID = Process.PHONE_UID;
242    private static final int LOG_UID = Process.LOG_UID;
243    private static final int NFC_UID = Process.NFC_UID;
244    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
245    private static final int SHELL_UID = Process.SHELL_UID;
246
247    // Cap the size of permission trees that 3rd party apps can define
248    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
249
250    // Suffix used during package installation when copying/moving
251    // package apks to install directory.
252    private static final String INSTALL_PACKAGE_SUFFIX = "-";
253
254    static final int SCAN_MONITOR = 1<<0;
255    static final int SCAN_NO_DEX = 1<<1;
256    static final int SCAN_FORCE_DEX = 1<<2;
257    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
258    static final int SCAN_NEW_INSTALL = 1<<4;
259    static final int SCAN_NO_PATHS = 1<<5;
260    static final int SCAN_UPDATE_TIME = 1<<6;
261    static final int SCAN_DEFER_DEX = 1<<7;
262    static final int SCAN_BOOTING = 1<<8;
263    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
264    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
265
266    static final int REMOVE_CHATTY = 1<<16;
267
268    /**
269     * Timeout (in milliseconds) after which the watchdog should declare that
270     * our handler thread is wedged.  The usual default for such things is one
271     * minute but we sometimes do very lengthy I/O operations on this thread,
272     * such as installing multi-gigabyte applications, so ours needs to be longer.
273     */
274    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
275
276    /**
277     * Whether verification is enabled by default.
278     */
279    private static final boolean DEFAULT_VERIFY_ENABLE = true;
280
281    /**
282     * The default maximum time to wait for the verification agent to return in
283     * milliseconds.
284     */
285    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
286
287    /**
288     * The default response for package verification timeout.
289     *
290     * This can be either PackageManager.VERIFICATION_ALLOW or
291     * PackageManager.VERIFICATION_REJECT.
292     */
293    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
294
295    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
296
297    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
298            DEFAULT_CONTAINER_PACKAGE,
299            "com.android.defcontainer.DefaultContainerService");
300
301    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
302
303    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
304
305    private static String sPreferredInstructionSet;
306
307    final ServiceThread mHandlerThread;
308
309    private static final String IDMAP_PREFIX = "/data/resource-cache/";
310    private static final String IDMAP_SUFFIX = "@idmap";
311
312    final PackageHandler mHandler;
313
314    final int mSdkVersion = Build.VERSION.SDK_INT;
315
316    final Context mContext;
317    final boolean mFactoryTest;
318    final boolean mOnlyCore;
319    final DisplayMetrics mMetrics;
320    final int mDefParseFlags;
321    final String[] mSeparateProcesses;
322
323    // This is where all application persistent data goes.
324    final File mAppDataDir;
325
326    // This is where all application persistent data goes for secondary users.
327    final File mUserAppDataDir;
328
329    /** The location for ASEC container files on internal storage. */
330    final String mAsecInternalPath;
331
332    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
333    // LOCK HELD.  Can be called with mInstallLock held.
334    final Installer mInstaller;
335
336    /** Directory where installed third-party apps stored */
337    final File mAppInstallDir;
338
339    /**
340     * Directory to which applications installed internally have their
341     * 32 bit native libraries copied.
342     */
343    private File mAppLib32InstallDir;
344
345    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
346    // apps.
347    final File mDrmAppPrivateInstallDir;
348
349    // ----------------------------------------------------------------
350
351    // Lock for state used when installing and doing other long running
352    // operations.  Methods that must be called with this lock held have
353    // the suffix "LI".
354    final Object mInstallLock = new Object();
355
356    // These are the directories in the 3rd party applications installed dir
357    // that we have currently loaded packages from.  Keys are the application's
358    // installed zip file (absolute codePath), and values are Package.
359    final HashMap<String, PackageParser.Package> mAppDirs =
360            new HashMap<String, PackageParser.Package>();
361
362    // ----------------------------------------------------------------
363
364    // Keys are String (package name), values are Package.  This also serves
365    // as the lock for the global state.  Methods that must be called with
366    // this lock held have the prefix "LP".
367    final HashMap<String, PackageParser.Package> mPackages =
368            new HashMap<String, PackageParser.Package>();
369
370    // Tracks available target package names -> overlay package paths.
371    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
372        new HashMap<String, HashMap<String, PackageParser.Package>>();
373
374    final Settings mSettings;
375    boolean mRestoredSettings;
376
377    // System configuration read by SystemConfig.
378    final int[] mGlobalGids;
379    final SparseArray<HashSet<String>> mSystemPermissions;
380    final HashMap<String, FeatureInfo> mAvailableFeatures;
381
382    // If mac_permissions.xml was found for seinfo labeling.
383    boolean mFoundPolicyFile;
384
385    // If a recursive restorecon of /data/data/<pkg> is needed.
386    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
387
388    public static final class SharedLibraryEntry {
389        public final String path;
390        public final String apk;
391
392        SharedLibraryEntry(String _path, String _apk) {
393            path = _path;
394            apk = _apk;
395        }
396    }
397
398    // Currently known shared libraries.
399    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
400            new HashMap<String, SharedLibraryEntry>();
401
402    // All available activities, for your resolving pleasure.
403    final ActivityIntentResolver mActivities =
404            new ActivityIntentResolver();
405
406    // All available receivers, for your resolving pleasure.
407    final ActivityIntentResolver mReceivers =
408            new ActivityIntentResolver();
409
410    // All available services, for your resolving pleasure.
411    final ServiceIntentResolver mServices = new ServiceIntentResolver();
412
413    // All available providers, for your resolving pleasure.
414    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
415
416    // Mapping from provider base names (first directory in content URI codePath)
417    // to the provider information.
418    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
419            new HashMap<String, PackageParser.Provider>();
420
421    // Mapping from instrumentation class names to info about them.
422    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
423            new HashMap<ComponentName, PackageParser.Instrumentation>();
424
425    // Mapping from permission names to info about them.
426    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
427            new HashMap<String, PackageParser.PermissionGroup>();
428
429    // Packages whose data we have transfered into another package, thus
430    // should no longer exist.
431    final HashSet<String> mTransferedPackages = new HashSet<String>();
432
433    // Broadcast actions that are only available to the system.
434    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
435
436    /** List of packages waiting for verification. */
437    final SparseArray<PackageVerificationState> mPendingVerification
438            = new SparseArray<PackageVerificationState>();
439
440    /** Set of packages associated with each app op permission. */
441    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
442
443    final PackageInstallerService mInstallerService;
444
445    HashSet<PackageParser.Package> mDeferredDexOpt = null;
446
447    // Cache of users who need badging.
448    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
449
450    /** Token for keys in mPendingVerification. */
451    private int mPendingVerificationToken = 0;
452
453    boolean mSystemReady;
454    boolean mSafeMode;
455    boolean mHasSystemUidErrors;
456
457    ApplicationInfo mAndroidApplication;
458    final ActivityInfo mResolveActivity = new ActivityInfo();
459    final ResolveInfo mResolveInfo = new ResolveInfo();
460    ComponentName mResolveComponentName;
461    PackageParser.Package mPlatformPackage;
462    ComponentName mCustomResolverComponentName;
463
464    boolean mResolverReplaced = false;
465
466    // Set of pending broadcasts for aggregating enable/disable of components.
467    static class PendingPackageBroadcasts {
468        // for each user id, a map of <package name -> components within that package>
469        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
470
471        public PendingPackageBroadcasts() {
472            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
473        }
474
475        public ArrayList<String> get(int userId, String packageName) {
476            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
477            return packages.get(packageName);
478        }
479
480        public void put(int userId, String packageName, ArrayList<String> components) {
481            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
482            packages.put(packageName, components);
483        }
484
485        public void remove(int userId, String packageName) {
486            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
487            if (packages != null) {
488                packages.remove(packageName);
489            }
490        }
491
492        public void remove(int userId) {
493            mUidMap.remove(userId);
494        }
495
496        public int userIdCount() {
497            return mUidMap.size();
498        }
499
500        public int userIdAt(int n) {
501            return mUidMap.keyAt(n);
502        }
503
504        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
505            return mUidMap.get(userId);
506        }
507
508        public int size() {
509            // total number of pending broadcast entries across all userIds
510            int num = 0;
511            for (int i = 0; i< mUidMap.size(); i++) {
512                num += mUidMap.valueAt(i).size();
513            }
514            return num;
515        }
516
517        public void clear() {
518            mUidMap.clear();
519        }
520
521        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
522            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
523            if (map == null) {
524                map = new HashMap<String, ArrayList<String>>();
525                mUidMap.put(userId, map);
526            }
527            return map;
528        }
529    }
530    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
531
532    // Service Connection to remote media container service to copy
533    // package uri's from external media onto secure containers
534    // or internal storage.
535    private IMediaContainerService mContainerService = null;
536
537    static final int SEND_PENDING_BROADCAST = 1;
538    static final int MCS_BOUND = 3;
539    static final int END_COPY = 4;
540    static final int INIT_COPY = 5;
541    static final int MCS_UNBIND = 6;
542    static final int START_CLEANING_PACKAGE = 7;
543    static final int FIND_INSTALL_LOC = 8;
544    static final int POST_INSTALL = 9;
545    static final int MCS_RECONNECT = 10;
546    static final int MCS_GIVE_UP = 11;
547    static final int UPDATED_MEDIA_STATUS = 12;
548    static final int WRITE_SETTINGS = 13;
549    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
550    static final int PACKAGE_VERIFIED = 15;
551    static final int CHECK_PENDING_VERIFICATION = 16;
552
553    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
554
555    // Delay time in millisecs
556    static final int BROADCAST_DELAY = 10 * 1000;
557
558    static UserManagerService sUserManager;
559
560    // Stores a list of users whose package restrictions file needs to be updated
561    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
562
563    final private DefaultContainerConnection mDefContainerConn =
564            new DefaultContainerConnection();
565    class DefaultContainerConnection implements ServiceConnection {
566        public void onServiceConnected(ComponentName name, IBinder service) {
567            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
568            IMediaContainerService imcs =
569                IMediaContainerService.Stub.asInterface(service);
570            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
571        }
572
573        public void onServiceDisconnected(ComponentName name) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
575        }
576    };
577
578    // Recordkeeping of restore-after-install operations that are currently in flight
579    // between the Package Manager and the Backup Manager
580    class PostInstallData {
581        public InstallArgs args;
582        public PackageInstalledInfo res;
583
584        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
585            args = _a;
586            res = _r;
587        }
588    };
589    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
590    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
591
592    private final String mRequiredVerifierPackage;
593
594    private final PackageUsage mPackageUsage = new PackageUsage();
595
596    private class PackageUsage {
597        private static final int WRITE_INTERVAL
598            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
599
600        private final Object mFileLock = new Object();
601        private final AtomicLong mLastWritten = new AtomicLong(0);
602        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
603
604        private boolean mIsHistoricalPackageUsageAvailable = true;
605
606        boolean isHistoricalPackageUsageAvailable() {
607            return mIsHistoricalPackageUsageAvailable;
608        }
609
610        void write(boolean force) {
611            if (force) {
612                writeInternal();
613                return;
614            }
615            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
616                && !DEBUG_DEXOPT) {
617                return;
618            }
619            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
620                new Thread("PackageUsage_DiskWriter") {
621                    @Override
622                    public void run() {
623                        try {
624                            writeInternal();
625                        } finally {
626                            mBackgroundWriteRunning.set(false);
627                        }
628                    }
629                }.start();
630            }
631        }
632
633        private void writeInternal() {
634            synchronized (mPackages) {
635                synchronized (mFileLock) {
636                    AtomicFile file = getFile();
637                    FileOutputStream f = null;
638                    try {
639                        f = file.startWrite();
640                        BufferedOutputStream out = new BufferedOutputStream(f);
641                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
642                        StringBuilder sb = new StringBuilder();
643                        for (PackageParser.Package pkg : mPackages.values()) {
644                            if (pkg.mLastPackageUsageTimeInMills == 0) {
645                                continue;
646                            }
647                            sb.setLength(0);
648                            sb.append(pkg.packageName);
649                            sb.append(' ');
650                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
651                            sb.append('\n');
652                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
653                        }
654                        out.flush();
655                        file.finishWrite(f);
656                    } catch (IOException e) {
657                        if (f != null) {
658                            file.failWrite(f);
659                        }
660                        Log.e(TAG, "Failed to write package usage times", e);
661                    }
662                }
663            }
664            mLastWritten.set(SystemClock.elapsedRealtime());
665        }
666
667        void readLP() {
668            synchronized (mFileLock) {
669                AtomicFile file = getFile();
670                BufferedInputStream in = null;
671                try {
672                    in = new BufferedInputStream(file.openRead());
673                    StringBuffer sb = new StringBuffer();
674                    while (true) {
675                        String packageName = readToken(in, sb, ' ');
676                        if (packageName == null) {
677                            break;
678                        }
679                        String timeInMillisString = readToken(in, sb, '\n');
680                        if (timeInMillisString == null) {
681                            throw new IOException("Failed to find last usage time for package "
682                                                  + packageName);
683                        }
684                        PackageParser.Package pkg = mPackages.get(packageName);
685                        if (pkg == null) {
686                            continue;
687                        }
688                        long timeInMillis;
689                        try {
690                            timeInMillis = Long.parseLong(timeInMillisString.toString());
691                        } catch (NumberFormatException e) {
692                            throw new IOException("Failed to parse " + timeInMillisString
693                                                  + " as a long.", e);
694                        }
695                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
696                    }
697                } catch (FileNotFoundException expected) {
698                    mIsHistoricalPackageUsageAvailable = false;
699                } catch (IOException e) {
700                    Log.w(TAG, "Failed to read package usage times", e);
701                } finally {
702                    IoUtils.closeQuietly(in);
703                }
704            }
705            mLastWritten.set(SystemClock.elapsedRealtime());
706        }
707
708        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
709                throws IOException {
710            sb.setLength(0);
711            while (true) {
712                int ch = in.read();
713                if (ch == -1) {
714                    if (sb.length() == 0) {
715                        return null;
716                    }
717                    throw new IOException("Unexpected EOF");
718                }
719                if (ch == endOfToken) {
720                    return sb.toString();
721                }
722                sb.append((char)ch);
723            }
724        }
725
726        private AtomicFile getFile() {
727            File dataDir = Environment.getDataDirectory();
728            File systemDir = new File(dataDir, "system");
729            File fname = new File(systemDir, "package-usage.list");
730            return new AtomicFile(fname);
731        }
732    }
733
734    class PackageHandler extends Handler {
735        private boolean mBound = false;
736        final ArrayList<HandlerParams> mPendingInstalls =
737            new ArrayList<HandlerParams>();
738
739        private boolean connectToService() {
740            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
741                    " DefaultContainerService");
742            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
743            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
744            if (mContext.bindServiceAsUser(service, mDefContainerConn,
745                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
746                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
747                mBound = true;
748                return true;
749            }
750            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751            return false;
752        }
753
754        private void disconnectService() {
755            mContainerService = null;
756            mBound = false;
757            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
758            mContext.unbindService(mDefContainerConn);
759            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
760        }
761
762        PackageHandler(Looper looper) {
763            super(looper);
764        }
765
766        public void handleMessage(Message msg) {
767            try {
768                doHandleMessage(msg);
769            } finally {
770                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            }
772        }
773
774        void doHandleMessage(Message msg) {
775            switch (msg.what) {
776                case INIT_COPY: {
777                    HandlerParams params = (HandlerParams) msg.obj;
778                    int idx = mPendingInstalls.size();
779                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
780                    // If a bind was already initiated we dont really
781                    // need to do anything. The pending install
782                    // will be processed later on.
783                    if (!mBound) {
784                        // If this is the only one pending we might
785                        // have to bind to the service again.
786                        if (!connectToService()) {
787                            Slog.e(TAG, "Failed to bind to media container service");
788                            params.serviceError();
789                            return;
790                        } else {
791                            // Once we bind to the service, the first
792                            // pending request will be processed.
793                            mPendingInstalls.add(idx, params);
794                        }
795                    } else {
796                        mPendingInstalls.add(idx, params);
797                        // Already bound to the service. Just make
798                        // sure we trigger off processing the first request.
799                        if (idx == 0) {
800                            mHandler.sendEmptyMessage(MCS_BOUND);
801                        }
802                    }
803                    break;
804                }
805                case MCS_BOUND: {
806                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
807                    if (msg.obj != null) {
808                        mContainerService = (IMediaContainerService) msg.obj;
809                    }
810                    if (mContainerService == null) {
811                        // Something seriously wrong. Bail out
812                        Slog.e(TAG, "Cannot bind to media container service");
813                        for (HandlerParams params : mPendingInstalls) {
814                            // Indicate service bind error
815                            params.serviceError();
816                        }
817                        mPendingInstalls.clear();
818                    } else if (mPendingInstalls.size() > 0) {
819                        HandlerParams params = mPendingInstalls.get(0);
820                        if (params != null) {
821                            if (params.startCopy()) {
822                                // We are done...  look for more work or to
823                                // go idle.
824                                if (DEBUG_SD_INSTALL) Log.i(TAG,
825                                        "Checking for more work or unbind...");
826                                // Delete pending install
827                                if (mPendingInstalls.size() > 0) {
828                                    mPendingInstalls.remove(0);
829                                }
830                                if (mPendingInstalls.size() == 0) {
831                                    if (mBound) {
832                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
833                                                "Posting delayed MCS_UNBIND");
834                                        removeMessages(MCS_UNBIND);
835                                        Message ubmsg = obtainMessage(MCS_UNBIND);
836                                        // Unbind after a little delay, to avoid
837                                        // continual thrashing.
838                                        sendMessageDelayed(ubmsg, 10000);
839                                    }
840                                } else {
841                                    // There are more pending requests in queue.
842                                    // Just post MCS_BOUND message to trigger processing
843                                    // of next pending install.
844                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                            "Posting MCS_BOUND for next work");
846                                    mHandler.sendEmptyMessage(MCS_BOUND);
847                                }
848                            }
849                        }
850                    } else {
851                        // Should never happen ideally.
852                        Slog.w(TAG, "Empty queue");
853                    }
854                    break;
855                }
856                case MCS_RECONNECT: {
857                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
858                    if (mPendingInstalls.size() > 0) {
859                        if (mBound) {
860                            disconnectService();
861                        }
862                        if (!connectToService()) {
863                            Slog.e(TAG, "Failed to bind to media container service");
864                            for (HandlerParams params : mPendingInstalls) {
865                                // Indicate service bind error
866                                params.serviceError();
867                            }
868                            mPendingInstalls.clear();
869                        }
870                    }
871                    break;
872                }
873                case MCS_UNBIND: {
874                    // If there is no actual work left, then time to unbind.
875                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
876
877                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
878                        if (mBound) {
879                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
880
881                            disconnectService();
882                        }
883                    } else if (mPendingInstalls.size() > 0) {
884                        // There are more pending requests in queue.
885                        // Just post MCS_BOUND message to trigger processing
886                        // of next pending install.
887                        mHandler.sendEmptyMessage(MCS_BOUND);
888                    }
889
890                    break;
891                }
892                case MCS_GIVE_UP: {
893                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
894                    mPendingInstalls.remove(0);
895                    break;
896                }
897                case SEND_PENDING_BROADCAST: {
898                    String packages[];
899                    ArrayList<String> components[];
900                    int size = 0;
901                    int uids[];
902                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
903                    synchronized (mPackages) {
904                        if (mPendingBroadcasts == null) {
905                            return;
906                        }
907                        size = mPendingBroadcasts.size();
908                        if (size <= 0) {
909                            // Nothing to be done. Just return
910                            return;
911                        }
912                        packages = new String[size];
913                        components = new ArrayList[size];
914                        uids = new int[size];
915                        int i = 0;  // filling out the above arrays
916
917                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
918                            int packageUserId = mPendingBroadcasts.userIdAt(n);
919                            Iterator<Map.Entry<String, ArrayList<String>>> it
920                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
921                                            .entrySet().iterator();
922                            while (it.hasNext() && i < size) {
923                                Map.Entry<String, ArrayList<String>> ent = it.next();
924                                packages[i] = ent.getKey();
925                                components[i] = ent.getValue();
926                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
927                                uids[i] = (ps != null)
928                                        ? UserHandle.getUid(packageUserId, ps.appId)
929                                        : -1;
930                                i++;
931                            }
932                        }
933                        size = i;
934                        mPendingBroadcasts.clear();
935                    }
936                    // Send broadcasts
937                    for (int i = 0; i < size; i++) {
938                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
939                    }
940                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
941                    break;
942                }
943                case START_CLEANING_PACKAGE: {
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
945                    final String packageName = (String)msg.obj;
946                    final int userId = msg.arg1;
947                    final boolean andCode = msg.arg2 != 0;
948                    synchronized (mPackages) {
949                        if (userId == UserHandle.USER_ALL) {
950                            int[] users = sUserManager.getUserIds();
951                            for (int user : users) {
952                                mSettings.addPackageToCleanLPw(
953                                        new PackageCleanItem(user, packageName, andCode));
954                            }
955                        } else {
956                            mSettings.addPackageToCleanLPw(
957                                    new PackageCleanItem(userId, packageName, andCode));
958                        }
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    startCleaningPackages();
962                } break;
963                case POST_INSTALL: {
964                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
965                    PostInstallData data = mRunningInstalls.get(msg.arg1);
966                    mRunningInstalls.delete(msg.arg1);
967                    boolean deleteOld = false;
968
969                    if (data != null) {
970                        InstallArgs args = data.args;
971                        PackageInstalledInfo res = data.res;
972
973                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
974                            res.removedInfo.sendBroadcast(false, true, false);
975                            Bundle extras = new Bundle(1);
976                            extras.putInt(Intent.EXTRA_UID, res.uid);
977                            // Determine the set of users who are adding this
978                            // package for the first time vs. those who are seeing
979                            // an update.
980                            int[] firstUsers;
981                            int[] updateUsers = new int[0];
982                            if (res.origUsers == null || res.origUsers.length == 0) {
983                                firstUsers = res.newUsers;
984                            } else {
985                                firstUsers = new int[0];
986                                for (int i=0; i<res.newUsers.length; i++) {
987                                    int user = res.newUsers[i];
988                                    boolean isNew = true;
989                                    for (int j=0; j<res.origUsers.length; j++) {
990                                        if (res.origUsers[j] == user) {
991                                            isNew = false;
992                                            break;
993                                        }
994                                    }
995                                    if (isNew) {
996                                        int[] newFirst = new int[firstUsers.length+1];
997                                        System.arraycopy(firstUsers, 0, newFirst, 0,
998                                                firstUsers.length);
999                                        newFirst[firstUsers.length] = user;
1000                                        firstUsers = newFirst;
1001                                    } else {
1002                                        int[] newUpdate = new int[updateUsers.length+1];
1003                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1004                                                updateUsers.length);
1005                                        newUpdate[updateUsers.length] = user;
1006                                        updateUsers = newUpdate;
1007                                    }
1008                                }
1009                            }
1010                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1011                                    res.pkg.applicationInfo.packageName,
1012                                    extras, null, null, firstUsers);
1013                            final boolean update = res.removedInfo.removedPackage != null;
1014                            if (update) {
1015                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1016                            }
1017                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1018                                    res.pkg.applicationInfo.packageName,
1019                                    extras, null, null, updateUsers);
1020                            if (update) {
1021                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1022                                        res.pkg.applicationInfo.packageName,
1023                                        extras, null, null, updateUsers);
1024                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1025                                        null, null,
1026                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1027
1028                                // treat asec-hosted packages like removable media on upgrade
1029                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1030                                    if (DEBUG_INSTALL) {
1031                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1032                                                + " is ASEC-hosted -> AVAILABLE");
1033                                    }
1034                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1035                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1036                                    pkgList.add(res.pkg.applicationInfo.packageName);
1037                                    sendResourcesChangedBroadcast(true, true,
1038                                            pkgList,uidArray, null);
1039                                }
1040                            }
1041                            if (res.removedInfo.args != null) {
1042                                // Remove the replaced package's older resources safely now
1043                                deleteOld = true;
1044                            }
1045
1046                            // Log current value of "unknown sources" setting
1047                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1048                                getUnknownSourcesSettings());
1049                        }
1050                        // Force a gc to clear up things
1051                        Runtime.getRuntime().gc();
1052                        // We delete after a gc for applications  on sdcard.
1053                        if (deleteOld) {
1054                            synchronized (mInstallLock) {
1055                                res.removedInfo.args.doPostDeleteLI(true);
1056                            }
1057                        }
1058                        if (args.observer != null) {
1059                            try {
1060                                Bundle extras = extrasForInstallResult(res);
1061                                args.observer.onPackageInstalled(res.name, res.returnCode,
1062                                        res.returnMsg, extras);
1063                            } catch (RemoteException e) {
1064                                Slog.i(TAG, "Observer no longer exists.");
1065                            }
1066                        }
1067                    } else {
1068                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1069                    }
1070                } break;
1071                case UPDATED_MEDIA_STATUS: {
1072                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1073                    boolean reportStatus = msg.arg1 == 1;
1074                    boolean doGc = msg.arg2 == 1;
1075                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1076                    if (doGc) {
1077                        // Force a gc to clear up stale containers.
1078                        Runtime.getRuntime().gc();
1079                    }
1080                    if (msg.obj != null) {
1081                        @SuppressWarnings("unchecked")
1082                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1083                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1084                        // Unload containers
1085                        unloadAllContainers(args);
1086                    }
1087                    if (reportStatus) {
1088                        try {
1089                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1090                            PackageHelper.getMountService().finishMediaUpdate();
1091                        } catch (RemoteException e) {
1092                            Log.e(TAG, "MountService not running?");
1093                        }
1094                    }
1095                } break;
1096                case WRITE_SETTINGS: {
1097                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098                    synchronized (mPackages) {
1099                        removeMessages(WRITE_SETTINGS);
1100                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1101                        mSettings.writeLPr();
1102                        mDirtyUsers.clear();
1103                    }
1104                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105                } break;
1106                case WRITE_PACKAGE_RESTRICTIONS: {
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1108                    synchronized (mPackages) {
1109                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1110                        for (int userId : mDirtyUsers) {
1111                            mSettings.writePackageRestrictionsLPr(userId);
1112                        }
1113                        mDirtyUsers.clear();
1114                    }
1115                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116                } break;
1117                case CHECK_PENDING_VERIFICATION: {
1118                    final int verificationId = msg.arg1;
1119                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1120
1121                    if ((state != null) && !state.timeoutExtended()) {
1122                        final InstallArgs args = state.getInstallArgs();
1123                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1124
1125                        Slog.i(TAG, "Verification timed out for " + originUri);
1126                        mPendingVerification.remove(verificationId);
1127
1128                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1129
1130                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1131                            Slog.i(TAG, "Continuing with installation of " + originUri);
1132                            state.setVerifierResponse(Binder.getCallingUid(),
1133                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1134                            broadcastPackageVerified(verificationId, originUri,
1135                                    PackageManager.VERIFICATION_ALLOW,
1136                                    state.getInstallArgs().getUser());
1137                            try {
1138                                ret = args.copyApk(mContainerService, true);
1139                            } catch (RemoteException e) {
1140                                Slog.e(TAG, "Could not contact the ContainerService");
1141                            }
1142                        } else {
1143                            broadcastPackageVerified(verificationId, originUri,
1144                                    PackageManager.VERIFICATION_REJECT,
1145                                    state.getInstallArgs().getUser());
1146                        }
1147
1148                        processPendingInstall(args, ret);
1149                        mHandler.sendEmptyMessage(MCS_UNBIND);
1150                    }
1151                    break;
1152                }
1153                case PACKAGE_VERIFIED: {
1154                    final int verificationId = msg.arg1;
1155
1156                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1157                    if (state == null) {
1158                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1159                        break;
1160                    }
1161
1162                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1163
1164                    state.setVerifierResponse(response.callerUid, response.code);
1165
1166                    if (state.isVerificationComplete()) {
1167                        mPendingVerification.remove(verificationId);
1168
1169                        final InstallArgs args = state.getInstallArgs();
1170                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1171
1172                        int ret;
1173                        if (state.isInstallAllowed()) {
1174                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1175                            broadcastPackageVerified(verificationId, originUri,
1176                                    response.code, state.getInstallArgs().getUser());
1177                            try {
1178                                ret = args.copyApk(mContainerService, true);
1179                            } catch (RemoteException e) {
1180                                Slog.e(TAG, "Could not contact the ContainerService");
1181                            }
1182                        } else {
1183                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1184                        }
1185
1186                        processPendingInstall(args, ret);
1187
1188                        mHandler.sendEmptyMessage(MCS_UNBIND);
1189                    }
1190
1191                    break;
1192                }
1193            }
1194        }
1195    }
1196
1197    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1198        Bundle extras = null;
1199        switch (res.returnCode) {
1200            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1201                extras = new Bundle();
1202                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1203                        res.origPermission);
1204                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1205                        res.origPackage);
1206                break;
1207            }
1208        }
1209        return extras;
1210    }
1211
1212    void scheduleWriteSettingsLocked() {
1213        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1214            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1215        }
1216    }
1217
1218    void scheduleWritePackageRestrictionsLocked(int userId) {
1219        if (!sUserManager.exists(userId)) return;
1220        mDirtyUsers.add(userId);
1221        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1222            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1223        }
1224    }
1225
1226    public static final PackageManagerService main(Context context, Installer installer,
1227            boolean factoryTest, boolean onlyCore) {
1228        PackageManagerService m = new PackageManagerService(context, installer,
1229                factoryTest, onlyCore);
1230        ServiceManager.addService("package", m);
1231        return m;
1232    }
1233
1234    static String[] splitString(String str, char sep) {
1235        int count = 1;
1236        int i = 0;
1237        while ((i=str.indexOf(sep, i)) >= 0) {
1238            count++;
1239            i++;
1240        }
1241
1242        String[] res = new String[count];
1243        i=0;
1244        count = 0;
1245        int lastI=0;
1246        while ((i=str.indexOf(sep, i)) >= 0) {
1247            res[count] = str.substring(lastI, i);
1248            count++;
1249            i++;
1250            lastI = i;
1251        }
1252        res[count] = str.substring(lastI, str.length());
1253        return res;
1254    }
1255
1256    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1257        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1258                Context.DISPLAY_SERVICE);
1259        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1260    }
1261
1262    public PackageManagerService(Context context, Installer installer,
1263            boolean factoryTest, boolean onlyCore) {
1264        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1265                SystemClock.uptimeMillis());
1266
1267        if (mSdkVersion <= 0) {
1268            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1269        }
1270
1271        mContext = context;
1272        mFactoryTest = factoryTest;
1273        mOnlyCore = onlyCore;
1274        mMetrics = new DisplayMetrics();
1275        mSettings = new Settings(context);
1276        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1277                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1278        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1279                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1280        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1281                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1282        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1283                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1284        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288
1289        String separateProcesses = SystemProperties.get("debug.separate_processes");
1290        if (separateProcesses != null && separateProcesses.length() > 0) {
1291            if ("*".equals(separateProcesses)) {
1292                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1293                mSeparateProcesses = null;
1294                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1295            } else {
1296                mDefParseFlags = 0;
1297                mSeparateProcesses = separateProcesses.split(",");
1298                Slog.w(TAG, "Running with debug.separate_processes: "
1299                        + separateProcesses);
1300            }
1301        } else {
1302            mDefParseFlags = 0;
1303            mSeparateProcesses = null;
1304        }
1305
1306        mInstaller = installer;
1307
1308        getDefaultDisplayMetrics(context, mMetrics);
1309
1310        SystemConfig systemConfig = SystemConfig.getInstance();
1311        mGlobalGids = systemConfig.getGlobalGids();
1312        mSystemPermissions = systemConfig.getSystemPermissions();
1313        mAvailableFeatures = systemConfig.getAvailableFeatures();
1314
1315        synchronized (mInstallLock) {
1316        // writer
1317        synchronized (mPackages) {
1318            mHandlerThread = new ServiceThread(TAG,
1319                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1320            mHandlerThread.start();
1321            mHandler = new PackageHandler(mHandlerThread.getLooper());
1322            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1323
1324            File dataDir = Environment.getDataDirectory();
1325            mAppDataDir = new File(dataDir, "data");
1326            mAppInstallDir = new File(dataDir, "app");
1327            mAppLib32InstallDir = new File(dataDir, "app-lib");
1328            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1329            mUserAppDataDir = new File(dataDir, "user");
1330            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1331
1332            sUserManager = new UserManagerService(context, this,
1333                    mInstallLock, mPackages);
1334
1335            // Propagate permission configuration in to package manager.
1336            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1337                    = systemConfig.getPermissions();
1338            for (int i=0; i<permConfig.size(); i++) {
1339                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1340                BasePermission bp = mSettings.mPermissions.get(perm.name);
1341                if (bp == null) {
1342                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1343                    mSettings.mPermissions.put(perm.name, bp);
1344                }
1345                if (perm.gids != null) {
1346                    bp.gids = appendInts(bp.gids, perm.gids);
1347                }
1348            }
1349
1350            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1351            for (int i=0; i<libConfig.size(); i++) {
1352                mSharedLibraries.put(libConfig.keyAt(i),
1353                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1354            }
1355
1356            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1357
1358            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1359                    mSdkVersion, mOnlyCore);
1360
1361            String customResolverActivity = Resources.getSystem().getString(
1362                    R.string.config_customResolverActivity);
1363            if (TextUtils.isEmpty(customResolverActivity)) {
1364                customResolverActivity = null;
1365            } else {
1366                mCustomResolverComponentName = ComponentName.unflattenFromString(
1367                        customResolverActivity);
1368            }
1369
1370            long startTime = SystemClock.uptimeMillis();
1371
1372            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1373                    startTime);
1374
1375            // Set flag to monitor and not change apk file paths when
1376            // scanning install directories.
1377            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1378
1379            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1380
1381            /**
1382             * Add everything in the in the boot class path to the
1383             * list of process files because dexopt will have been run
1384             * if necessary during zygote startup.
1385             */
1386            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1387            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1388
1389            if (bootClassPath != null) {
1390                String[] bootClassPathElements = splitString(bootClassPath, ':');
1391                for (String element : bootClassPathElements) {
1392                    alreadyDexOpted.add(element);
1393                }
1394            } else {
1395                Slog.w(TAG, "No BOOTCLASSPATH found!");
1396            }
1397
1398            if (systemServerClassPath != null) {
1399                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1400                for (String element : systemServerClassPathElements) {
1401                    alreadyDexOpted.add(element);
1402                }
1403            } else {
1404                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1405            }
1406
1407            boolean didDexOptLibraryOrTool = false;
1408
1409            final List<String> allInstructionSets = getAllInstructionSets();
1410            final String[] dexCodeInstructionSets =
1411                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1412
1413            /**
1414             * Ensure all external libraries have had dexopt run on them.
1415             */
1416            if (mSharedLibraries.size() > 0) {
1417                // NOTE: For now, we're compiling these system "shared libraries"
1418                // (and framework jars) into all available architectures. It's possible
1419                // to compile them only when we come across an app that uses them (there's
1420                // already logic for that in scanPackageLI) but that adds some complexity.
1421                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1422                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1423                        final String lib = libEntry.path;
1424                        if (lib == null) {
1425                            continue;
1426                        }
1427
1428                        try {
1429                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1430                                                                                 dexCodeInstructionSet,
1431                                                                                 false);
1432                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1433                                alreadyDexOpted.add(lib);
1434
1435                                // The list of "shared libraries" we have at this point is
1436                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1437                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1438                                } else {
1439                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1440                                }
1441                                didDexOptLibraryOrTool = true;
1442                            }
1443                        } catch (FileNotFoundException e) {
1444                            Slog.w(TAG, "Library not found: " + lib);
1445                        } catch (IOException e) {
1446                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1447                                    + e.getMessage());
1448                        }
1449                    }
1450                }
1451            }
1452
1453            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1454
1455            // Gross hack for now: we know this file doesn't contain any
1456            // code, so don't dexopt it to avoid the resulting log spew.
1457            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1458
1459            // Gross hack for now: we know this file is only part of
1460            // the boot class path for art, so don't dexopt it to
1461            // avoid the resulting log spew.
1462            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1463
1464            /**
1465             * And there are a number of commands implemented in Java, which
1466             * we currently need to do the dexopt on so that they can be
1467             * run from a non-root shell.
1468             */
1469            String[] frameworkFiles = frameworkDir.list();
1470            if (frameworkFiles != null) {
1471                // TODO: We could compile these only for the most preferred ABI. We should
1472                // first double check that the dex files for these commands are not referenced
1473                // by other system apps.
1474                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1475                    for (int i=0; i<frameworkFiles.length; i++) {
1476                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1477                        String path = libPath.getPath();
1478                        // Skip the file if we already did it.
1479                        if (alreadyDexOpted.contains(path)) {
1480                            continue;
1481                        }
1482                        // Skip the file if it is not a type we want to dexopt.
1483                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1484                            continue;
1485                        }
1486                        try {
1487                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1488                                                                                 dexCodeInstructionSet,
1489                                                                                 false);
1490                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1491                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1492                                didDexOptLibraryOrTool = true;
1493                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1494                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1495                                didDexOptLibraryOrTool = true;
1496                            }
1497                        } catch (FileNotFoundException e) {
1498                            Slog.w(TAG, "Jar not found: " + path);
1499                        } catch (IOException e) {
1500                            Slog.w(TAG, "Exception reading jar: " + path, e);
1501                        }
1502                    }
1503                }
1504            }
1505
1506            if (didDexOptLibraryOrTool) {
1507                // If we dexopted a library or tool, then something on the system has
1508                // changed. Consider this significant, and wipe away all other
1509                // existing dexopt files to ensure we don't leave any dangling around.
1510                //
1511                // TODO: This should be revisited because it isn't as good an indicator
1512                // as it used to be. It used to include the boot classpath but at some point
1513                // DexFile.isDexOptNeeded started returning false for the boot
1514                // class path files in all cases. It is very possible in a
1515                // small maintenance release update that the library and tool
1516                // jars may be unchanged but APK could be removed resulting in
1517                // unused dalvik-cache files.
1518                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1519                    mInstaller.pruneDexCache(dexCodeInstructionSet);
1520                }
1521
1522                // Additionally, delete all dex files from the root directory
1523                // since there shouldn't be any there anyway, unless we're upgrading
1524                // from an older OS version or a build that contained the "old" style
1525                // flat scheme.
1526                mInstaller.pruneDexCache(".");
1527            }
1528
1529            // Collect vendor overlay packages.
1530            // (Do this before scanning any apps.)
1531            // For security and version matching reason, only consider
1532            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1533            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1534            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1535                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1536
1537            // Find base frameworks (resource packages without code).
1538            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR
1540                    | PackageParser.PARSE_IS_PRIVILEGED,
1541                    scanMode | SCAN_NO_DEX, 0);
1542
1543            // Collected privileged system packages.
1544            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1545            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR
1547                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1548
1549            // Collect ordinary system packages.
1550            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1551            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1553
1554            // Collect all vendor packages.
1555            File vendorAppDir = new File("/vendor/app");
1556            try {
1557                vendorAppDir = vendorAppDir.getCanonicalFile();
1558            } catch (IOException e) {
1559                // failed to look up canonical path, continue with original one
1560            }
1561            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1562                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1563
1564            // Collect all OEM packages.
1565            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1566            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1567                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1568
1569            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1570            mInstaller.moveFiles();
1571
1572            // Prune any system packages that no longer exist.
1573            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1574            if (!mOnlyCore) {
1575                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1576                while (psit.hasNext()) {
1577                    PackageSetting ps = psit.next();
1578
1579                    /*
1580                     * If this is not a system app, it can't be a
1581                     * disable system app.
1582                     */
1583                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1584                        continue;
1585                    }
1586
1587                    /*
1588                     * If the package is scanned, it's not erased.
1589                     */
1590                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1591                    if (scannedPkg != null) {
1592                        /*
1593                         * If the system app is both scanned and in the
1594                         * disabled packages list, then it must have been
1595                         * added via OTA. Remove it from the currently
1596                         * scanned package so the previously user-installed
1597                         * application can be scanned.
1598                         */
1599                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1600                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1601                                    + "; removing system app");
1602                            removePackageLI(ps, true);
1603                        }
1604
1605                        continue;
1606                    }
1607
1608                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1609                        psit.remove();
1610                        String msg = "System package " + ps.name
1611                                + " no longer exists; wiping its data";
1612                        reportSettingsProblem(Log.WARN, msg);
1613                        removeDataDirsLI(ps.name);
1614                    } else {
1615                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1616                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1617                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1618                        }
1619                    }
1620                }
1621            }
1622
1623            //look for any incomplete package installations
1624            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1625            //clean up list
1626            for(int i = 0; i < deletePkgsList.size(); i++) {
1627                //clean up here
1628                cleanupInstallFailedPackage(deletePkgsList.get(i));
1629            }
1630            //delete tmp files
1631            deleteTempPackageFiles();
1632
1633            // Remove any shared userIDs that have no associated packages
1634            mSettings.pruneSharedUsersLPw();
1635
1636            if (!mOnlyCore) {
1637                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1638                        SystemClock.uptimeMillis());
1639                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1640
1641                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1642                        scanMode, 0);
1643
1644                /**
1645                 * Remove disable package settings for any updated system
1646                 * apps that were removed via an OTA. If they're not a
1647                 * previously-updated app, remove them completely.
1648                 * Otherwise, just revoke their system-level permissions.
1649                 */
1650                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1651                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1652                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1653
1654                    String msg;
1655                    if (deletedPkg == null) {
1656                        msg = "Updated system package " + deletedAppName
1657                                + " no longer exists; wiping its data";
1658                        removeDataDirsLI(deletedAppName);
1659                    } else {
1660                        msg = "Updated system app + " + deletedAppName
1661                                + " no longer present; removing system privileges for "
1662                                + deletedAppName;
1663
1664                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1665
1666                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1667                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1668                    }
1669                    reportSettingsProblem(Log.WARN, msg);
1670                }
1671            }
1672
1673            // Now that we know all of the shared libraries, update all clients to have
1674            // the correct library paths.
1675            updateAllSharedLibrariesLPw();
1676
1677            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1678                // NOTE: We ignore potential failures here during a system scan (like
1679                // the rest of the commands above) because there's precious little we
1680                // can do about it. A settings error is reported, though.
1681                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1682                        false /* force dexopt */, false /* defer dexopt */);
1683            }
1684
1685            // Now that we know all the packages we are keeping,
1686            // read and update their last usage times.
1687            mPackageUsage.readLP();
1688
1689            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1690                    SystemClock.uptimeMillis());
1691            Slog.i(TAG, "Time to scan packages: "
1692                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1693                    + " seconds");
1694
1695            // If the platform SDK has changed since the last time we booted,
1696            // we need to re-grant app permission to catch any new ones that
1697            // appear.  This is really a hack, and means that apps can in some
1698            // cases get permissions that the user didn't initially explicitly
1699            // allow...  it would be nice to have some better way to handle
1700            // this situation.
1701            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1702                    != mSdkVersion;
1703            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1704                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1705                    + "; regranting permissions for internal storage");
1706            mSettings.mInternalSdkPlatform = mSdkVersion;
1707
1708            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1709                    | (regrantPermissions
1710                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1711                            : 0));
1712
1713            // If this is the first boot, and it is a normal boot, then
1714            // we need to initialize the default preferred apps.
1715            if (!mRestoredSettings && !onlyCore) {
1716                mSettings.readDefaultPreferredAppsLPw(this, 0);
1717            }
1718
1719            // If this is first boot after an OTA, and a normal boot, then
1720            // we need to clear code cache directories.
1721            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1722                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1723                for (String pkgName : mSettings.mPackages.keySet()) {
1724                    deleteCodeCacheDirsLI(pkgName);
1725                }
1726                mSettings.mFingerprint = Build.FINGERPRINT;
1727            }
1728
1729            // All the changes are done during package scanning.
1730            mSettings.updateInternalDatabaseVersion();
1731
1732            // can downgrade to reader
1733            mSettings.writeLPr();
1734
1735            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1736                    SystemClock.uptimeMillis());
1737
1738
1739            mRequiredVerifierPackage = getRequiredVerifierLPr();
1740        } // synchronized (mPackages)
1741        } // synchronized (mInstallLock)
1742
1743        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1744
1745        // Now after opening every single application zip, make sure they
1746        // are all flushed.  Not really needed, but keeps things nice and
1747        // tidy.
1748        Runtime.getRuntime().gc();
1749    }
1750
1751    @Override
1752    public boolean isFirstBoot() {
1753        return !mRestoredSettings;
1754    }
1755
1756    @Override
1757    public boolean isOnlyCoreApps() {
1758        return mOnlyCore;
1759    }
1760
1761    private String getRequiredVerifierLPr() {
1762        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1763        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1764                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1765
1766        String requiredVerifier = null;
1767
1768        final int N = receivers.size();
1769        for (int i = 0; i < N; i++) {
1770            final ResolveInfo info = receivers.get(i);
1771
1772            if (info.activityInfo == null) {
1773                continue;
1774            }
1775
1776            final String packageName = info.activityInfo.packageName;
1777
1778            final PackageSetting ps = mSettings.mPackages.get(packageName);
1779            if (ps == null) {
1780                continue;
1781            }
1782
1783            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1784            if (!gp.grantedPermissions
1785                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1786                continue;
1787            }
1788
1789            if (requiredVerifier != null) {
1790                throw new RuntimeException("There can be only one required verifier");
1791            }
1792
1793            requiredVerifier = packageName;
1794        }
1795
1796        return requiredVerifier;
1797    }
1798
1799    @Override
1800    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1801            throws RemoteException {
1802        try {
1803            return super.onTransact(code, data, reply, flags);
1804        } catch (RuntimeException e) {
1805            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1806                Slog.wtf(TAG, "Package Manager Crash", e);
1807            }
1808            throw e;
1809        }
1810    }
1811
1812    void cleanupInstallFailedPackage(PackageSetting ps) {
1813        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1814        removeDataDirsLI(ps.name);
1815
1816        // TODO: try cleaning up codePath directory contents first, since it
1817        // might be a cluster
1818
1819        if (ps.codePath != null) {
1820            if (!ps.codePath.delete()) {
1821                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1822            }
1823        }
1824        if (ps.resourcePath != null) {
1825            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1826                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1827            }
1828        }
1829        mSettings.removePackageLPw(ps.name);
1830    }
1831
1832    static int[] appendInts(int[] cur, int[] add) {
1833        if (add == null) return cur;
1834        if (cur == null) return add;
1835        final int N = add.length;
1836        for (int i=0; i<N; i++) {
1837            cur = appendInt(cur, add[i]);
1838        }
1839        return cur;
1840    }
1841
1842    static int[] removeInts(int[] cur, int[] rem) {
1843        if (rem == null) return cur;
1844        if (cur == null) return cur;
1845        final int N = rem.length;
1846        for (int i=0; i<N; i++) {
1847            cur = removeInt(cur, rem[i]);
1848        }
1849        return cur;
1850    }
1851
1852    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1853        if (!sUserManager.exists(userId)) return null;
1854        final PackageSetting ps = (PackageSetting) p.mExtras;
1855        if (ps == null) {
1856            return null;
1857        }
1858        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1859        final PackageUserState state = ps.readUserState(userId);
1860        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1861                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1862                state, userId);
1863    }
1864
1865    @Override
1866    public boolean isPackageAvailable(String packageName, int userId) {
1867        if (!sUserManager.exists(userId)) return false;
1868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1869        synchronized (mPackages) {
1870            PackageParser.Package p = mPackages.get(packageName);
1871            if (p != null) {
1872                final PackageSetting ps = (PackageSetting) p.mExtras;
1873                if (ps != null) {
1874                    final PackageUserState state = ps.readUserState(userId);
1875                    if (state != null) {
1876                        return PackageParser.isAvailable(state);
1877                    }
1878                }
1879            }
1880        }
1881        return false;
1882    }
1883
1884    @Override
1885    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1886        if (!sUserManager.exists(userId)) return null;
1887        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1888        // reader
1889        synchronized (mPackages) {
1890            PackageParser.Package p = mPackages.get(packageName);
1891            if (DEBUG_PACKAGE_INFO)
1892                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1893            if (p != null) {
1894                return generatePackageInfo(p, flags, userId);
1895            }
1896            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1897                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1898            }
1899        }
1900        return null;
1901    }
1902
1903    @Override
1904    public String[] currentToCanonicalPackageNames(String[] names) {
1905        String[] out = new String[names.length];
1906        // reader
1907        synchronized (mPackages) {
1908            for (int i=names.length-1; i>=0; i--) {
1909                PackageSetting ps = mSettings.mPackages.get(names[i]);
1910                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1911            }
1912        }
1913        return out;
1914    }
1915
1916    @Override
1917    public String[] canonicalToCurrentPackageNames(String[] names) {
1918        String[] out = new String[names.length];
1919        // reader
1920        synchronized (mPackages) {
1921            for (int i=names.length-1; i>=0; i--) {
1922                String cur = mSettings.mRenamedPackages.get(names[i]);
1923                out[i] = cur != null ? cur : names[i];
1924            }
1925        }
1926        return out;
1927    }
1928
1929    @Override
1930    public int getPackageUid(String packageName, int userId) {
1931        if (!sUserManager.exists(userId)) return -1;
1932        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1933        // reader
1934        synchronized (mPackages) {
1935            PackageParser.Package p = mPackages.get(packageName);
1936            if(p != null) {
1937                return UserHandle.getUid(userId, p.applicationInfo.uid);
1938            }
1939            PackageSetting ps = mSettings.mPackages.get(packageName);
1940            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1941                return -1;
1942            }
1943            p = ps.pkg;
1944            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1945        }
1946    }
1947
1948    @Override
1949    public int[] getPackageGids(String packageName) {
1950        // reader
1951        synchronized (mPackages) {
1952            PackageParser.Package p = mPackages.get(packageName);
1953            if (DEBUG_PACKAGE_INFO)
1954                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1955            if (p != null) {
1956                final PackageSetting ps = (PackageSetting)p.mExtras;
1957                return ps.getGids();
1958            }
1959        }
1960        // stupid thing to indicate an error.
1961        return new int[0];
1962    }
1963
1964    static final PermissionInfo generatePermissionInfo(
1965            BasePermission bp, int flags) {
1966        if (bp.perm != null) {
1967            return PackageParser.generatePermissionInfo(bp.perm, flags);
1968        }
1969        PermissionInfo pi = new PermissionInfo();
1970        pi.name = bp.name;
1971        pi.packageName = bp.sourcePackage;
1972        pi.nonLocalizedLabel = bp.name;
1973        pi.protectionLevel = bp.protectionLevel;
1974        return pi;
1975    }
1976
1977    @Override
1978    public PermissionInfo getPermissionInfo(String name, int flags) {
1979        // reader
1980        synchronized (mPackages) {
1981            final BasePermission p = mSettings.mPermissions.get(name);
1982            if (p != null) {
1983                return generatePermissionInfo(p, flags);
1984            }
1985            return null;
1986        }
1987    }
1988
1989    @Override
1990    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1991        // reader
1992        synchronized (mPackages) {
1993            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1994            for (BasePermission p : mSettings.mPermissions.values()) {
1995                if (group == null) {
1996                    if (p.perm == null || p.perm.info.group == null) {
1997                        out.add(generatePermissionInfo(p, flags));
1998                    }
1999                } else {
2000                    if (p.perm != null && group.equals(p.perm.info.group)) {
2001                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2002                    }
2003                }
2004            }
2005
2006            if (out.size() > 0) {
2007                return out;
2008            }
2009            return mPermissionGroups.containsKey(group) ? out : null;
2010        }
2011    }
2012
2013    @Override
2014    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2015        // reader
2016        synchronized (mPackages) {
2017            return PackageParser.generatePermissionGroupInfo(
2018                    mPermissionGroups.get(name), flags);
2019        }
2020    }
2021
2022    @Override
2023    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2024        // reader
2025        synchronized (mPackages) {
2026            final int N = mPermissionGroups.size();
2027            ArrayList<PermissionGroupInfo> out
2028                    = new ArrayList<PermissionGroupInfo>(N);
2029            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2030                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2031            }
2032            return out;
2033        }
2034    }
2035
2036    private ApplicationInfo generateApplicationInfoFromSettingsLPw(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            if (ps.pkg == null) {
2042                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2043                        flags, userId);
2044                if (pInfo != null) {
2045                    return pInfo.applicationInfo;
2046                }
2047                return null;
2048            }
2049            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2050                    ps.readUserState(userId), userId);
2051        }
2052        return null;
2053    }
2054
2055    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2056            int userId) {
2057        if (!sUserManager.exists(userId)) return null;
2058        PackageSetting ps = mSettings.mPackages.get(packageName);
2059        if (ps != null) {
2060            PackageParser.Package pkg = ps.pkg;
2061            if (pkg == null) {
2062                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2063                    return null;
2064                }
2065                // Only data remains, so we aren't worried about code paths
2066                pkg = new PackageParser.Package(packageName);
2067                pkg.applicationInfo.packageName = packageName;
2068                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2069                pkg.applicationInfo.dataDir =
2070                        getDataPathForPackage(packageName, 0).getPath();
2071                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2072                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2073            }
2074            return generatePackageInfo(pkg, flags, userId);
2075        }
2076        return null;
2077    }
2078
2079    @Override
2080    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2081        if (!sUserManager.exists(userId)) return null;
2082        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2083        // writer
2084        synchronized (mPackages) {
2085            PackageParser.Package p = mPackages.get(packageName);
2086            if (DEBUG_PACKAGE_INFO) Log.v(
2087                    TAG, "getApplicationInfo " + packageName
2088                    + ": " + p);
2089            if (p != null) {
2090                PackageSetting ps = mSettings.mPackages.get(packageName);
2091                if (ps == null) return null;
2092                // Note: isEnabledLP() does not apply here - always return info
2093                return PackageParser.generateApplicationInfo(
2094                        p, flags, ps.readUserState(userId), userId);
2095            }
2096            if ("android".equals(packageName)||"system".equals(packageName)) {
2097                return mAndroidApplication;
2098            }
2099            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2100                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2101            }
2102        }
2103        return null;
2104    }
2105
2106
2107    @Override
2108    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2109        mContext.enforceCallingOrSelfPermission(
2110                android.Manifest.permission.CLEAR_APP_CACHE, null);
2111        // Queue up an async operation since clearing cache may take a little while.
2112        mHandler.post(new Runnable() {
2113            public void run() {
2114                mHandler.removeCallbacks(this);
2115                int retCode = -1;
2116                synchronized (mInstallLock) {
2117                    retCode = mInstaller.freeCache(freeStorageSize);
2118                    if (retCode < 0) {
2119                        Slog.w(TAG, "Couldn't clear application caches");
2120                    }
2121                }
2122                if (observer != null) {
2123                    try {
2124                        observer.onRemoveCompleted(null, (retCode >= 0));
2125                    } catch (RemoteException e) {
2126                        Slog.w(TAG, "RemoveException when invoking call back");
2127                    }
2128                }
2129            }
2130        });
2131    }
2132
2133    @Override
2134    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2135        mContext.enforceCallingOrSelfPermission(
2136                android.Manifest.permission.CLEAR_APP_CACHE, null);
2137        // Queue up an async operation since clearing cache may take a little while.
2138        mHandler.post(new Runnable() {
2139            public void run() {
2140                mHandler.removeCallbacks(this);
2141                int retCode = -1;
2142                synchronized (mInstallLock) {
2143                    retCode = mInstaller.freeCache(freeStorageSize);
2144                    if (retCode < 0) {
2145                        Slog.w(TAG, "Couldn't clear application caches");
2146                    }
2147                }
2148                if(pi != null) {
2149                    try {
2150                        // Callback via pending intent
2151                        int code = (retCode >= 0) ? 1 : 0;
2152                        pi.sendIntent(null, code, null,
2153                                null, null);
2154                    } catch (SendIntentException e1) {
2155                        Slog.i(TAG, "Failed to send pending intent");
2156                    }
2157                }
2158            }
2159        });
2160    }
2161
2162    void freeStorage(long freeStorageSize) throws IOException {
2163        synchronized (mInstallLock) {
2164            if (mInstaller.freeCache(freeStorageSize) < 0) {
2165                throw new IOException("Failed to free enough space");
2166            }
2167        }
2168    }
2169
2170    @Override
2171    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2172        if (!sUserManager.exists(userId)) return null;
2173        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2174        synchronized (mPackages) {
2175            PackageParser.Activity a = mActivities.mActivities.get(component);
2176
2177            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2178            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2179                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2180                if (ps == null) return null;
2181                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2182                        userId);
2183            }
2184            if (mResolveComponentName.equals(component)) {
2185                return mResolveActivity;
2186            }
2187        }
2188        return null;
2189    }
2190
2191    @Override
2192    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2193            String resolvedType) {
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mActivities.mActivities.get(component);
2196            if (a == null) {
2197                return false;
2198            }
2199            for (int i=0; i<a.intents.size(); i++) {
2200                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2201                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2202                    return true;
2203                }
2204            }
2205            return false;
2206        }
2207    }
2208
2209    @Override
2210    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2211        if (!sUserManager.exists(userId)) return null;
2212        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2213        synchronized (mPackages) {
2214            PackageParser.Activity a = mReceivers.mActivities.get(component);
2215            if (DEBUG_PACKAGE_INFO) Log.v(
2216                TAG, "getReceiverInfo " + component + ": " + a);
2217            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2218                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2219                if (ps == null) return null;
2220                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2221                        userId);
2222            }
2223        }
2224        return null;
2225    }
2226
2227    @Override
2228    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2229        if (!sUserManager.exists(userId)) return null;
2230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2231        synchronized (mPackages) {
2232            PackageParser.Service s = mServices.mServices.get(component);
2233            if (DEBUG_PACKAGE_INFO) Log.v(
2234                TAG, "getServiceInfo " + component + ": " + s);
2235            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2236                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2237                if (ps == null) return null;
2238                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2239                        userId);
2240            }
2241        }
2242        return null;
2243    }
2244
2245    @Override
2246    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2247        if (!sUserManager.exists(userId)) return null;
2248        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2249        synchronized (mPackages) {
2250            PackageParser.Provider p = mProviders.mProviders.get(component);
2251            if (DEBUG_PACKAGE_INFO) Log.v(
2252                TAG, "getProviderInfo " + component + ": " + p);
2253            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2254                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2255                if (ps == null) return null;
2256                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2257                        userId);
2258            }
2259        }
2260        return null;
2261    }
2262
2263    @Override
2264    public String[] getSystemSharedLibraryNames() {
2265        Set<String> libSet;
2266        synchronized (mPackages) {
2267            libSet = mSharedLibraries.keySet();
2268            int size = libSet.size();
2269            if (size > 0) {
2270                String[] libs = new String[size];
2271                libSet.toArray(libs);
2272                return libs;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public FeatureInfo[] getSystemAvailableFeatures() {
2280        Collection<FeatureInfo> featSet;
2281        synchronized (mPackages) {
2282            featSet = mAvailableFeatures.values();
2283            int size = featSet.size();
2284            if (size > 0) {
2285                FeatureInfo[] features = new FeatureInfo[size+1];
2286                featSet.toArray(features);
2287                FeatureInfo fi = new FeatureInfo();
2288                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2289                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2290                features[size] = fi;
2291                return features;
2292            }
2293        }
2294        return null;
2295    }
2296
2297    @Override
2298    public boolean hasSystemFeature(String name) {
2299        synchronized (mPackages) {
2300            return mAvailableFeatures.containsKey(name);
2301        }
2302    }
2303
2304    private void checkValidCaller(int uid, int userId) {
2305        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2306            return;
2307
2308        throw new SecurityException("Caller uid=" + uid
2309                + " is not privileged to communicate with user=" + userId);
2310    }
2311
2312    @Override
2313    public int checkPermission(String permName, String pkgName) {
2314        synchronized (mPackages) {
2315            PackageParser.Package p = mPackages.get(pkgName);
2316            if (p != null && p.mExtras != null) {
2317                PackageSetting ps = (PackageSetting)p.mExtras;
2318                if (ps.sharedUser != null) {
2319                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2320                        return PackageManager.PERMISSION_GRANTED;
2321                    }
2322                } else if (ps.grantedPermissions.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    @Override
2331    public int checkUidPermission(String permName, int uid) {
2332        synchronized (mPackages) {
2333            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2334            if (obj != null) {
2335                GrantedPermissions gp = (GrantedPermissions)obj;
2336                if (gp.grantedPermissions.contains(permName)) {
2337                    return PackageManager.PERMISSION_GRANTED;
2338                }
2339            } else {
2340                HashSet<String> perms = mSystemPermissions.get(uid);
2341                if (perms != null && perms.contains(permName)) {
2342                    return PackageManager.PERMISSION_GRANTED;
2343                }
2344            }
2345        }
2346        return PackageManager.PERMISSION_DENIED;
2347    }
2348
2349    /**
2350     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2351     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2352     * @param message the message to log on security exception
2353     */
2354    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2355            String message) {
2356        if (userId < 0) {
2357            throw new IllegalArgumentException("Invalid userId " + userId);
2358        }
2359        if (userId == UserHandle.getUserId(callingUid)) return;
2360        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2361            if (requireFullPermission) {
2362                mContext.enforceCallingOrSelfPermission(
2363                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2364            } else {
2365                try {
2366                    mContext.enforceCallingOrSelfPermission(
2367                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2368                } catch (SecurityException se) {
2369                    mContext.enforceCallingOrSelfPermission(
2370                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2371                }
2372            }
2373        }
2374    }
2375
2376    private BasePermission findPermissionTreeLP(String permName) {
2377        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2378            if (permName.startsWith(bp.name) &&
2379                    permName.length() > bp.name.length() &&
2380                    permName.charAt(bp.name.length()) == '.') {
2381                return bp;
2382            }
2383        }
2384        return null;
2385    }
2386
2387    private BasePermission checkPermissionTreeLP(String permName) {
2388        if (permName != null) {
2389            BasePermission bp = findPermissionTreeLP(permName);
2390            if (bp != null) {
2391                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2392                    return bp;
2393                }
2394                throw new SecurityException("Calling uid "
2395                        + Binder.getCallingUid()
2396                        + " is not allowed to add to permission tree "
2397                        + bp.name + " owned by uid " + bp.uid);
2398            }
2399        }
2400        throw new SecurityException("No permission tree found for " + permName);
2401    }
2402
2403    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2404        if (s1 == null) {
2405            return s2 == null;
2406        }
2407        if (s2 == null) {
2408            return false;
2409        }
2410        if (s1.getClass() != s2.getClass()) {
2411            return false;
2412        }
2413        return s1.equals(s2);
2414    }
2415
2416    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2417        if (pi1.icon != pi2.icon) return false;
2418        if (pi1.logo != pi2.logo) return false;
2419        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2420        if (!compareStrings(pi1.name, pi2.name)) return false;
2421        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2422        // We'll take care of setting this one.
2423        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2424        // These are not currently stored in settings.
2425        //if (!compareStrings(pi1.group, pi2.group)) return false;
2426        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2427        //if (pi1.labelRes != pi2.labelRes) return false;
2428        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2429        return true;
2430    }
2431
2432    int permissionInfoFootprint(PermissionInfo info) {
2433        int size = info.name.length();
2434        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2435        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2436        return size;
2437    }
2438
2439    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2440        int size = 0;
2441        for (BasePermission perm : mSettings.mPermissions.values()) {
2442            if (perm.uid == tree.uid) {
2443                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2444            }
2445        }
2446        return size;
2447    }
2448
2449    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2450        // We calculate the max size of permissions defined by this uid and throw
2451        // if that plus the size of 'info' would exceed our stated maximum.
2452        if (tree.uid != Process.SYSTEM_UID) {
2453            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2454            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2455                throw new SecurityException("Permission tree size cap exceeded");
2456            }
2457        }
2458    }
2459
2460    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2461        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2462            throw new SecurityException("Label must be specified in permission");
2463        }
2464        BasePermission tree = checkPermissionTreeLP(info.name);
2465        BasePermission bp = mSettings.mPermissions.get(info.name);
2466        boolean added = bp == null;
2467        boolean changed = true;
2468        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2469        if (added) {
2470            enforcePermissionCapLocked(info, tree);
2471            bp = new BasePermission(info.name, tree.sourcePackage,
2472                    BasePermission.TYPE_DYNAMIC);
2473        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2474            throw new SecurityException(
2475                    "Not allowed to modify non-dynamic permission "
2476                    + info.name);
2477        } else {
2478            if (bp.protectionLevel == fixedLevel
2479                    && bp.perm.owner.equals(tree.perm.owner)
2480                    && bp.uid == tree.uid
2481                    && comparePermissionInfos(bp.perm.info, info)) {
2482                changed = false;
2483            }
2484        }
2485        bp.protectionLevel = fixedLevel;
2486        info = new PermissionInfo(info);
2487        info.protectionLevel = fixedLevel;
2488        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2489        bp.perm.info.packageName = tree.perm.info.packageName;
2490        bp.uid = tree.uid;
2491        if (added) {
2492            mSettings.mPermissions.put(info.name, bp);
2493        }
2494        if (changed) {
2495            if (!async) {
2496                mSettings.writeLPr();
2497            } else {
2498                scheduleWriteSettingsLocked();
2499            }
2500        }
2501        return added;
2502    }
2503
2504    @Override
2505    public boolean addPermission(PermissionInfo info) {
2506        synchronized (mPackages) {
2507            return addPermissionLocked(info, false);
2508        }
2509    }
2510
2511    @Override
2512    public boolean addPermissionAsync(PermissionInfo info) {
2513        synchronized (mPackages) {
2514            return addPermissionLocked(info, true);
2515        }
2516    }
2517
2518    @Override
2519    public void removePermission(String name) {
2520        synchronized (mPackages) {
2521            checkPermissionTreeLP(name);
2522            BasePermission bp = mSettings.mPermissions.get(name);
2523            if (bp != null) {
2524                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2525                    throw new SecurityException(
2526                            "Not allowed to modify non-dynamic permission "
2527                            + name);
2528                }
2529                mSettings.mPermissions.remove(name);
2530                mSettings.writeLPr();
2531            }
2532        }
2533    }
2534
2535    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2536        int index = pkg.requestedPermissions.indexOf(bp.name);
2537        if (index == -1) {
2538            throw new SecurityException("Package " + pkg.packageName
2539                    + " has not requested permission " + bp.name);
2540        }
2541        boolean isNormal =
2542                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2543                        == PermissionInfo.PROTECTION_NORMAL);
2544        boolean isDangerous =
2545                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2546                        == PermissionInfo.PROTECTION_DANGEROUS);
2547        boolean isDevelopment =
2548                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2549
2550        if (!isNormal && !isDangerous && !isDevelopment) {
2551            throw new SecurityException("Permission " + bp.name
2552                    + " is not a changeable permission type");
2553        }
2554
2555        if (isNormal || isDangerous) {
2556            if (pkg.requestedPermissionsRequired.get(index)) {
2557                throw new SecurityException("Can't change " + bp.name
2558                        + ". It is required by the application");
2559            }
2560        }
2561    }
2562
2563    @Override
2564    public void grantPermission(String packageName, String permissionName) {
2565        mContext.enforceCallingOrSelfPermission(
2566                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2567        synchronized (mPackages) {
2568            final PackageParser.Package pkg = mPackages.get(packageName);
2569            if (pkg == null) {
2570                throw new IllegalArgumentException("Unknown package: " + packageName);
2571            }
2572            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2573            if (bp == null) {
2574                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2575            }
2576
2577            checkGrantRevokePermissions(pkg, bp);
2578
2579            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2580            if (ps == null) {
2581                return;
2582            }
2583            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2584            if (gp.grantedPermissions.add(permissionName)) {
2585                if (ps.haveGids) {
2586                    gp.gids = appendInts(gp.gids, bp.gids);
2587                }
2588                mSettings.writeLPr();
2589            }
2590        }
2591    }
2592
2593    @Override
2594    public void revokePermission(String packageName, String permissionName) {
2595        int changedAppId = -1;
2596
2597        synchronized (mPackages) {
2598            final PackageParser.Package pkg = mPackages.get(packageName);
2599            if (pkg == null) {
2600                throw new IllegalArgumentException("Unknown package: " + packageName);
2601            }
2602            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2603                mContext.enforceCallingOrSelfPermission(
2604                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2605            }
2606            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2607            if (bp == null) {
2608                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2609            }
2610
2611            checkGrantRevokePermissions(pkg, bp);
2612
2613            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2614            if (ps == null) {
2615                return;
2616            }
2617            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2618            if (gp.grantedPermissions.remove(permissionName)) {
2619                gp.grantedPermissions.remove(permissionName);
2620                if (ps.haveGids) {
2621                    gp.gids = removeInts(gp.gids, bp.gids);
2622                }
2623                mSettings.writeLPr();
2624                changedAppId = ps.appId;
2625            }
2626        }
2627
2628        if (changedAppId >= 0) {
2629            // We changed the perm on someone, kill its processes.
2630            IActivityManager am = ActivityManagerNative.getDefault();
2631            if (am != null) {
2632                final int callingUserId = UserHandle.getCallingUserId();
2633                final long ident = Binder.clearCallingIdentity();
2634                try {
2635                    //XXX we should only revoke for the calling user's app permissions,
2636                    // but for now we impact all users.
2637                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2638                    //        "revoke " + permissionName);
2639                    int[] users = sUserManager.getUserIds();
2640                    for (int user : users) {
2641                        am.killUid(UserHandle.getUid(user, changedAppId),
2642                                "revoke " + permissionName);
2643                    }
2644                } catch (RemoteException e) {
2645                } finally {
2646                    Binder.restoreCallingIdentity(ident);
2647                }
2648            }
2649        }
2650    }
2651
2652    @Override
2653    public boolean isProtectedBroadcast(String actionName) {
2654        synchronized (mPackages) {
2655            return mProtectedBroadcasts.contains(actionName);
2656        }
2657    }
2658
2659    @Override
2660    public int checkSignatures(String pkg1, String pkg2) {
2661        synchronized (mPackages) {
2662            final PackageParser.Package p1 = mPackages.get(pkg1);
2663            final PackageParser.Package p2 = mPackages.get(pkg2);
2664            if (p1 == null || p1.mExtras == null
2665                    || p2 == null || p2.mExtras == null) {
2666                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2667            }
2668            return compareSignatures(p1.mSignatures, p2.mSignatures);
2669        }
2670    }
2671
2672    @Override
2673    public int checkUidSignatures(int uid1, int uid2) {
2674        // Map to base uids.
2675        uid1 = UserHandle.getAppId(uid1);
2676        uid2 = UserHandle.getAppId(uid2);
2677        // reader
2678        synchronized (mPackages) {
2679            Signature[] s1;
2680            Signature[] s2;
2681            Object obj = mSettings.getUserIdLPr(uid1);
2682            if (obj != null) {
2683                if (obj instanceof SharedUserSetting) {
2684                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2685                } else if (obj instanceof PackageSetting) {
2686                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2687                } else {
2688                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2689                }
2690            } else {
2691                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2692            }
2693            obj = mSettings.getUserIdLPr(uid2);
2694            if (obj != null) {
2695                if (obj instanceof SharedUserSetting) {
2696                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2697                } else if (obj instanceof PackageSetting) {
2698                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2699                } else {
2700                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2701                }
2702            } else {
2703                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2704            }
2705            return compareSignatures(s1, s2);
2706        }
2707    }
2708
2709    /**
2710     * Compares two sets of signatures. Returns:
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2719     * <br />
2720     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2721     */
2722    static int compareSignatures(Signature[] s1, Signature[] s2) {
2723        if (s1 == null) {
2724            return s2 == null
2725                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2726                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2727        }
2728
2729        if (s2 == null) {
2730            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2731        }
2732
2733        if (s1.length != s2.length) {
2734            return PackageManager.SIGNATURE_NO_MATCH;
2735        }
2736
2737        // Since both signature sets are of size 1, we can compare without HashSets.
2738        if (s1.length == 1) {
2739            return s1[0].equals(s2[0]) ?
2740                    PackageManager.SIGNATURE_MATCH :
2741                    PackageManager.SIGNATURE_NO_MATCH;
2742        }
2743
2744        HashSet<Signature> set1 = new HashSet<Signature>();
2745        for (Signature sig : s1) {
2746            set1.add(sig);
2747        }
2748        HashSet<Signature> set2 = new HashSet<Signature>();
2749        for (Signature sig : s2) {
2750            set2.add(sig);
2751        }
2752        // Make sure s2 contains all signatures in s1.
2753        if (set1.equals(set2)) {
2754            return PackageManager.SIGNATURE_MATCH;
2755        }
2756        return PackageManager.SIGNATURE_NO_MATCH;
2757    }
2758
2759    /**
2760     * If the database version for this type of package (internal storage or
2761     * external storage) is less than the version where package signatures
2762     * were updated, return true.
2763     */
2764    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2765        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2766                DatabaseVersion.SIGNATURE_END_ENTITY))
2767                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2768                        DatabaseVersion.SIGNATURE_END_ENTITY));
2769    }
2770
2771    /**
2772     * Used for backward compatibility to make sure any packages with
2773     * certificate chains get upgraded to the new style. {@code existingSigs}
2774     * will be in the old format (since they were stored on disk from before the
2775     * system upgrade) and {@code scannedSigs} will be in the newer format.
2776     */
2777    private int compareSignaturesCompat(PackageSignatures existingSigs,
2778            PackageParser.Package scannedPkg) {
2779        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2780            return PackageManager.SIGNATURE_NO_MATCH;
2781        }
2782
2783        HashSet<Signature> existingSet = new HashSet<Signature>();
2784        for (Signature sig : existingSigs.mSignatures) {
2785            existingSet.add(sig);
2786        }
2787        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2788        for (Signature sig : scannedPkg.mSignatures) {
2789            try {
2790                Signature[] chainSignatures = sig.getChainSignatures();
2791                for (Signature chainSig : chainSignatures) {
2792                    scannedCompatSet.add(chainSig);
2793                }
2794            } catch (CertificateEncodingException e) {
2795                scannedCompatSet.add(sig);
2796            }
2797        }
2798        /*
2799         * Make sure the expanded scanned set contains all signatures in the
2800         * existing one.
2801         */
2802        if (scannedCompatSet.equals(existingSet)) {
2803            // Migrate the old signatures to the new scheme.
2804            existingSigs.assignSignatures(scannedPkg.mSignatures);
2805            // The new KeySets will be re-added later in the scanning process.
2806            synchronized (mPackages) {
2807                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2808            }
2809            return PackageManager.SIGNATURE_MATCH;
2810        }
2811        return PackageManager.SIGNATURE_NO_MATCH;
2812    }
2813
2814    @Override
2815    public String[] getPackagesForUid(int uid) {
2816        uid = UserHandle.getAppId(uid);
2817        // reader
2818        synchronized (mPackages) {
2819            Object obj = mSettings.getUserIdLPr(uid);
2820            if (obj instanceof SharedUserSetting) {
2821                final SharedUserSetting sus = (SharedUserSetting) obj;
2822                final int N = sus.packages.size();
2823                final String[] res = new String[N];
2824                final Iterator<PackageSetting> it = sus.packages.iterator();
2825                int i = 0;
2826                while (it.hasNext()) {
2827                    res[i++] = it.next().name;
2828                }
2829                return res;
2830            } else if (obj instanceof PackageSetting) {
2831                final PackageSetting ps = (PackageSetting) obj;
2832                return new String[] { ps.name };
2833            }
2834        }
2835        return null;
2836    }
2837
2838    @Override
2839    public String getNameForUid(int uid) {
2840        // reader
2841        synchronized (mPackages) {
2842            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2843            if (obj instanceof SharedUserSetting) {
2844                final SharedUserSetting sus = (SharedUserSetting) obj;
2845                return sus.name + ":" + sus.userId;
2846            } else if (obj instanceof PackageSetting) {
2847                final PackageSetting ps = (PackageSetting) obj;
2848                return ps.name;
2849            }
2850        }
2851        return null;
2852    }
2853
2854    @Override
2855    public int getUidForSharedUser(String sharedUserName) {
2856        if(sharedUserName == null) {
2857            return -1;
2858        }
2859        // reader
2860        synchronized (mPackages) {
2861            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2862            if (suid == null) {
2863                return -1;
2864            }
2865            return suid.userId;
2866        }
2867    }
2868
2869    @Override
2870    public int getFlagsForUid(int uid) {
2871        synchronized (mPackages) {
2872            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2873            if (obj instanceof SharedUserSetting) {
2874                final SharedUserSetting sus = (SharedUserSetting) obj;
2875                return sus.pkgFlags;
2876            } else if (obj instanceof PackageSetting) {
2877                final PackageSetting ps = (PackageSetting) obj;
2878                return ps.pkgFlags;
2879            }
2880        }
2881        return 0;
2882    }
2883
2884    @Override
2885    public String[] getAppOpPermissionPackages(String permissionName) {
2886        synchronized (mPackages) {
2887            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2888            if (pkgs == null) {
2889                return null;
2890            }
2891            return pkgs.toArray(new String[pkgs.size()]);
2892        }
2893    }
2894
2895    @Override
2896    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2897            int flags, int userId) {
2898        if (!sUserManager.exists(userId)) return null;
2899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2900        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2901        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2902    }
2903
2904    @Override
2905    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2906            IntentFilter filter, int match, ComponentName activity) {
2907        final int userId = UserHandle.getCallingUserId();
2908        if (DEBUG_PREFERRED) {
2909            Log.v(TAG, "setLastChosenActivity intent=" + intent
2910                + " resolvedType=" + resolvedType
2911                + " flags=" + flags
2912                + " filter=" + filter
2913                + " match=" + match
2914                + " activity=" + activity);
2915            filter.dump(new PrintStreamPrinter(System.out), "    ");
2916        }
2917        intent.setComponent(null);
2918        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2919        // Find any earlier preferred or last chosen entries and nuke them
2920        findPreferredActivity(intent, resolvedType,
2921                flags, query, 0, false, true, false, userId);
2922        // Add the new activity as the last chosen for this filter
2923        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2924                "Setting last chosen");
2925    }
2926
2927    @Override
2928    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2929        final int userId = UserHandle.getCallingUserId();
2930        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2931        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2932        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2933                false, false, false, userId);
2934    }
2935
2936    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2937            int flags, List<ResolveInfo> query, int userId) {
2938        if (query != null) {
2939            final int N = query.size();
2940            if (N == 1) {
2941                return query.get(0);
2942            } else if (N > 1) {
2943                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2944                // If there is more than one activity with the same priority,
2945                // then let the user decide between them.
2946                ResolveInfo r0 = query.get(0);
2947                ResolveInfo r1 = query.get(1);
2948                if (DEBUG_INTENT_MATCHING || debug) {
2949                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2950                            + r1.activityInfo.name + "=" + r1.priority);
2951                }
2952                // If the first activity has a higher priority, or a different
2953                // default, then it is always desireable to pick it.
2954                if (r0.priority != r1.priority
2955                        || r0.preferredOrder != r1.preferredOrder
2956                        || r0.isDefault != r1.isDefault) {
2957                    return query.get(0);
2958                }
2959                // If we have saved a preference for a preferred activity for
2960                // this Intent, use that.
2961                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2962                        flags, query, r0.priority, true, false, debug, userId);
2963                if (ri != null) {
2964                    return ri;
2965                }
2966                if (userId != 0) {
2967                    ri = new ResolveInfo(mResolveInfo);
2968                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2969                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2970                            ri.activityInfo.applicationInfo);
2971                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2972                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2973                    return ri;
2974                }
2975                return mResolveInfo;
2976            }
2977        }
2978        return null;
2979    }
2980
2981    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2982            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2983        final int N = query.size();
2984        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2985                .get(userId);
2986        // Get the list of persistent preferred activities that handle the intent
2987        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2988        List<PersistentPreferredActivity> pprefs = ppir != null
2989                ? ppir.queryIntent(intent, resolvedType,
2990                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2991                : null;
2992        if (pprefs != null && pprefs.size() > 0) {
2993            final int M = pprefs.size();
2994            for (int i=0; i<M; i++) {
2995                final PersistentPreferredActivity ppa = pprefs.get(i);
2996                if (DEBUG_PREFERRED || debug) {
2997                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2998                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2999                            + "\n  component=" + ppa.mComponent);
3000                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3001                }
3002                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3003                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3004                if (DEBUG_PREFERRED || debug) {
3005                    Slog.v(TAG, "Found persistent preferred activity:");
3006                    if (ai != null) {
3007                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3008                    } else {
3009                        Slog.v(TAG, "  null");
3010                    }
3011                }
3012                if (ai == null) {
3013                    // This previously registered persistent preferred activity
3014                    // component is no longer known. Ignore it and do NOT remove it.
3015                    continue;
3016                }
3017                for (int j=0; j<N; j++) {
3018                    final ResolveInfo ri = query.get(j);
3019                    if (!ri.activityInfo.applicationInfo.packageName
3020                            .equals(ai.applicationInfo.packageName)) {
3021                        continue;
3022                    }
3023                    if (!ri.activityInfo.name.equals(ai.name)) {
3024                        continue;
3025                    }
3026                    //  Found a persistent preference that can handle the intent.
3027                    if (DEBUG_PREFERRED || debug) {
3028                        Slog.v(TAG, "Returning persistent preferred activity: " +
3029                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3030                    }
3031                    return ri;
3032                }
3033            }
3034        }
3035        return null;
3036    }
3037
3038    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3039            List<ResolveInfo> query, int priority, boolean always,
3040            boolean removeMatches, boolean debug, int userId) {
3041        if (!sUserManager.exists(userId)) return null;
3042        // writer
3043        synchronized (mPackages) {
3044            if (intent.getSelector() != null) {
3045                intent = intent.getSelector();
3046            }
3047            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3048
3049            // Try to find a matching persistent preferred activity.
3050            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3051                    debug, userId);
3052
3053            // If a persistent preferred activity matched, use it.
3054            if (pri != null) {
3055                return pri;
3056            }
3057
3058            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3059            // Get the list of preferred activities that handle the intent
3060            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3061            List<PreferredActivity> prefs = pir != null
3062                    ? pir.queryIntent(intent, resolvedType,
3063                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3064                    : null;
3065            if (prefs != null && prefs.size() > 0) {
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                        continue;
3127                    }
3128                    for (int j=0; j<N; j++) {
3129                        final ResolveInfo ri = query.get(j);
3130                        if (!ri.activityInfo.applicationInfo.packageName
3131                                .equals(ai.applicationInfo.packageName)) {
3132                            continue;
3133                        }
3134                        if (!ri.activityInfo.name.equals(ai.name)) {
3135                            continue;
3136                        }
3137
3138                        if (removeMatches) {
3139                            pir.removeFilter(pa);
3140                            if (DEBUG_PREFERRED) {
3141                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3142                            }
3143                            break;
3144                        }
3145
3146                        // Okay we found a previously set preferred or last chosen app.
3147                        // If the result set is different from when this
3148                        // was created, we need to clear it and re-ask the
3149                        // user their preference, if we're looking for an "always" type entry.
3150                        if (always && !pa.mPref.sameSet(query, priority)) {
3151                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3152                                    + intent + " type " + resolvedType);
3153                            if (DEBUG_PREFERRED) {
3154                                Slog.v(TAG, "Removing preferred activity since set changed "
3155                                        + pa.mPref.mComponent);
3156                            }
3157                            pir.removeFilter(pa);
3158                            // Re-add the filter as a "last chosen" entry (!always)
3159                            PreferredActivity lastChosen = new PreferredActivity(
3160                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3161                            pir.addFilter(lastChosen);
3162                            mSettings.writePackageRestrictionsLPr(userId);
3163                            return null;
3164                        }
3165
3166                        // Yay! Either the set matched or we're looking for the last chosen
3167                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3168                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3169                        mSettings.writePackageRestrictionsLPr(userId);
3170                        return ri;
3171                    }
3172                }
3173            }
3174            mSettings.writePackageRestrictionsLPr(userId);
3175        }
3176        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3177        return null;
3178    }
3179
3180    /*
3181     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3182     */
3183    @Override
3184    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3185            int targetUserId) {
3186        mContext.enforceCallingOrSelfPermission(
3187                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3188        List<CrossProfileIntentFilter> matches =
3189                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3190        if (matches != null) {
3191            int size = matches.size();
3192            for (int i = 0; i < size; i++) {
3193                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3194            }
3195        }
3196        ArrayList<String> packageNames = null;
3197        SparseArray<ArrayList<String>> fromSource =
3198                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3199        if (fromSource != null) {
3200            packageNames = fromSource.get(targetUserId);
3201            if (packageNames != null) {
3202                // We need the package name, so we try to resolve with the loosest flags possible
3203                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3204                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3205                int count = resolveInfos.size();
3206                for (int i = 0; i < count; i++) {
3207                    ResolveInfo resolveInfo = resolveInfos.get(i);
3208                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3209                        return true;
3210                    }
3211                }
3212            }
3213        }
3214        return false;
3215    }
3216
3217    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3218            String resolvedType, int userId) {
3219        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3220        if (resolver != null) {
3221            return resolver.queryIntent(intent, resolvedType, false, userId);
3222        }
3223        return null;
3224    }
3225
3226    @Override
3227    public List<ResolveInfo> queryIntentActivities(Intent intent,
3228            String resolvedType, int flags, int userId) {
3229        if (!sUserManager.exists(userId)) return Collections.emptyList();
3230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3231        ComponentName comp = intent.getComponent();
3232        if (comp == null) {
3233            if (intent.getSelector() != null) {
3234                intent = intent.getSelector();
3235                comp = intent.getComponent();
3236            }
3237        }
3238
3239        if (comp != null) {
3240            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3241            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3242            if (ai != null) {
3243                final ResolveInfo ri = new ResolveInfo();
3244                ri.activityInfo = ai;
3245                list.add(ri);
3246            }
3247            return list;
3248        }
3249
3250        // reader
3251        synchronized (mPackages) {
3252            final String pkgName = intent.getPackage();
3253            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3254            if (pkgName == null) {
3255                ResolveInfo resolveInfo = null;
3256                if (queryCrossProfile) {
3257                    // Check if the intent needs to be forwarded to another user for this package
3258                    ArrayList<ResolveInfo> crossProfileResult =
3259                            queryIntentActivitiesCrossProfilePackage(
3260                                    intent, resolvedType, flags, userId);
3261                    if (!crossProfileResult.isEmpty()) {
3262                        // Skip the current profile
3263                        return crossProfileResult;
3264                    }
3265                    List<CrossProfileIntentFilter> matchingFilters =
3266                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3267                    // Check for results that need to skip the current profile.
3268                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3269                            resolvedType, flags, userId);
3270                    if (resolveInfo != null) {
3271                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3272                        result.add(resolveInfo);
3273                        return result;
3274                    }
3275                    // Check for cross profile results.
3276                    resolveInfo = queryCrossProfileIntents(
3277                            matchingFilters, intent, resolvedType, flags, userId);
3278                }
3279                // Check for results in the current profile.
3280                List<ResolveInfo> result = mActivities.queryIntent(
3281                        intent, resolvedType, flags, userId);
3282                if (resolveInfo != null) {
3283                    result.add(resolveInfo);
3284                    Collections.sort(result, mResolvePrioritySorter);
3285                }
3286                return result;
3287            }
3288            final PackageParser.Package pkg = mPackages.get(pkgName);
3289            if (pkg != null) {
3290                if (queryCrossProfile) {
3291                    ArrayList<ResolveInfo> crossProfileResult =
3292                            queryIntentActivitiesCrossProfilePackage(
3293                                    intent, resolvedType, flags, userId, pkg, pkgName);
3294                    if (!crossProfileResult.isEmpty()) {
3295                        // Skip the current profile
3296                        return crossProfileResult;
3297                    }
3298                }
3299                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3300                        pkg.activities, userId);
3301            }
3302            return new ArrayList<ResolveInfo>();
3303        }
3304    }
3305
3306    private ResolveInfo querySkipCurrentProfileIntents(
3307            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3308            int flags, int sourceUserId) {
3309        if (matchingFilters != null) {
3310            int size = matchingFilters.size();
3311            for (int i = 0; i < size; i ++) {
3312                CrossProfileIntentFilter filter = matchingFilters.get(i);
3313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3314                    // Checking if there are activities in the target user that can handle the
3315                    // intent.
3316                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3317                            flags, sourceUserId);
3318                    if (resolveInfo != null) {
3319                        return resolveInfo;
3320                    }
3321                }
3322            }
3323        }
3324        return null;
3325    }
3326
3327    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3328            Intent intent, String resolvedType, int flags, int userId) {
3329        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3330        SparseArray<ArrayList<String>> sourceForwardingInfo =
3331                mSettings.mCrossProfilePackageInfo.get(userId);
3332        if (sourceForwardingInfo != null) {
3333            int NI = sourceForwardingInfo.size();
3334            for (int i = 0; i < NI; i++) {
3335                int targetUserId = sourceForwardingInfo.keyAt(i);
3336                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3337                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3338                        intent, resolvedType, flags, targetUserId);
3339                int NJ = resolveInfos.size();
3340                for (int j = 0; j < NJ; j++) {
3341                    ResolveInfo resolveInfo = resolveInfos.get(j);
3342                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3343                        matchingResolveInfos.add(createForwardingResolveInfo(
3344                                resolveInfo.filter, userId, targetUserId));
3345                    }
3346                }
3347            }
3348        }
3349        return matchingResolveInfos;
3350    }
3351
3352    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3353            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3354            String packageName) {
3355        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3356        SparseArray<ArrayList<String>> sourceForwardingInfo =
3357                mSettings.mCrossProfilePackageInfo.get(userId);
3358        if (sourceForwardingInfo != null) {
3359            int NI = sourceForwardingInfo.size();
3360            for (int i = 0; i < NI; i++) {
3361                int targetUserId = sourceForwardingInfo.keyAt(i);
3362                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3363                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3364                            intent, resolvedType, flags, pkg.activities, targetUserId);
3365                    int NJ = resolveInfos.size();
3366                    for (int j = 0; j < NJ; j++) {
3367                        ResolveInfo resolveInfo = resolveInfos.get(j);
3368                        matchingResolveInfos.add(createForwardingResolveInfo(
3369                                resolveInfo.filter, userId, targetUserId));
3370                    }
3371                }
3372            }
3373        }
3374        return matchingResolveInfos;
3375    }
3376
3377    // Return matching ResolveInfo if any for skip current profile intent filters.
3378    private ResolveInfo queryCrossProfileIntents(
3379            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3380            int flags, int sourceUserId) {
3381        if (matchingFilters != null) {
3382            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3383            // match the same intent. For performance reasons, it is better not to
3384            // run queryIntent twice for the same userId
3385            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3386            int size = matchingFilters.size();
3387            for (int i = 0; i < size; i++) {
3388                CrossProfileIntentFilter filter = matchingFilters.get(i);
3389                int targetUserId = filter.getTargetUserId();
3390                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3391                        && !alreadyTriedUserIds.get(targetUserId)) {
3392                    // Checking if there are activities in the target user that can handle the
3393                    // intent.
3394                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3395                            flags, sourceUserId);
3396                    if (resolveInfo != null) return resolveInfo;
3397                    alreadyTriedUserIds.put(targetUserId, true);
3398                }
3399            }
3400        }
3401        return null;
3402    }
3403
3404    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3405            String resolvedType, int flags, int sourceUserId) {
3406        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3407                resolvedType, flags, filter.getTargetUserId());
3408        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3409            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3410        }
3411        return null;
3412    }
3413
3414    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3415            int sourceUserId, int targetUserId) {
3416        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3417        String className;
3418        if (targetUserId == UserHandle.USER_OWNER) {
3419            className = FORWARD_INTENT_TO_USER_OWNER;
3420        } else {
3421            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3422        }
3423        ComponentName forwardingActivityComponentName = new ComponentName(
3424                mAndroidApplication.packageName, className);
3425        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3426                sourceUserId);
3427        if (targetUserId == UserHandle.USER_OWNER) {
3428            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3429            forwardingResolveInfo.noResourceId = true;
3430        }
3431        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3432        forwardingResolveInfo.priority = 0;
3433        forwardingResolveInfo.preferredOrder = 0;
3434        forwardingResolveInfo.match = 0;
3435        forwardingResolveInfo.isDefault = true;
3436        forwardingResolveInfo.filter = filter;
3437        forwardingResolveInfo.targetUserId = targetUserId;
3438        return forwardingResolveInfo;
3439    }
3440
3441    @Override
3442    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3443            Intent[] specifics, String[] specificTypes, Intent intent,
3444            String resolvedType, int flags, int userId) {
3445        if (!sUserManager.exists(userId)) return Collections.emptyList();
3446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3447                "query intent activity options");
3448        final String resultsAction = intent.getAction();
3449
3450        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3451                | PackageManager.GET_RESOLVED_FILTER, userId);
3452
3453        if (DEBUG_INTENT_MATCHING) {
3454            Log.v(TAG, "Query " + intent + ": " + results);
3455        }
3456
3457        int specificsPos = 0;
3458        int N;
3459
3460        // todo: note that the algorithm used here is O(N^2).  This
3461        // isn't a problem in our current environment, but if we start running
3462        // into situations where we have more than 5 or 10 matches then this
3463        // should probably be changed to something smarter...
3464
3465        // First we go through and resolve each of the specific items
3466        // that were supplied, taking care of removing any corresponding
3467        // duplicate items in the generic resolve list.
3468        if (specifics != null) {
3469            for (int i=0; i<specifics.length; i++) {
3470                final Intent sintent = specifics[i];
3471                if (sintent == null) {
3472                    continue;
3473                }
3474
3475                if (DEBUG_INTENT_MATCHING) {
3476                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3477                }
3478
3479                String action = sintent.getAction();
3480                if (resultsAction != null && resultsAction.equals(action)) {
3481                    // If this action was explicitly requested, then don't
3482                    // remove things that have it.
3483                    action = null;
3484                }
3485
3486                ResolveInfo ri = null;
3487                ActivityInfo ai = null;
3488
3489                ComponentName comp = sintent.getComponent();
3490                if (comp == null) {
3491                    ri = resolveIntent(
3492                        sintent,
3493                        specificTypes != null ? specificTypes[i] : null,
3494                            flags, userId);
3495                    if (ri == null) {
3496                        continue;
3497                    }
3498                    if (ri == mResolveInfo) {
3499                        // ACK!  Must do something better with this.
3500                    }
3501                    ai = ri.activityInfo;
3502                    comp = new ComponentName(ai.applicationInfo.packageName,
3503                            ai.name);
3504                } else {
3505                    ai = getActivityInfo(comp, flags, userId);
3506                    if (ai == null) {
3507                        continue;
3508                    }
3509                }
3510
3511                // Look for any generic query activities that are duplicates
3512                // of this specific one, and remove them from the results.
3513                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3514                N = results.size();
3515                int j;
3516                for (j=specificsPos; j<N; j++) {
3517                    ResolveInfo sri = results.get(j);
3518                    if ((sri.activityInfo.name.equals(comp.getClassName())
3519                            && sri.activityInfo.applicationInfo.packageName.equals(
3520                                    comp.getPackageName()))
3521                        || (action != null && sri.filter.matchAction(action))) {
3522                        results.remove(j);
3523                        if (DEBUG_INTENT_MATCHING) Log.v(
3524                            TAG, "Removing duplicate item from " + j
3525                            + " due to specific " + specificsPos);
3526                        if (ri == null) {
3527                            ri = sri;
3528                        }
3529                        j--;
3530                        N--;
3531                    }
3532                }
3533
3534                // Add this specific item to its proper place.
3535                if (ri == null) {
3536                    ri = new ResolveInfo();
3537                    ri.activityInfo = ai;
3538                }
3539                results.add(specificsPos, ri);
3540                ri.specificIndex = i;
3541                specificsPos++;
3542            }
3543        }
3544
3545        // Now we go through the remaining generic results and remove any
3546        // duplicate actions that are found here.
3547        N = results.size();
3548        for (int i=specificsPos; i<N-1; i++) {
3549            final ResolveInfo rii = results.get(i);
3550            if (rii.filter == null) {
3551                continue;
3552            }
3553
3554            // Iterate over all of the actions of this result's intent
3555            // filter...  typically this should be just one.
3556            final Iterator<String> it = rii.filter.actionsIterator();
3557            if (it == null) {
3558                continue;
3559            }
3560            while (it.hasNext()) {
3561                final String action = it.next();
3562                if (resultsAction != null && resultsAction.equals(action)) {
3563                    // If this action was explicitly requested, then don't
3564                    // remove things that have it.
3565                    continue;
3566                }
3567                for (int j=i+1; j<N; j++) {
3568                    final ResolveInfo rij = results.get(j);
3569                    if (rij.filter != null && rij.filter.hasAction(action)) {
3570                        results.remove(j);
3571                        if (DEBUG_INTENT_MATCHING) Log.v(
3572                            TAG, "Removing duplicate item from " + j
3573                            + " due to action " + action + " at " + i);
3574                        j--;
3575                        N--;
3576                    }
3577                }
3578            }
3579
3580            // If the caller didn't request filter information, drop it now
3581            // so we don't have to marshall/unmarshall it.
3582            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3583                rii.filter = null;
3584            }
3585        }
3586
3587        // Filter out the caller activity if so requested.
3588        if (caller != null) {
3589            N = results.size();
3590            for (int i=0; i<N; i++) {
3591                ActivityInfo ainfo = results.get(i).activityInfo;
3592                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3593                        && caller.getClassName().equals(ainfo.name)) {
3594                    results.remove(i);
3595                    break;
3596                }
3597            }
3598        }
3599
3600        // If the caller didn't request filter information,
3601        // drop them now so we don't have to
3602        // marshall/unmarshall it.
3603        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3604            N = results.size();
3605            for (int i=0; i<N; i++) {
3606                results.get(i).filter = null;
3607            }
3608        }
3609
3610        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3611        return results;
3612    }
3613
3614    @Override
3615    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3616            int userId) {
3617        if (!sUserManager.exists(userId)) return Collections.emptyList();
3618        ComponentName comp = intent.getComponent();
3619        if (comp == null) {
3620            if (intent.getSelector() != null) {
3621                intent = intent.getSelector();
3622                comp = intent.getComponent();
3623            }
3624        }
3625        if (comp != null) {
3626            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3627            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3628            if (ai != null) {
3629                ResolveInfo ri = new ResolveInfo();
3630                ri.activityInfo = ai;
3631                list.add(ri);
3632            }
3633            return list;
3634        }
3635
3636        // reader
3637        synchronized (mPackages) {
3638            String pkgName = intent.getPackage();
3639            if (pkgName == null) {
3640                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3641            }
3642            final PackageParser.Package pkg = mPackages.get(pkgName);
3643            if (pkg != null) {
3644                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3645                        userId);
3646            }
3647            return null;
3648        }
3649    }
3650
3651    @Override
3652    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3653        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3654        if (!sUserManager.exists(userId)) return null;
3655        if (query != null) {
3656            if (query.size() >= 1) {
3657                // If there is more than one service with the same priority,
3658                // just arbitrarily pick the first one.
3659                return query.get(0);
3660            }
3661        }
3662        return null;
3663    }
3664
3665    @Override
3666    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3667            int userId) {
3668        if (!sUserManager.exists(userId)) return Collections.emptyList();
3669        ComponentName comp = intent.getComponent();
3670        if (comp == null) {
3671            if (intent.getSelector() != null) {
3672                intent = intent.getSelector();
3673                comp = intent.getComponent();
3674            }
3675        }
3676        if (comp != null) {
3677            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3678            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3679            if (si != null) {
3680                final ResolveInfo ri = new ResolveInfo();
3681                ri.serviceInfo = si;
3682                list.add(ri);
3683            }
3684            return list;
3685        }
3686
3687        // reader
3688        synchronized (mPackages) {
3689            String pkgName = intent.getPackage();
3690            if (pkgName == null) {
3691                return mServices.queryIntent(intent, resolvedType, flags, userId);
3692            }
3693            final PackageParser.Package pkg = mPackages.get(pkgName);
3694            if (pkg != null) {
3695                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3696                        userId);
3697            }
3698            return null;
3699        }
3700    }
3701
3702    @Override
3703    public List<ResolveInfo> queryIntentContentProviders(
3704            Intent intent, String resolvedType, int flags, int userId) {
3705        if (!sUserManager.exists(userId)) return Collections.emptyList();
3706        ComponentName comp = intent.getComponent();
3707        if (comp == null) {
3708            if (intent.getSelector() != null) {
3709                intent = intent.getSelector();
3710                comp = intent.getComponent();
3711            }
3712        }
3713        if (comp != null) {
3714            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3715            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3716            if (pi != null) {
3717                final ResolveInfo ri = new ResolveInfo();
3718                ri.providerInfo = pi;
3719                list.add(ri);
3720            }
3721            return list;
3722        }
3723
3724        // reader
3725        synchronized (mPackages) {
3726            String pkgName = intent.getPackage();
3727            if (pkgName == null) {
3728                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3729            }
3730            final PackageParser.Package pkg = mPackages.get(pkgName);
3731            if (pkg != null) {
3732                return mProviders.queryIntentForPackage(
3733                        intent, resolvedType, flags, pkg.providers, userId);
3734            }
3735            return null;
3736        }
3737    }
3738
3739    @Override
3740    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3741        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3742
3743        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3744
3745        // writer
3746        synchronized (mPackages) {
3747            ArrayList<PackageInfo> list;
3748            if (listUninstalled) {
3749                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3750                for (PackageSetting ps : mSettings.mPackages.values()) {
3751                    PackageInfo pi;
3752                    if (ps.pkg != null) {
3753                        pi = generatePackageInfo(ps.pkg, flags, userId);
3754                    } else {
3755                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3756                    }
3757                    if (pi != null) {
3758                        list.add(pi);
3759                    }
3760                }
3761            } else {
3762                list = new ArrayList<PackageInfo>(mPackages.size());
3763                for (PackageParser.Package p : mPackages.values()) {
3764                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3765                    if (pi != null) {
3766                        list.add(pi);
3767                    }
3768                }
3769            }
3770
3771            return new ParceledListSlice<PackageInfo>(list);
3772        }
3773    }
3774
3775    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3776            String[] permissions, boolean[] tmp, int flags, int userId) {
3777        int numMatch = 0;
3778        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3779        for (int i=0; i<permissions.length; i++) {
3780            if (gp.grantedPermissions.contains(permissions[i])) {
3781                tmp[i] = true;
3782                numMatch++;
3783            } else {
3784                tmp[i] = false;
3785            }
3786        }
3787        if (numMatch == 0) {
3788            return;
3789        }
3790        PackageInfo pi;
3791        if (ps.pkg != null) {
3792            pi = generatePackageInfo(ps.pkg, flags, userId);
3793        } else {
3794            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3795        }
3796        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3797            if (numMatch == permissions.length) {
3798                pi.requestedPermissions = permissions;
3799            } else {
3800                pi.requestedPermissions = new String[numMatch];
3801                numMatch = 0;
3802                for (int i=0; i<permissions.length; i++) {
3803                    if (tmp[i]) {
3804                        pi.requestedPermissions[numMatch] = permissions[i];
3805                        numMatch++;
3806                    }
3807                }
3808            }
3809        }
3810        list.add(pi);
3811    }
3812
3813    @Override
3814    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3815            String[] permissions, int flags, int userId) {
3816        if (!sUserManager.exists(userId)) return null;
3817        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3818
3819        // writer
3820        synchronized (mPackages) {
3821            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3822            boolean[] tmpBools = new boolean[permissions.length];
3823            if (listUninstalled) {
3824                for (PackageSetting ps : mSettings.mPackages.values()) {
3825                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3826                }
3827            } else {
3828                for (PackageParser.Package pkg : mPackages.values()) {
3829                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3830                    if (ps != null) {
3831                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3832                                userId);
3833                    }
3834                }
3835            }
3836
3837            return new ParceledListSlice<PackageInfo>(list);
3838        }
3839    }
3840
3841    @Override
3842    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3843        if (!sUserManager.exists(userId)) return null;
3844        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3845
3846        // writer
3847        synchronized (mPackages) {
3848            ArrayList<ApplicationInfo> list;
3849            if (listUninstalled) {
3850                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3851                for (PackageSetting ps : mSettings.mPackages.values()) {
3852                    ApplicationInfo ai;
3853                    if (ps.pkg != null) {
3854                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3855                                ps.readUserState(userId), userId);
3856                    } else {
3857                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3858                    }
3859                    if (ai != null) {
3860                        list.add(ai);
3861                    }
3862                }
3863            } else {
3864                list = new ArrayList<ApplicationInfo>(mPackages.size());
3865                for (PackageParser.Package p : mPackages.values()) {
3866                    if (p.mExtras != null) {
3867                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3868                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3869                        if (ai != null) {
3870                            list.add(ai);
3871                        }
3872                    }
3873                }
3874            }
3875
3876            return new ParceledListSlice<ApplicationInfo>(list);
3877        }
3878    }
3879
3880    public List<ApplicationInfo> getPersistentApplications(int flags) {
3881        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3882
3883        // reader
3884        synchronized (mPackages) {
3885            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3886            final int userId = UserHandle.getCallingUserId();
3887            while (i.hasNext()) {
3888                final PackageParser.Package p = i.next();
3889                if (p.applicationInfo != null
3890                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3891                        && (!mSafeMode || isSystemApp(p))) {
3892                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3893                    if (ps != null) {
3894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3895                                ps.readUserState(userId), userId);
3896                        if (ai != null) {
3897                            finalList.add(ai);
3898                        }
3899                    }
3900                }
3901            }
3902        }
3903
3904        return finalList;
3905    }
3906
3907    @Override
3908    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3909        if (!sUserManager.exists(userId)) return null;
3910        // reader
3911        synchronized (mPackages) {
3912            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3913            PackageSetting ps = provider != null
3914                    ? mSettings.mPackages.get(provider.owner.packageName)
3915                    : null;
3916            return ps != null
3917                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3918                    && (!mSafeMode || (provider.info.applicationInfo.flags
3919                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3920                    ? PackageParser.generateProviderInfo(provider, flags,
3921                            ps.readUserState(userId), userId)
3922                    : null;
3923        }
3924    }
3925
3926    /**
3927     * @deprecated
3928     */
3929    @Deprecated
3930    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3931        // reader
3932        synchronized (mPackages) {
3933            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3934                    .entrySet().iterator();
3935            final int userId = UserHandle.getCallingUserId();
3936            while (i.hasNext()) {
3937                Map.Entry<String, PackageParser.Provider> entry = i.next();
3938                PackageParser.Provider p = entry.getValue();
3939                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3940
3941                if (ps != null && p.syncable
3942                        && (!mSafeMode || (p.info.applicationInfo.flags
3943                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3944                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3945                            ps.readUserState(userId), userId);
3946                    if (info != null) {
3947                        outNames.add(entry.getKey());
3948                        outInfo.add(info);
3949                    }
3950                }
3951            }
3952        }
3953    }
3954
3955    @Override
3956    public List<ProviderInfo> queryContentProviders(String processName,
3957            int uid, int flags) {
3958        ArrayList<ProviderInfo> finalList = null;
3959        // reader
3960        synchronized (mPackages) {
3961            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3962            final int userId = processName != null ?
3963                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3964            while (i.hasNext()) {
3965                final PackageParser.Provider p = i.next();
3966                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3967                if (ps != null && p.info.authority != null
3968                        && (processName == null
3969                                || (p.info.processName.equals(processName)
3970                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3971                        && mSettings.isEnabledLPr(p.info, flags, userId)
3972                        && (!mSafeMode
3973                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3974                    if (finalList == null) {
3975                        finalList = new ArrayList<ProviderInfo>(3);
3976                    }
3977                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3978                            ps.readUserState(userId), userId);
3979                    if (info != null) {
3980                        finalList.add(info);
3981                    }
3982                }
3983            }
3984        }
3985
3986        if (finalList != null) {
3987            Collections.sort(finalList, mProviderInitOrderSorter);
3988        }
3989
3990        return finalList;
3991    }
3992
3993    @Override
3994    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3995            int flags) {
3996        // reader
3997        synchronized (mPackages) {
3998            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3999            return PackageParser.generateInstrumentationInfo(i, flags);
4000        }
4001    }
4002
4003    @Override
4004    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4005            int flags) {
4006        ArrayList<InstrumentationInfo> finalList =
4007            new ArrayList<InstrumentationInfo>();
4008
4009        // reader
4010        synchronized (mPackages) {
4011            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4012            while (i.hasNext()) {
4013                final PackageParser.Instrumentation p = i.next();
4014                if (targetPackage == null
4015                        || targetPackage.equals(p.info.targetPackage)) {
4016                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4017                            flags);
4018                    if (ii != null) {
4019                        finalList.add(ii);
4020                    }
4021                }
4022            }
4023        }
4024
4025        return finalList;
4026    }
4027
4028    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4029        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4030        if (overlays == null) {
4031            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4032            return;
4033        }
4034        for (PackageParser.Package opkg : overlays.values()) {
4035            // Not much to do if idmap fails: we already logged the error
4036            // and we certainly don't want to abort installation of pkg simply
4037            // because an overlay didn't fit properly. For these reasons,
4038            // ignore the return value of createIdmapForPackagePairLI.
4039            createIdmapForPackagePairLI(pkg, opkg);
4040        }
4041    }
4042
4043    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4044            PackageParser.Package opkg) {
4045        if (!opkg.mTrustedOverlay) {
4046            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4047                    opkg.baseCodePath + ": overlay not trusted");
4048            return false;
4049        }
4050        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4051        if (overlaySet == null) {
4052            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4053                    opkg.baseCodePath + " but target package has no known overlays");
4054            return false;
4055        }
4056        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4057        // TODO: generate idmap for split APKs
4058        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4059            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4060                    + opkg.baseCodePath);
4061            return false;
4062        }
4063        PackageParser.Package[] overlayArray =
4064            overlaySet.values().toArray(new PackageParser.Package[0]);
4065        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4066            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4067                return p1.mOverlayPriority - p2.mOverlayPriority;
4068            }
4069        };
4070        Arrays.sort(overlayArray, cmp);
4071
4072        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4073        int i = 0;
4074        for (PackageParser.Package p : overlayArray) {
4075            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4076        }
4077        return true;
4078    }
4079
4080    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4081        final File[] files = dir.listFiles();
4082        if (ArrayUtils.isEmpty(files)) {
4083            Log.d(TAG, "No files in app dir " + dir);
4084            return;
4085        }
4086
4087        if (DEBUG_PACKAGE_SCANNING) {
4088            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4089                    + " flags=0x" + Integer.toHexString(flags));
4090        }
4091
4092        for (File file : files) {
4093            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4094                    && !PackageInstallerService.isStageName(file.getName());
4095            if (!isPackage) {
4096                // Ignore entries which are not packages
4097                continue;
4098            }
4099            try {
4100                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK,
4101                        scanMode, currentTime, null);
4102            } catch (PackageManagerException e) {
4103                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4104
4105                // Delete invalid userdata apps
4106                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4107                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4108                    Slog.w(TAG, "Deleting invalid package at " + file);
4109                    if (file.isDirectory()) {
4110                        FileUtils.deleteContents(file);
4111                    }
4112                    file.delete();
4113                }
4114            }
4115        }
4116    }
4117
4118    private static File getSettingsProblemFile() {
4119        File dataDir = Environment.getDataDirectory();
4120        File systemDir = new File(dataDir, "system");
4121        File fname = new File(systemDir, "uiderrors.txt");
4122        return fname;
4123    }
4124
4125    static void reportSettingsProblem(int priority, String msg) {
4126        try {
4127            File fname = getSettingsProblemFile();
4128            FileOutputStream out = new FileOutputStream(fname, true);
4129            PrintWriter pw = new FastPrintWriter(out);
4130            SimpleDateFormat formatter = new SimpleDateFormat();
4131            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4132            pw.println(dateString + ": " + msg);
4133            pw.close();
4134            FileUtils.setPermissions(
4135                    fname.toString(),
4136                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4137                    -1, -1);
4138        } catch (java.io.IOException e) {
4139        }
4140        Slog.println(priority, TAG, msg);
4141    }
4142
4143    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4144            PackageParser.Package pkg, File srcFile, int parseFlags)
4145            throws PackageManagerException {
4146        if (ps != null
4147                && ps.codePath.equals(srcFile)
4148                && ps.timeStamp == srcFile.lastModified()
4149                && !isCompatSignatureUpdateNeeded(pkg)) {
4150            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4151            if (ps.signatures.mSignatures != null
4152                    && ps.signatures.mSignatures.length != 0
4153                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4154                // Optimization: reuse the existing cached certificates
4155                // if the package appears to be unchanged.
4156                pkg.mSignatures = ps.signatures.mSignatures;
4157                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4158                synchronized (mPackages) {
4159                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4160                }
4161                return;
4162            }
4163
4164            Slog.w(TAG, "PackageSetting for " + ps.name
4165                    + " is missing signatures.  Collecting certs again to recover them.");
4166        } else {
4167            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4168        }
4169
4170        try {
4171            pp.collectCertificates(pkg, parseFlags);
4172            pp.collectManifestDigest(pkg);
4173        } catch (PackageParserException e) {
4174            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4175                    + pkg.packageName + ": " + e.getMessage());
4176        }
4177    }
4178
4179    /*
4180     *  Scan a package and return the newly parsed package.
4181     *  Returns null in case of errors and the error code is stored in mLastScanError
4182     */
4183    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4184            long currentTime, UserHandle user) throws PackageManagerException {
4185        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4186        parseFlags |= mDefParseFlags;
4187        PackageParser pp = new PackageParser();
4188        pp.setSeparateProcesses(mSeparateProcesses);
4189        pp.setOnlyCoreApps(mOnlyCore);
4190        pp.setDisplayMetrics(mMetrics);
4191
4192        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4193            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4194        }
4195
4196        final PackageParser.Package pkg;
4197        try {
4198            pkg = pp.parsePackage(scanFile, parseFlags);
4199        } catch (PackageParserException e) {
4200            throw new PackageManagerException(e.error,
4201                    "Failed to scan " + scanFile + ": " + e.getMessage());
4202        }
4203
4204        PackageSetting ps = null;
4205        PackageSetting updatedPkg;
4206        // reader
4207        synchronized (mPackages) {
4208            // Look to see if we already know about this package.
4209            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4210            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4211                // This package has been renamed to its original name.  Let's
4212                // use that.
4213                ps = mSettings.peekPackageLPr(oldName);
4214            }
4215            // If there was no original package, see one for the real package name.
4216            if (ps == null) {
4217                ps = mSettings.peekPackageLPr(pkg.packageName);
4218            }
4219            // Check to see if this package could be hiding/updating a system
4220            // package.  Must look for it either under the original or real
4221            // package name depending on our state.
4222            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4223            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4224        }
4225        boolean updatedPkgBetter = false;
4226        // First check if this is a system package that may involve an update
4227        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4228            if (ps != null && !ps.codePath.equals(scanFile)) {
4229                // The path has changed from what was last scanned...  check the
4230                // version of the new path against what we have stored to determine
4231                // what to do.
4232                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4233                if (pkg.mVersionCode < ps.versionCode) {
4234                    // The system package has been updated and the code path does not match
4235                    // Ignore entry. Skip it.
4236                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4237                            + " ignored: updated version " + ps.versionCode
4238                            + " better than this " + pkg.mVersionCode);
4239                    if (!updatedPkg.codePath.equals(scanFile)) {
4240                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4241                                + ps.name + " changing from " + updatedPkg.codePathString
4242                                + " to " + scanFile);
4243                        updatedPkg.codePath = scanFile;
4244                        updatedPkg.codePathString = scanFile.toString();
4245                        // This is the point at which we know that the system-disk APK
4246                        // for this package has moved during a reboot (e.g. due to an OTA),
4247                        // so we need to reevaluate it for privilege policy.
4248                        if (locationIsPrivileged(scanFile)) {
4249                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4250                        }
4251                    }
4252                    updatedPkg.pkg = pkg;
4253                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4254                } else {
4255                    // The current app on the system partition is better than
4256                    // what we have updated to on the data partition; switch
4257                    // back to the system partition version.
4258                    // At this point, its safely assumed that package installation for
4259                    // apps in system partition will go through. If not there won't be a working
4260                    // version of the app
4261                    // writer
4262                    synchronized (mPackages) {
4263                        // Just remove the loaded entries from package lists.
4264                        mPackages.remove(ps.name);
4265                    }
4266                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4267                            + "reverting from " + ps.codePathString
4268                            + ": new version " + pkg.mVersionCode
4269                            + " better than installed " + ps.versionCode);
4270
4271                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4272                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4273                            getAppDexInstructionSets(ps));
4274                    synchronized (mInstallLock) {
4275                        args.cleanUpResourcesLI();
4276                    }
4277                    synchronized (mPackages) {
4278                        mSettings.enableSystemPackageLPw(ps.name);
4279                    }
4280                    updatedPkgBetter = true;
4281                }
4282            }
4283        }
4284
4285        if (updatedPkg != null) {
4286            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4287            // initially
4288            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4289
4290            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4291            // flag set initially
4292            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4293                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4294            }
4295        }
4296
4297        // Verify certificates against what was last scanned
4298        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4299
4300        /*
4301         * A new system app appeared, but we already had a non-system one of the
4302         * same name installed earlier.
4303         */
4304        boolean shouldHideSystemApp = false;
4305        if (updatedPkg == null && ps != null
4306                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4307            /*
4308             * Check to make sure the signatures match first. If they don't,
4309             * wipe the installed application and its data.
4310             */
4311            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4312                    != PackageManager.SIGNATURE_MATCH) {
4313                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4314                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4315                ps = null;
4316            } else {
4317                /*
4318                 * If the newly-added system app is an older version than the
4319                 * already installed version, hide it. It will be scanned later
4320                 * and re-added like an update.
4321                 */
4322                if (pkg.mVersionCode < ps.versionCode) {
4323                    shouldHideSystemApp = true;
4324                } else {
4325                    /*
4326                     * The newly found system app is a newer version that the
4327                     * one previously installed. Simply remove the
4328                     * already-installed application and replace it with our own
4329                     * while keeping the application data.
4330                     */
4331                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4332                            + ps.codePathString + ": new version " + pkg.mVersionCode
4333                            + " better than installed " + ps.versionCode);
4334                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4335                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4336                            getAppDexInstructionSets(ps));
4337                    synchronized (mInstallLock) {
4338                        args.cleanUpResourcesLI();
4339                    }
4340                }
4341            }
4342        }
4343
4344        // The apk is forward locked (not public) if its code and resources
4345        // are kept in different files. (except for app in either system or
4346        // vendor path).
4347        // TODO grab this value from PackageSettings
4348        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4349            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4350                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4351            }
4352        }
4353
4354        // TODO: extend to support forward-locked splits
4355        String resourcePath = null;
4356        String baseResourcePath = null;
4357        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4358            if (ps != null && ps.resourcePathString != null) {
4359                resourcePath = ps.resourcePathString;
4360                baseResourcePath = ps.resourcePathString;
4361            } else {
4362                // Should not happen at all. Just log an error.
4363                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4364            }
4365        } else {
4366            resourcePath = pkg.codePath;
4367            baseResourcePath = pkg.baseCodePath;
4368        }
4369
4370        // Set application objects path explicitly.
4371        pkg.applicationInfo.setCodePath(pkg.codePath);
4372        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4373        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4374        pkg.applicationInfo.setResourcePath(resourcePath);
4375        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4376        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4377
4378        // Note that we invoke the following method only if we are about to unpack an application
4379        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4380                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4381
4382        /*
4383         * If the system app should be overridden by a previously installed
4384         * data, hide the system app now and let the /data/app scan pick it up
4385         * again.
4386         */
4387        if (shouldHideSystemApp) {
4388            synchronized (mPackages) {
4389                /*
4390                 * We have to grant systems permissions before we hide, because
4391                 * grantPermissions will assume the package update is trying to
4392                 * expand its permissions.
4393                 */
4394                grantPermissionsLPw(pkg, true);
4395                mSettings.disableSystemPackageLPw(pkg.packageName);
4396            }
4397        }
4398
4399        return scannedPkg;
4400    }
4401
4402    private static String fixProcessName(String defProcessName,
4403            String processName, int uid) {
4404        if (processName == null) {
4405            return defProcessName;
4406        }
4407        return processName;
4408    }
4409
4410    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4411            throws PackageManagerException {
4412        if (pkgSetting.signatures.mSignatures != null) {
4413            // Already existing package. Make sure signatures match
4414            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4415                    == PackageManager.SIGNATURE_MATCH;
4416            if (!match) {
4417                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4418                        == PackageManager.SIGNATURE_MATCH;
4419            }
4420            if (!match) {
4421                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4422                        + pkg.packageName + " signatures do not match the "
4423                        + "previously installed version; ignoring!");
4424            }
4425        }
4426
4427        // Check for shared user signatures
4428        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4429            // Already existing package. Make sure signatures match
4430            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4431                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4432            if (!match) {
4433                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4434                        == PackageManager.SIGNATURE_MATCH;
4435            }
4436            if (!match) {
4437                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4438                        "Package " + pkg.packageName
4439                        + " has no signatures that match those in shared user "
4440                        + pkgSetting.sharedUser.name + "; ignoring!");
4441            }
4442        }
4443    }
4444
4445    /**
4446     * Enforces that only the system UID or root's UID can call a method exposed
4447     * via Binder.
4448     *
4449     * @param message used as message if SecurityException is thrown
4450     * @throws SecurityException if the caller is not system or root
4451     */
4452    private static final void enforceSystemOrRoot(String message) {
4453        final int uid = Binder.getCallingUid();
4454        if (uid != Process.SYSTEM_UID && uid != 0) {
4455            throw new SecurityException(message);
4456        }
4457    }
4458
4459    @Override
4460    public void performBootDexOpt() {
4461        enforceSystemOrRoot("Only the system can request dexopt be performed");
4462
4463        final HashSet<PackageParser.Package> pkgs;
4464        synchronized (mPackages) {
4465            pkgs = mDeferredDexOpt;
4466            mDeferredDexOpt = null;
4467        }
4468
4469        if (pkgs != null) {
4470            // Filter out packages that aren't recently used.
4471            //
4472            // The exception is first boot of a non-eng device, which
4473            // should do a full dexopt.
4474            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4475            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4476                // TODO: add a property to control this?
4477                long dexOptLRUThresholdInMinutes;
4478                if (eng) {
4479                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4480                } else {
4481                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4482                }
4483                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4484
4485                int total = pkgs.size();
4486                int skipped = 0;
4487                long now = System.currentTimeMillis();
4488                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4489                    PackageParser.Package pkg = i.next();
4490                    long then = pkg.mLastPackageUsageTimeInMills;
4491                    if (then + dexOptLRUThresholdInMills < now) {
4492                        if (DEBUG_DEXOPT) {
4493                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4494                                  ((then == 0) ? "never" : new Date(then)));
4495                        }
4496                        i.remove();
4497                        skipped++;
4498                    }
4499                }
4500                if (DEBUG_DEXOPT) {
4501                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4502                }
4503            }
4504
4505            int i = 0;
4506            for (PackageParser.Package pkg : pkgs) {
4507                i++;
4508                if (DEBUG_DEXOPT) {
4509                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4510                          + ": " + pkg.packageName);
4511                }
4512                if (!isFirstBoot()) {
4513                    try {
4514                        ActivityManagerNative.getDefault().showBootMessage(
4515                                mContext.getResources().getString(
4516                                        R.string.android_upgrading_apk,
4517                                        i, pkgs.size()), true);
4518                    } catch (RemoteException e) {
4519                    }
4520                }
4521                PackageParser.Package p = pkg;
4522                synchronized (mInstallLock) {
4523                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4524                            true /* include dependencies */);
4525                }
4526            }
4527        }
4528    }
4529
4530    @Override
4531    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4532        return performDexOpt(packageName, instructionSet, true);
4533    }
4534
4535    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4536        if (info.primaryCpuAbi == null) {
4537            return getPreferredInstructionSet();
4538        }
4539
4540        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4541    }
4542
4543    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4544        PackageParser.Package p;
4545        final String targetInstructionSet;
4546        synchronized (mPackages) {
4547            p = mPackages.get(packageName);
4548            if (p == null) {
4549                return false;
4550            }
4551            if (updateUsage) {
4552                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4553            }
4554            mPackageUsage.write(false);
4555
4556            targetInstructionSet = instructionSet != null ? instructionSet :
4557                    getPrimaryInstructionSet(p.applicationInfo);
4558            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4559                return false;
4560            }
4561        }
4562
4563        synchronized (mInstallLock) {
4564            final String[] instructionSets = new String[] { targetInstructionSet };
4565            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4566                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4567        }
4568    }
4569
4570    public HashSet<String> getPackagesThatNeedDexOpt() {
4571        HashSet<String> pkgs = null;
4572        synchronized (mPackages) {
4573            for (PackageParser.Package p : mPackages.values()) {
4574                if (DEBUG_DEXOPT) {
4575                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4576                }
4577                if (!p.mDexOptPerformed.isEmpty()) {
4578                    continue;
4579                }
4580                if (pkgs == null) {
4581                    pkgs = new HashSet<String>();
4582                }
4583                pkgs.add(p.packageName);
4584            }
4585        }
4586        return pkgs;
4587    }
4588
4589    public void shutdown() {
4590        mPackageUsage.write(true);
4591    }
4592
4593    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4594             boolean forceDex, boolean defer, HashSet<String> done) {
4595        for (int i=0; i<libs.size(); i++) {
4596            PackageParser.Package libPkg;
4597            String libName;
4598            synchronized (mPackages) {
4599                libName = libs.get(i);
4600                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4601                if (lib != null && lib.apk != null) {
4602                    libPkg = mPackages.get(lib.apk);
4603                } else {
4604                    libPkg = null;
4605                }
4606            }
4607            if (libPkg != null && !done.contains(libName)) {
4608                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4609            }
4610        }
4611    }
4612
4613    static final int DEX_OPT_SKIPPED = 0;
4614    static final int DEX_OPT_PERFORMED = 1;
4615    static final int DEX_OPT_DEFERRED = 2;
4616    static final int DEX_OPT_FAILED = -1;
4617
4618    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4619            boolean forceDex, boolean defer, HashSet<String> done) {
4620        final String[] instructionSets = targetInstructionSets != null ?
4621                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4622
4623        if (done != null) {
4624            done.add(pkg.packageName);
4625            if (pkg.usesLibraries != null) {
4626                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4627            }
4628            if (pkg.usesOptionalLibraries != null) {
4629                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4630            }
4631        }
4632
4633        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4634            return DEX_OPT_SKIPPED;
4635        }
4636
4637        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4638
4639        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4640        boolean performedDexOpt = false;
4641        // There are three basic cases here:
4642        // 1.) we need to dexopt, either because we are forced or it is needed
4643        // 2.) we are defering a needed dexopt
4644        // 3.) we are skipping an unneeded dexopt
4645        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4646        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4647            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4648                continue;
4649            }
4650
4651            for (String path : paths) {
4652                try {
4653                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4654                    // patckage or the one we find does not match the image checksum (i.e. it was
4655                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4656                    // odex file and it matches the checksum of the image but not its base address,
4657                    // meaning we need to move it.
4658                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4659                            pkg.packageName, dexCodeInstructionSet, defer);
4660                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4661                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4662                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4663                                + " vmSafeMode=" + vmSafeMode);
4664                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4665                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4666                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4667
4668                        if (ret < 0) {
4669                            // Don't bother running dexopt again if we failed, it will probably
4670                            // just result in an error again. Also, don't bother dexopting for other
4671                            // paths & ISAs.
4672                            return DEX_OPT_FAILED;
4673                        }
4674
4675                        performedDexOpt = true;
4676                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4677                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4678                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4679                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4680                                pkg.packageName, dexCodeInstructionSet);
4681
4682                        if (ret < 0) {
4683                            // Don't bother running patchoat again if we failed, it will probably
4684                            // just result in an error again. Also, don't bother dexopting for other
4685                            // paths & ISAs.
4686                            return DEX_OPT_FAILED;
4687                        }
4688
4689                        performedDexOpt = true;
4690                    }
4691
4692                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4693                    // paths and instruction sets. We'll deal with them all together when we process
4694                    // our list of deferred dexopts.
4695                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4696                        if (mDeferredDexOpt == null) {
4697                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4698                        }
4699                        mDeferredDexOpt.add(pkg);
4700                        return DEX_OPT_DEFERRED;
4701                    }
4702                } catch (FileNotFoundException e) {
4703                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4704                    return DEX_OPT_FAILED;
4705                } catch (IOException e) {
4706                    Slog.w(TAG, "IOException reading apk: " + path, e);
4707                    return DEX_OPT_FAILED;
4708                } catch (StaleDexCacheError e) {
4709                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4710                    return DEX_OPT_FAILED;
4711                } catch (Exception e) {
4712                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4713                    return DEX_OPT_FAILED;
4714                }
4715            }
4716
4717            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4718            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4719            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4720            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4721            // it.
4722            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4723        }
4724
4725        // If we've gotten here, we're sure that no error occurred and that we haven't
4726        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4727        // we've skipped all of them because they are up to date. In both cases this
4728        // package doesn't need dexopt any longer.
4729        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4730    }
4731
4732    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4733        if (info.primaryCpuAbi != null) {
4734            if (info.secondaryCpuAbi != null) {
4735                return new String[] {
4736                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4737                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4738            } else {
4739                return new String[] {
4740                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4741            }
4742        }
4743
4744        return new String[] { getPreferredInstructionSet() };
4745    }
4746
4747    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4748        if (ps.primaryCpuAbiString != null) {
4749            if (ps.secondaryCpuAbiString != null) {
4750                return new String[] {
4751                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4752                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4753            } else {
4754                return new String[] {
4755                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4756            }
4757        }
4758
4759        return new String[] { getPreferredInstructionSet() };
4760    }
4761
4762    private static String getPreferredInstructionSet() {
4763        if (sPreferredInstructionSet == null) {
4764            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4765        }
4766
4767        return sPreferredInstructionSet;
4768    }
4769
4770    private static List<String> getAllInstructionSets() {
4771        final String[] allAbis = Build.SUPPORTED_ABIS;
4772        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4773
4774        for (String abi : allAbis) {
4775            final String instructionSet = VMRuntime.getInstructionSet(abi);
4776            if (!allInstructionSets.contains(instructionSet)) {
4777                allInstructionSets.add(instructionSet);
4778            }
4779        }
4780
4781        return allInstructionSets;
4782    }
4783
4784    /**
4785     * Returns the instruction set that should be used to compile dex code. In the presence of
4786     * a native bridge this might be different than the one shared libraries use.
4787     */
4788    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4789        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4790        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4791    }
4792
4793    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4794        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4795        for (String instructionSet : instructionSets) {
4796            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4797        }
4798        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4799    }
4800
4801    @Override
4802    public void forceDexOpt(String packageName) {
4803        enforceSystemOrRoot("forceDexOpt");
4804
4805        PackageParser.Package pkg;
4806        synchronized (mPackages) {
4807            pkg = mPackages.get(packageName);
4808            if (pkg == null) {
4809                throw new IllegalArgumentException("Missing package: " + packageName);
4810            }
4811        }
4812
4813        synchronized (mInstallLock) {
4814            final String[] instructionSets = new String[] {
4815                    getPrimaryInstructionSet(pkg.applicationInfo) };
4816            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4817            if (res != DEX_OPT_PERFORMED) {
4818                throw new IllegalStateException("Failed to dexopt: " + res);
4819            }
4820        }
4821    }
4822
4823    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4824                                boolean forceDex, boolean defer, boolean inclDependencies) {
4825        HashSet<String> done;
4826        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4827            done = new HashSet<String>();
4828            done.add(pkg.packageName);
4829        } else {
4830            done = null;
4831        }
4832        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4833    }
4834
4835    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4836        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4837            Slog.w(TAG, "Unable to update from " + oldPkg.name
4838                    + " to " + newPkg.packageName
4839                    + ": old package not in system partition");
4840            return false;
4841        } else if (mPackages.get(oldPkg.name) != null) {
4842            Slog.w(TAG, "Unable to update from " + oldPkg.name
4843                    + " to " + newPkg.packageName
4844                    + ": old package still exists");
4845            return false;
4846        }
4847        return true;
4848    }
4849
4850    File getDataPathForUser(int userId) {
4851        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4852    }
4853
4854    private File getDataPathForPackage(String packageName, int userId) {
4855        /*
4856         * Until we fully support multiple users, return the directory we
4857         * previously would have. The PackageManagerTests will need to be
4858         * revised when this is changed back..
4859         */
4860        if (userId == 0) {
4861            return new File(mAppDataDir, packageName);
4862        } else {
4863            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4864                + File.separator + packageName);
4865        }
4866    }
4867
4868    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4869        int[] users = sUserManager.getUserIds();
4870        int res = mInstaller.install(packageName, uid, uid, seinfo);
4871        if (res < 0) {
4872            return res;
4873        }
4874        for (int user : users) {
4875            if (user != 0) {
4876                res = mInstaller.createUserData(packageName,
4877                        UserHandle.getUid(user, uid), user, seinfo);
4878                if (res < 0) {
4879                    return res;
4880                }
4881            }
4882        }
4883        return res;
4884    }
4885
4886    private int removeDataDirsLI(String packageName) {
4887        int[] users = sUserManager.getUserIds();
4888        int res = 0;
4889        for (int user : users) {
4890            int resInner = mInstaller.remove(packageName, user);
4891            if (resInner < 0) {
4892                res = resInner;
4893            }
4894        }
4895
4896        return res;
4897    }
4898
4899    private int deleteCodeCacheDirsLI(String packageName) {
4900        int[] users = sUserManager.getUserIds();
4901        int res = 0;
4902        for (int user : users) {
4903            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4904            if (resInner < 0) {
4905                res = resInner;
4906            }
4907        }
4908        return res;
4909    }
4910
4911    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4912            PackageParser.Package changingLib) {
4913        if (file.path != null) {
4914            usesLibraryFiles.add(file.path);
4915            return;
4916        }
4917        PackageParser.Package p = mPackages.get(file.apk);
4918        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4919            // If we are doing this while in the middle of updating a library apk,
4920            // then we need to make sure to use that new apk for determining the
4921            // dependencies here.  (We haven't yet finished committing the new apk
4922            // to the package manager state.)
4923            if (p == null || p.packageName.equals(changingLib.packageName)) {
4924                p = changingLib;
4925            }
4926        }
4927        if (p != null) {
4928            usesLibraryFiles.addAll(p.getAllCodePaths());
4929        }
4930    }
4931
4932    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4933            PackageParser.Package changingLib) throws PackageManagerException {
4934        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4935            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4936            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4937            for (int i=0; i<N; i++) {
4938                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4939                if (file == null) {
4940                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4941                            "Package " + pkg.packageName + " requires unavailable shared library "
4942                            + pkg.usesLibraries.get(i) + "; failing!");
4943                }
4944                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4945            }
4946            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4947            for (int i=0; i<N; i++) {
4948                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4949                if (file == null) {
4950                    Slog.w(TAG, "Package " + pkg.packageName
4951                            + " desires unavailable shared library "
4952                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4953                } else {
4954                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4955                }
4956            }
4957            N = usesLibraryFiles.size();
4958            if (N > 0) {
4959                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4960            } else {
4961                pkg.usesLibraryFiles = null;
4962            }
4963        }
4964    }
4965
4966    private static boolean hasString(List<String> list, List<String> which) {
4967        if (list == null) {
4968            return false;
4969        }
4970        for (int i=list.size()-1; i>=0; i--) {
4971            for (int j=which.size()-1; j>=0; j--) {
4972                if (which.get(j).equals(list.get(i))) {
4973                    return true;
4974                }
4975            }
4976        }
4977        return false;
4978    }
4979
4980    private void updateAllSharedLibrariesLPw() {
4981        for (PackageParser.Package pkg : mPackages.values()) {
4982            try {
4983                updateSharedLibrariesLPw(pkg, null);
4984            } catch (PackageManagerException e) {
4985                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4986            }
4987        }
4988    }
4989
4990    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4991            PackageParser.Package changingPkg) {
4992        ArrayList<PackageParser.Package> res = null;
4993        for (PackageParser.Package pkg : mPackages.values()) {
4994            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4995                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4996                if (res == null) {
4997                    res = new ArrayList<PackageParser.Package>();
4998                }
4999                res.add(pkg);
5000                try {
5001                    updateSharedLibrariesLPw(pkg, changingPkg);
5002                } catch (PackageManagerException e) {
5003                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5004                }
5005            }
5006        }
5007        return res;
5008    }
5009
5010    /**
5011     * Derive the value of the {@code cpuAbiOverride} based on the provided
5012     * value and an optional stored value from the package settings.
5013     */
5014    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5015        String cpuAbiOverride = null;
5016
5017        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5018            cpuAbiOverride = null;
5019        } else if (abiOverride != null) {
5020            cpuAbiOverride = abiOverride;
5021        } else if (settings != null) {
5022            cpuAbiOverride = settings.cpuAbiOverrideString;
5023        }
5024
5025        return cpuAbiOverride;
5026    }
5027
5028    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5029            int scanMode, long currentTime, UserHandle user)
5030            throws PackageManagerException {
5031        final File scanFile = new File(pkg.codePath);
5032        if (pkg.applicationInfo.getCodePath() == null ||
5033                pkg.applicationInfo.getResourcePath() == null) {
5034            // Bail out. The resource and code paths haven't been set.
5035            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5036                    "Code and resource paths haven't been set correctly");
5037        }
5038
5039        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5040            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5041        }
5042
5043        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5044            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5045        }
5046
5047        if (mCustomResolverComponentName != null &&
5048                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5049            setUpCustomResolverActivity(pkg);
5050        }
5051
5052        if (pkg.packageName.equals("android")) {
5053            synchronized (mPackages) {
5054                if (mAndroidApplication != null) {
5055                    Slog.w(TAG, "*************************************************");
5056                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5057                    Slog.w(TAG, " file=" + scanFile);
5058                    Slog.w(TAG, "*************************************************");
5059                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5060                            "Core android package being redefined.  Skipping.");
5061                }
5062
5063                // Set up information for our fall-back user intent resolution activity.
5064                mPlatformPackage = pkg;
5065                pkg.mVersionCode = mSdkVersion;
5066                mAndroidApplication = pkg.applicationInfo;
5067
5068                if (!mResolverReplaced) {
5069                    mResolveActivity.applicationInfo = mAndroidApplication;
5070                    mResolveActivity.name = ResolverActivity.class.getName();
5071                    mResolveActivity.packageName = mAndroidApplication.packageName;
5072                    mResolveActivity.processName = "system:ui";
5073                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5074                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5075                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5076                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5077                    mResolveActivity.exported = true;
5078                    mResolveActivity.enabled = true;
5079                    mResolveInfo.activityInfo = mResolveActivity;
5080                    mResolveInfo.priority = 0;
5081                    mResolveInfo.preferredOrder = 0;
5082                    mResolveInfo.match = 0;
5083                    mResolveComponentName = new ComponentName(
5084                            mAndroidApplication.packageName, mResolveActivity.name);
5085                }
5086            }
5087        }
5088
5089        if (DEBUG_PACKAGE_SCANNING) {
5090            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5091                Log.d(TAG, "Scanning package " + pkg.packageName);
5092        }
5093
5094        if (mPackages.containsKey(pkg.packageName)
5095                || mSharedLibraries.containsKey(pkg.packageName)) {
5096            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5097                    "Application package " + pkg.packageName
5098                    + " already installed.  Skipping duplicate.");
5099        }
5100
5101        // Initialize package source and resource directories
5102        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5103        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5104
5105        SharedUserSetting suid = null;
5106        PackageSetting pkgSetting = null;
5107
5108        if (!isSystemApp(pkg)) {
5109            // Only system apps can use these features.
5110            pkg.mOriginalPackages = null;
5111            pkg.mRealPackage = null;
5112            pkg.mAdoptPermissions = null;
5113        }
5114
5115        // writer
5116        synchronized (mPackages) {
5117            if (pkg.mSharedUserId != null) {
5118                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5119                if (suid == null) {
5120                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5121                            "Creating application package " + pkg.packageName
5122                            + " for shared user failed");
5123                }
5124                if (DEBUG_PACKAGE_SCANNING) {
5125                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5126                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5127                                + "): packages=" + suid.packages);
5128                }
5129            }
5130
5131            // Check if we are renaming from an original package name.
5132            PackageSetting origPackage = null;
5133            String realName = null;
5134            if (pkg.mOriginalPackages != null) {
5135                // This package may need to be renamed to a previously
5136                // installed name.  Let's check on that...
5137                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5138                if (pkg.mOriginalPackages.contains(renamed)) {
5139                    // This package had originally been installed as the
5140                    // original name, and we have already taken care of
5141                    // transitioning to the new one.  Just update the new
5142                    // one to continue using the old name.
5143                    realName = pkg.mRealPackage;
5144                    if (!pkg.packageName.equals(renamed)) {
5145                        // Callers into this function may have already taken
5146                        // care of renaming the package; only do it here if
5147                        // it is not already done.
5148                        pkg.setPackageName(renamed);
5149                    }
5150
5151                } else {
5152                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5153                        if ((origPackage = mSettings.peekPackageLPr(
5154                                pkg.mOriginalPackages.get(i))) != null) {
5155                            // We do have the package already installed under its
5156                            // original name...  should we use it?
5157                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5158                                // New package is not compatible with original.
5159                                origPackage = null;
5160                                continue;
5161                            } else if (origPackage.sharedUser != null) {
5162                                // Make sure uid is compatible between packages.
5163                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5164                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5165                                            + " to " + pkg.packageName + ": old uid "
5166                                            + origPackage.sharedUser.name
5167                                            + " differs from " + pkg.mSharedUserId);
5168                                    origPackage = null;
5169                                    continue;
5170                                }
5171                            } else {
5172                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5173                                        + pkg.packageName + " to old name " + origPackage.name);
5174                            }
5175                            break;
5176                        }
5177                    }
5178                }
5179            }
5180
5181            if (mTransferedPackages.contains(pkg.packageName)) {
5182                Slog.w(TAG, "Package " + pkg.packageName
5183                        + " was transferred to another, but its .apk remains");
5184            }
5185
5186            // Just create the setting, don't add it yet. For already existing packages
5187            // the PkgSetting exists already and doesn't have to be created.
5188            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5189                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5190                    pkg.applicationInfo.primaryCpuAbi,
5191                    pkg.applicationInfo.secondaryCpuAbi,
5192                    pkg.applicationInfo.flags, user, false);
5193            if (pkgSetting == null) {
5194                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5195                        "Creating application package " + pkg.packageName + " failed");
5196            }
5197
5198            if (pkgSetting.origPackage != null) {
5199                // If we are first transitioning from an original package,
5200                // fix up the new package's name now.  We need to do this after
5201                // looking up the package under its new name, so getPackageLP
5202                // can take care of fiddling things correctly.
5203                pkg.setPackageName(origPackage.name);
5204
5205                // File a report about this.
5206                String msg = "New package " + pkgSetting.realName
5207                        + " renamed to replace old package " + pkgSetting.name;
5208                reportSettingsProblem(Log.WARN, msg);
5209
5210                // Make a note of it.
5211                mTransferedPackages.add(origPackage.name);
5212
5213                // No longer need to retain this.
5214                pkgSetting.origPackage = null;
5215            }
5216
5217            if (realName != null) {
5218                // Make a note of it.
5219                mTransferedPackages.add(pkg.packageName);
5220            }
5221
5222            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5223                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5224            }
5225
5226            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5227                // Check all shared libraries and map to their actual file path.
5228                // We only do this here for apps not on a system dir, because those
5229                // are the only ones that can fail an install due to this.  We
5230                // will take care of the system apps by updating all of their
5231                // library paths after the scan is done.
5232                updateSharedLibrariesLPw(pkg, null);
5233            }
5234
5235            if (mFoundPolicyFile) {
5236                SELinuxMMAC.assignSeinfoValue(pkg);
5237            }
5238
5239            pkg.applicationInfo.uid = pkgSetting.appId;
5240            pkg.mExtras = pkgSetting;
5241            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5242                try {
5243                    verifySignaturesLP(pkgSetting, pkg);
5244                } catch (PackageManagerException e) {
5245                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5246                        throw e;
5247                    }
5248                    // The signature has changed, but this package is in the system
5249                    // image...  let's recover!
5250                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5251                    // However...  if this package is part of a shared user, but it
5252                    // doesn't match the signature of the shared user, let's fail.
5253                    // What this means is that you can't change the signatures
5254                    // associated with an overall shared user, which doesn't seem all
5255                    // that unreasonable.
5256                    if (pkgSetting.sharedUser != null) {
5257                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5258                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5259                            throw new PackageManagerException(
5260                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5261                                            "Signature mismatch for shared user : "
5262                                            + pkgSetting.sharedUser);
5263                        }
5264                    }
5265                    // File a report about this.
5266                    String msg = "System package " + pkg.packageName
5267                        + " signature changed; retaining data.";
5268                    reportSettingsProblem(Log.WARN, msg);
5269                }
5270            } else {
5271                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5272                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5273                            + pkg.packageName + " upgrade keys do not match the "
5274                            + "previously installed version");
5275                } else {
5276                    // signatures may have changed as result of upgrade
5277                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5278                }
5279            }
5280            // Verify that this new package doesn't have any content providers
5281            // that conflict with existing packages.  Only do this if the
5282            // package isn't already installed, since we don't want to break
5283            // things that are installed.
5284            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5285                final int N = pkg.providers.size();
5286                int i;
5287                for (i=0; i<N; i++) {
5288                    PackageParser.Provider p = pkg.providers.get(i);
5289                    if (p.info.authority != null) {
5290                        String names[] = p.info.authority.split(";");
5291                        for (int j = 0; j < names.length; j++) {
5292                            if (mProvidersByAuthority.containsKey(names[j])) {
5293                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5294                                final String otherPackageName =
5295                                        ((other != null && other.getComponentName() != null) ?
5296                                                other.getComponentName().getPackageName() : "?");
5297                                throw new PackageManagerException(
5298                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5299                                                "Can't install because provider name " + names[j]
5300                                                + " (in package " + pkg.applicationInfo.packageName
5301                                                + ") is already used by " + otherPackageName);
5302                            }
5303                        }
5304                    }
5305                }
5306            }
5307
5308            if (pkg.mAdoptPermissions != null) {
5309                // This package wants to adopt ownership of permissions from
5310                // another package.
5311                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5312                    final String origName = pkg.mAdoptPermissions.get(i);
5313                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5314                    if (orig != null) {
5315                        if (verifyPackageUpdateLPr(orig, pkg)) {
5316                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5317                                    + pkg.packageName);
5318                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5319                        }
5320                    }
5321                }
5322            }
5323        }
5324
5325        final String pkgName = pkg.packageName;
5326
5327        final long scanFileTime = scanFile.lastModified();
5328        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5329        pkg.applicationInfo.processName = fixProcessName(
5330                pkg.applicationInfo.packageName,
5331                pkg.applicationInfo.processName,
5332                pkg.applicationInfo.uid);
5333
5334        File dataPath;
5335        if (mPlatformPackage == pkg) {
5336            // The system package is special.
5337            dataPath = new File (Environment.getDataDirectory(), "system");
5338            pkg.applicationInfo.dataDir = dataPath.getPath();
5339
5340        } else {
5341            // This is a normal package, need to make its data directory.
5342            dataPath = getDataPathForPackage(pkg.packageName, 0);
5343
5344            boolean uidError = false;
5345
5346            if (dataPath.exists()) {
5347                int currentUid = 0;
5348                try {
5349                    StructStat stat = Os.stat(dataPath.getPath());
5350                    currentUid = stat.st_uid;
5351                } catch (ErrnoException e) {
5352                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5353                }
5354
5355                // If we have mismatched owners for the data path, we have a problem.
5356                if (currentUid != pkg.applicationInfo.uid) {
5357                    boolean recovered = false;
5358                    if (currentUid == 0) {
5359                        // The directory somehow became owned by root.  Wow.
5360                        // This is probably because the system was stopped while
5361                        // installd was in the middle of messing with its libs
5362                        // directory.  Ask installd to fix that.
5363                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5364                                pkg.applicationInfo.uid);
5365                        if (ret >= 0) {
5366                            recovered = true;
5367                            String msg = "Package " + pkg.packageName
5368                                    + " unexpectedly changed to uid 0; recovered to " +
5369                                    + pkg.applicationInfo.uid;
5370                            reportSettingsProblem(Log.WARN, msg);
5371                        }
5372                    }
5373                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5374                            || (scanMode&SCAN_BOOTING) != 0)) {
5375                        // If this is a system app, we can at least delete its
5376                        // current data so the application will still work.
5377                        int ret = removeDataDirsLI(pkgName);
5378                        if (ret >= 0) {
5379                            // TODO: Kill the processes first
5380                            // Old data gone!
5381                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5382                                    ? "System package " : "Third party package ";
5383                            String msg = prefix + pkg.packageName
5384                                    + " has changed from uid: "
5385                                    + currentUid + " to "
5386                                    + pkg.applicationInfo.uid + "; old data erased";
5387                            reportSettingsProblem(Log.WARN, msg);
5388                            recovered = true;
5389
5390                            // And now re-install the app.
5391                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5392                                                   pkg.applicationInfo.seinfo);
5393                            if (ret == -1) {
5394                                // Ack should not happen!
5395                                msg = prefix + pkg.packageName
5396                                        + " could not have data directory re-created after delete.";
5397                                reportSettingsProblem(Log.WARN, msg);
5398                                throw new PackageManagerException(
5399                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5400                            }
5401                        }
5402                        if (!recovered) {
5403                            mHasSystemUidErrors = true;
5404                        }
5405                    } else if (!recovered) {
5406                        // If we allow this install to proceed, we will be broken.
5407                        // Abort, abort!
5408                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5409                                "scanPackageLI");
5410                    }
5411                    if (!recovered) {
5412                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5413                            + pkg.applicationInfo.uid + "/fs_"
5414                            + currentUid;
5415                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5416                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5417                        String msg = "Package " + pkg.packageName
5418                                + " has mismatched uid: "
5419                                + currentUid + " on disk, "
5420                                + pkg.applicationInfo.uid + " in settings";
5421                        // writer
5422                        synchronized (mPackages) {
5423                            mSettings.mReadMessages.append(msg);
5424                            mSettings.mReadMessages.append('\n');
5425                            uidError = true;
5426                            if (!pkgSetting.uidError) {
5427                                reportSettingsProblem(Log.ERROR, msg);
5428                            }
5429                        }
5430                    }
5431                }
5432                pkg.applicationInfo.dataDir = dataPath.getPath();
5433                if (mShouldRestoreconData) {
5434                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5435                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5436                                pkg.applicationInfo.uid);
5437                }
5438            } else {
5439                if (DEBUG_PACKAGE_SCANNING) {
5440                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5441                        Log.v(TAG, "Want this data dir: " + dataPath);
5442                }
5443                //invoke installer to do the actual installation
5444                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5445                                           pkg.applicationInfo.seinfo);
5446                if (ret < 0) {
5447                    // Error from installer
5448                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5449                            "Unable to create data dirs [errorCode=" + ret + "]");
5450                }
5451
5452                if (dataPath.exists()) {
5453                    pkg.applicationInfo.dataDir = dataPath.getPath();
5454                } else {
5455                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5456                    pkg.applicationInfo.dataDir = null;
5457                }
5458            }
5459
5460            pkgSetting.uidError = uidError;
5461        }
5462
5463        final String path = scanFile.getPath();
5464        final String codePath = pkg.applicationInfo.getCodePath();
5465        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5466        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5467            setBundledAppAbisAndRoots(pkg, pkgSetting);
5468
5469            // If we haven't found any native libraries for the app, check if it has
5470            // renderscript code. We'll need to force the app to 32 bit if it has
5471            // renderscript bitcode.
5472            if (pkg.applicationInfo.primaryCpuAbi == null
5473                    && pkg.applicationInfo.secondaryCpuAbi == null
5474                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5475                NativeLibraryHelper.Handle handle = null;
5476                try {
5477                    handle = NativeLibraryHelper.Handle.create(scanFile);
5478                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5479                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5480                    }
5481                } catch (IOException ioe) {
5482                    Slog.w(TAG, "Error scanning system app : " + ioe);
5483                } finally {
5484                    IoUtils.closeQuietly(handle);
5485                }
5486            }
5487
5488            setNativeLibraryPaths(pkg);
5489        } else {
5490            // TODO: We can probably be smarter about this stuff. For installed apps,
5491            // we can calculate this information at install time once and for all. For
5492            // system apps, we can probably assume that this information doesn't change
5493            // after the first boot scan. As things stand, we do lots of unnecessary work.
5494
5495            // Give ourselves some initial paths; we'll come back for another
5496            // pass once we've determined ABI below.
5497            setNativeLibraryPaths(pkg);
5498
5499            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5500            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5501            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5502
5503            NativeLibraryHelper.Handle handle = null;
5504            try {
5505                handle = NativeLibraryHelper.Handle.create(scanFile);
5506                // TODO(multiArch): This can be null for apps that didn't go through the
5507                // usual installation process. We can calculate it again, like we
5508                // do during install time.
5509                //
5510                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5511                // unnecessary.
5512                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5513
5514                // Null out the abis so that they can be recalculated.
5515                pkg.applicationInfo.primaryCpuAbi = null;
5516                pkg.applicationInfo.secondaryCpuAbi = null;
5517                if (isMultiArch(pkg.applicationInfo)) {
5518                    // Warn if we've set an abiOverride for multi-lib packages..
5519                    // By definition, we need to copy both 32 and 64 bit libraries for
5520                    // such packages.
5521                    if (pkg.cpuAbiOverride != null
5522                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5523                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5524                    }
5525
5526                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5527                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5528                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5529                        if (isAsec) {
5530                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5531                        } else {
5532                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5533                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5534                                    useIsaSpecificSubdirs);
5535                        }
5536                    }
5537
5538                    maybeThrowExceptionForMultiArchCopy(
5539                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5540
5541                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5542                        if (isAsec) {
5543                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5544                        } else {
5545                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5546                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5547                                    useIsaSpecificSubdirs);
5548                        }
5549                    }
5550
5551                    maybeThrowExceptionForMultiArchCopy(
5552                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5553
5554                    if (abi64 >= 0) {
5555                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5556                    }
5557
5558                    if (abi32 >= 0) {
5559                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5560                        if (abi64 >= 0) {
5561                            pkg.applicationInfo.secondaryCpuAbi = abi;
5562                        } else {
5563                            pkg.applicationInfo.primaryCpuAbi = abi;
5564                        }
5565                    }
5566                } else {
5567                    String[] abiList = (cpuAbiOverride != null) ?
5568                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5569
5570                    // Enable gross and lame hacks for apps that are built with old
5571                    // SDK tools. We must scan their APKs for renderscript bitcode and
5572                    // not launch them if it's present. Don't bother checking on devices
5573                    // that don't have 64 bit support.
5574                    boolean needsRenderScriptOverride = false;
5575                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5576                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5577                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5578                        needsRenderScriptOverride = true;
5579                    }
5580
5581                    final int copyRet;
5582                    if (isAsec) {
5583                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5584                    } else {
5585                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5586                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5587                    }
5588
5589                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5590                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5591                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5592                    }
5593
5594                    if (copyRet >= 0) {
5595                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5596                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5597                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5598                    } else if (needsRenderScriptOverride) {
5599                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5600                    }
5601                }
5602            } catch (IOException ioe) {
5603                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5604            } finally {
5605                IoUtils.closeQuietly(handle);
5606            }
5607
5608            // Now that we've calculated the ABIs and determined if it's an internal app,
5609            // we will go ahead and populate the nativeLibraryPath.
5610            setNativeLibraryPaths(pkg);
5611
5612            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5613            final int[] userIds = sUserManager.getUserIds();
5614            synchronized (mInstallLock) {
5615                // Create a native library symlink only if we have native libraries
5616                // and if the native libraries are 32 bit libraries. We do not provide
5617                // this symlink for 64 bit libraries.
5618                if (pkg.applicationInfo.primaryCpuAbi != null &&
5619                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5620                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5621                    for (int userId : userIds) {
5622                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5623                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5624                                    "Failed linking native library dir (user=" + userId + ")");
5625                        }
5626                    }
5627                }
5628            }
5629        }
5630
5631        // This is a special case for the "system" package, where the ABI is
5632        // dictated by the zygote configuration (and init.rc). We should keep track
5633        // of this ABI so that we can deal with "normal" applications that run under
5634        // the same UID correctly.
5635        if (mPlatformPackage == pkg) {
5636            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5637                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5638        }
5639
5640        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5641        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5642        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5643        // Copy the derived override back to the parsed package, so that we can
5644        // update the package settings accordingly.
5645        pkg.cpuAbiOverride = cpuAbiOverride;
5646
5647        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5648                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5649                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5650
5651        // Push the derived path down into PackageSettings so we know what to
5652        // clean up at uninstall time.
5653        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5654
5655        if (DEBUG_ABI_SELECTION) {
5656            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5657                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5658                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5659        }
5660
5661        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5662            // We don't do this here during boot because we can do it all
5663            // at once after scanning all existing packages.
5664            //
5665            // We also do this *before* we perform dexopt on this package, so that
5666            // we can avoid redundant dexopts, and also to make sure we've got the
5667            // code and package path correct.
5668            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5669                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5670        }
5671
5672        if ((scanMode&SCAN_NO_DEX) == 0) {
5673            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5674                    == DEX_OPT_FAILED) {
5675                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5676                    removeDataDirsLI(pkg.packageName);
5677                }
5678
5679                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5680            }
5681        }
5682
5683        if (mFactoryTest && pkg.requestedPermissions.contains(
5684                android.Manifest.permission.FACTORY_TEST)) {
5685            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5686        }
5687
5688        ArrayList<PackageParser.Package> clientLibPkgs = null;
5689
5690        // writer
5691        synchronized (mPackages) {
5692            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5693                // Only system apps can add new shared libraries.
5694                if (pkg.libraryNames != null) {
5695                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5696                        String name = pkg.libraryNames.get(i);
5697                        boolean allowed = false;
5698                        if (isUpdatedSystemApp(pkg)) {
5699                            // New library entries can only be added through the
5700                            // system image.  This is important to get rid of a lot
5701                            // of nasty edge cases: for example if we allowed a non-
5702                            // system update of the app to add a library, then uninstalling
5703                            // the update would make the library go away, and assumptions
5704                            // we made such as through app install filtering would now
5705                            // have allowed apps on the device which aren't compatible
5706                            // with it.  Better to just have the restriction here, be
5707                            // conservative, and create many fewer cases that can negatively
5708                            // impact the user experience.
5709                            final PackageSetting sysPs = mSettings
5710                                    .getDisabledSystemPkgLPr(pkg.packageName);
5711                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5712                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5713                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5714                                        allowed = true;
5715                                        allowed = true;
5716                                        break;
5717                                    }
5718                                }
5719                            }
5720                        } else {
5721                            allowed = true;
5722                        }
5723                        if (allowed) {
5724                            if (!mSharedLibraries.containsKey(name)) {
5725                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5726                            } else if (!name.equals(pkg.packageName)) {
5727                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5728                                        + name + " already exists; skipping");
5729                            }
5730                        } else {
5731                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5732                                    + name + " that is not declared on system image; skipping");
5733                        }
5734                    }
5735                    if ((scanMode&SCAN_BOOTING) == 0) {
5736                        // If we are not booting, we need to update any applications
5737                        // that are clients of our shared library.  If we are booting,
5738                        // this will all be done once the scan is complete.
5739                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5740                    }
5741                }
5742            }
5743        }
5744
5745        // We also need to dexopt any apps that are dependent on this library.  Note that
5746        // if these fail, we should abort the install since installing the library will
5747        // result in some apps being broken.
5748        if (clientLibPkgs != null) {
5749            if ((scanMode&SCAN_NO_DEX) == 0) {
5750                for (int i=0; i<clientLibPkgs.size(); i++) {
5751                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5752                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5753                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5754                            == DEX_OPT_FAILED) {
5755                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5756                            removeDataDirsLI(pkg.packageName);
5757                        }
5758
5759                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5760                                "scanPackageLI failed to dexopt clientLibPkgs");
5761                    }
5762                }
5763            }
5764        }
5765
5766        // Request the ActivityManager to kill the process(only for existing packages)
5767        // so that we do not end up in a confused state while the user is still using the older
5768        // version of the application while the new one gets installed.
5769        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5770            // If the package lives in an asec, tell everyone that the container is going
5771            // away so they can clean up any references to its resources (which would prevent
5772            // vold from being able to unmount the asec)
5773            if (isForwardLocked(pkg) || isExternal(pkg)) {
5774                if (DEBUG_INSTALL) {
5775                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5776                }
5777                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5778                final ArrayList<String> pkgList = new ArrayList<String>(1);
5779                pkgList.add(pkg.applicationInfo.packageName);
5780                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5781            }
5782
5783            // Post the request that it be killed now that the going-away broadcast is en route
5784            killApplication(pkg.applicationInfo.packageName,
5785                        pkg.applicationInfo.uid, "update pkg");
5786        }
5787
5788        // Also need to kill any apps that are dependent on the library.
5789        if (clientLibPkgs != null) {
5790            for (int i=0; i<clientLibPkgs.size(); i++) {
5791                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5792                killApplication(clientPkg.applicationInfo.packageName,
5793                        clientPkg.applicationInfo.uid, "update lib");
5794            }
5795        }
5796
5797        // writer
5798        synchronized (mPackages) {
5799            // We don't expect installation to fail beyond this point,
5800            if ((scanMode&SCAN_MONITOR) != 0) {
5801                mAppDirs.put(pkg.codePath, pkg);
5802            }
5803            // Add the new setting to mSettings
5804            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5805            // Add the new setting to mPackages
5806            mPackages.put(pkg.applicationInfo.packageName, pkg);
5807            // Make sure we don't accidentally delete its data.
5808            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5809            while (iter.hasNext()) {
5810                PackageCleanItem item = iter.next();
5811                if (pkgName.equals(item.packageName)) {
5812                    iter.remove();
5813                }
5814            }
5815
5816            // Take care of first install / last update times.
5817            if (currentTime != 0) {
5818                if (pkgSetting.firstInstallTime == 0) {
5819                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5820                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5821                    pkgSetting.lastUpdateTime = currentTime;
5822                }
5823            } else if (pkgSetting.firstInstallTime == 0) {
5824                // We need *something*.  Take time time stamp of the file.
5825                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5826            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5827                if (scanFileTime != pkgSetting.timeStamp) {
5828                    // A package on the system image has changed; consider this
5829                    // to be an update.
5830                    pkgSetting.lastUpdateTime = scanFileTime;
5831                }
5832            }
5833
5834            // Add the package's KeySets to the global KeySetManagerService
5835            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5836            try {
5837                // Old KeySetData no longer valid.
5838                ksms.removeAppKeySetDataLPw(pkg.packageName);
5839                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5840                if (pkg.mKeySetMapping != null) {
5841                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5842                            pkg.mKeySetMapping.entrySet()) {
5843                        if (entry.getValue() != null) {
5844                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5845                                                          entry.getValue(), entry.getKey());
5846                        }
5847                    }
5848                    if (pkg.mUpgradeKeySets != null) {
5849                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5850                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5851                        }
5852                    }
5853                }
5854            } catch (NullPointerException e) {
5855                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5856            } catch (IllegalArgumentException e) {
5857                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5858            }
5859
5860            int N = pkg.providers.size();
5861            StringBuilder r = null;
5862            int i;
5863            for (i=0; i<N; i++) {
5864                PackageParser.Provider p = pkg.providers.get(i);
5865                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5866                        p.info.processName, pkg.applicationInfo.uid);
5867                mProviders.addProvider(p);
5868                p.syncable = p.info.isSyncable;
5869                if (p.info.authority != null) {
5870                    String names[] = p.info.authority.split(";");
5871                    p.info.authority = null;
5872                    for (int j = 0; j < names.length; j++) {
5873                        if (j == 1 && p.syncable) {
5874                            // We only want the first authority for a provider to possibly be
5875                            // syncable, so if we already added this provider using a different
5876                            // authority clear the syncable flag. We copy the provider before
5877                            // changing it because the mProviders object contains a reference
5878                            // to a provider that we don't want to change.
5879                            // Only do this for the second authority since the resulting provider
5880                            // object can be the same for all future authorities for this provider.
5881                            p = new PackageParser.Provider(p);
5882                            p.syncable = false;
5883                        }
5884                        if (!mProvidersByAuthority.containsKey(names[j])) {
5885                            mProvidersByAuthority.put(names[j], p);
5886                            if (p.info.authority == null) {
5887                                p.info.authority = names[j];
5888                            } else {
5889                                p.info.authority = p.info.authority + ";" + names[j];
5890                            }
5891                            if (DEBUG_PACKAGE_SCANNING) {
5892                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5893                                    Log.d(TAG, "Registered content provider: " + names[j]
5894                                            + ", className = " + p.info.name + ", isSyncable = "
5895                                            + p.info.isSyncable);
5896                            }
5897                        } else {
5898                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5899                            Slog.w(TAG, "Skipping provider name " + names[j] +
5900                                    " (in package " + pkg.applicationInfo.packageName +
5901                                    "): name already used by "
5902                                    + ((other != null && other.getComponentName() != null)
5903                                            ? other.getComponentName().getPackageName() : "?"));
5904                        }
5905                    }
5906                }
5907                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5908                    if (r == null) {
5909                        r = new StringBuilder(256);
5910                    } else {
5911                        r.append(' ');
5912                    }
5913                    r.append(p.info.name);
5914                }
5915            }
5916            if (r != null) {
5917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5918            }
5919
5920            N = pkg.services.size();
5921            r = null;
5922            for (i=0; i<N; i++) {
5923                PackageParser.Service s = pkg.services.get(i);
5924                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5925                        s.info.processName, pkg.applicationInfo.uid);
5926                mServices.addService(s);
5927                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5928                    if (r == null) {
5929                        r = new StringBuilder(256);
5930                    } else {
5931                        r.append(' ');
5932                    }
5933                    r.append(s.info.name);
5934                }
5935            }
5936            if (r != null) {
5937                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5938            }
5939
5940            N = pkg.receivers.size();
5941            r = null;
5942            for (i=0; i<N; i++) {
5943                PackageParser.Activity a = pkg.receivers.get(i);
5944                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5945                        a.info.processName, pkg.applicationInfo.uid);
5946                mReceivers.addActivity(a, "receiver");
5947                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5948                    if (r == null) {
5949                        r = new StringBuilder(256);
5950                    } else {
5951                        r.append(' ');
5952                    }
5953                    r.append(a.info.name);
5954                }
5955            }
5956            if (r != null) {
5957                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5958            }
5959
5960            N = pkg.activities.size();
5961            r = null;
5962            for (i=0; i<N; i++) {
5963                PackageParser.Activity a = pkg.activities.get(i);
5964                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5965                        a.info.processName, pkg.applicationInfo.uid);
5966                mActivities.addActivity(a, "activity");
5967                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5968                    if (r == null) {
5969                        r = new StringBuilder(256);
5970                    } else {
5971                        r.append(' ');
5972                    }
5973                    r.append(a.info.name);
5974                }
5975            }
5976            if (r != null) {
5977                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5978            }
5979
5980            N = pkg.permissionGroups.size();
5981            r = null;
5982            for (i=0; i<N; i++) {
5983                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5984                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5985                if (cur == null) {
5986                    mPermissionGroups.put(pg.info.name, pg);
5987                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5988                        if (r == null) {
5989                            r = new StringBuilder(256);
5990                        } else {
5991                            r.append(' ');
5992                        }
5993                        r.append(pg.info.name);
5994                    }
5995                } else {
5996                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5997                            + pg.info.packageName + " ignored: original from "
5998                            + cur.info.packageName);
5999                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6000                        if (r == null) {
6001                            r = new StringBuilder(256);
6002                        } else {
6003                            r.append(' ');
6004                        }
6005                        r.append("DUP:");
6006                        r.append(pg.info.name);
6007                    }
6008                }
6009            }
6010            if (r != null) {
6011                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6012            }
6013
6014            N = pkg.permissions.size();
6015            r = null;
6016            for (i=0; i<N; i++) {
6017                PackageParser.Permission p = pkg.permissions.get(i);
6018                HashMap<String, BasePermission> permissionMap =
6019                        p.tree ? mSettings.mPermissionTrees
6020                        : mSettings.mPermissions;
6021                p.group = mPermissionGroups.get(p.info.group);
6022                if (p.info.group == null || p.group != null) {
6023                    BasePermission bp = permissionMap.get(p.info.name);
6024                    if (bp == null) {
6025                        bp = new BasePermission(p.info.name, p.info.packageName,
6026                                BasePermission.TYPE_NORMAL);
6027                        permissionMap.put(p.info.name, bp);
6028                    }
6029                    if (bp.perm == null) {
6030                        if (bp.sourcePackage != null
6031                                && !bp.sourcePackage.equals(p.info.packageName)) {
6032                            // If this is a permission that was formerly defined by a non-system
6033                            // app, but is now defined by a system app (following an upgrade),
6034                            // discard the previous declaration and consider the system's to be
6035                            // canonical.
6036                            if (isSystemApp(p.owner)) {
6037                                String msg = "New decl " + p.owner + " of permission  "
6038                                        + p.info.name + " is system";
6039                                reportSettingsProblem(Log.WARN, msg);
6040                                bp.sourcePackage = null;
6041                            }
6042                        }
6043                        if (bp.sourcePackage == null
6044                                || bp.sourcePackage.equals(p.info.packageName)) {
6045                            BasePermission tree = findPermissionTreeLP(p.info.name);
6046                            if (tree == null
6047                                    || tree.sourcePackage.equals(p.info.packageName)) {
6048                                bp.packageSetting = pkgSetting;
6049                                bp.perm = p;
6050                                bp.uid = pkg.applicationInfo.uid;
6051                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6052                                    if (r == null) {
6053                                        r = new StringBuilder(256);
6054                                    } else {
6055                                        r.append(' ');
6056                                    }
6057                                    r.append(p.info.name);
6058                                }
6059                            } else {
6060                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6061                                        + p.info.packageName + " ignored: base tree "
6062                                        + tree.name + " is from package "
6063                                        + tree.sourcePackage);
6064                            }
6065                        } else {
6066                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6067                                    + p.info.packageName + " ignored: original from "
6068                                    + bp.sourcePackage);
6069                        }
6070                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6071                        if (r == null) {
6072                            r = new StringBuilder(256);
6073                        } else {
6074                            r.append(' ');
6075                        }
6076                        r.append("DUP:");
6077                        r.append(p.info.name);
6078                    }
6079                    if (bp.perm == p) {
6080                        bp.protectionLevel = p.info.protectionLevel;
6081                    }
6082                } else {
6083                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6084                            + p.info.packageName + " ignored: no group "
6085                            + p.group);
6086                }
6087            }
6088            if (r != null) {
6089                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6090            }
6091
6092            N = pkg.instrumentation.size();
6093            r = null;
6094            for (i=0; i<N; i++) {
6095                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6096                a.info.packageName = pkg.applicationInfo.packageName;
6097                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6098                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6099                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6100                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6101                a.info.dataDir = pkg.applicationInfo.dataDir;
6102
6103                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6104                // need other information about the application, like the ABI and what not ?
6105                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6106                mInstrumentation.put(a.getComponentName(), a);
6107                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6108                    if (r == null) {
6109                        r = new StringBuilder(256);
6110                    } else {
6111                        r.append(' ');
6112                    }
6113                    r.append(a.info.name);
6114                }
6115            }
6116            if (r != null) {
6117                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6118            }
6119
6120            if (pkg.protectedBroadcasts != null) {
6121                N = pkg.protectedBroadcasts.size();
6122                for (i=0; i<N; i++) {
6123                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6124                }
6125            }
6126
6127            pkgSetting.setTimeStamp(scanFileTime);
6128
6129            // Create idmap files for pairs of (packages, overlay packages).
6130            // Note: "android", ie framework-res.apk, is handled by native layers.
6131            if (pkg.mOverlayTarget != null) {
6132                // This is an overlay package.
6133                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6134                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6135                        mOverlays.put(pkg.mOverlayTarget,
6136                                new HashMap<String, PackageParser.Package>());
6137                    }
6138                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6139                    map.put(pkg.packageName, pkg);
6140                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6141                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6142                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6143                                "scanPackageLI failed to createIdmap");
6144                    }
6145                }
6146            } else if (mOverlays.containsKey(pkg.packageName) &&
6147                    !pkg.packageName.equals("android")) {
6148                // This is a regular package, with one or more known overlay packages.
6149                createIdmapsForPackageLI(pkg);
6150            }
6151        }
6152
6153        return pkg;
6154    }
6155
6156    /**
6157     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6158     * i.e, so that all packages can be run inside a single process if required.
6159     *
6160     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6161     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6162     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6163     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6164     * updating a package that belongs to a shared user.
6165     *
6166     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6167     * adds unnecessary complexity.
6168     */
6169    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6170            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6171        String requiredInstructionSet = null;
6172        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6173            requiredInstructionSet = VMRuntime.getInstructionSet(
6174                     scannedPackage.applicationInfo.primaryCpuAbi);
6175        }
6176
6177        PackageSetting requirer = null;
6178        for (PackageSetting ps : packagesForUser) {
6179            // If packagesForUser contains scannedPackage, we skip it. This will happen
6180            // when scannedPackage is an update of an existing package. Without this check,
6181            // we will never be able to change the ABI of any package belonging to a shared
6182            // user, even if it's compatible with other packages.
6183            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6184                if (ps.primaryCpuAbiString == null) {
6185                    continue;
6186                }
6187
6188                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6189                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6190                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6191                    // this but there's not much we can do.
6192                    String errorMessage = "Instruction set mismatch, "
6193                            + ((requirer == null) ? "[caller]" : requirer)
6194                            + " requires " + requiredInstructionSet + " whereas " + ps
6195                            + " requires " + instructionSet;
6196                    Slog.w(TAG, errorMessage);
6197                }
6198
6199                if (requiredInstructionSet == null) {
6200                    requiredInstructionSet = instructionSet;
6201                    requirer = ps;
6202                }
6203            }
6204        }
6205
6206        if (requiredInstructionSet != null) {
6207            String adjustedAbi;
6208            if (requirer != null) {
6209                // requirer != null implies that either scannedPackage was null or that scannedPackage
6210                // did not require an ABI, in which case we have to adjust scannedPackage to match
6211                // the ABI of the set (which is the same as requirer's ABI)
6212                adjustedAbi = requirer.primaryCpuAbiString;
6213                if (scannedPackage != null) {
6214                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6215                }
6216            } else {
6217                // requirer == null implies that we're updating all ABIs in the set to
6218                // match scannedPackage.
6219                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6220            }
6221
6222            for (PackageSetting ps : packagesForUser) {
6223                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6224                    if (ps.primaryCpuAbiString != null) {
6225                        continue;
6226                    }
6227
6228                    ps.primaryCpuAbiString = adjustedAbi;
6229                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6230                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6231                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6232
6233                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6234                                deferDexOpt, true) == DEX_OPT_FAILED) {
6235                            ps.primaryCpuAbiString = null;
6236                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6237                            return;
6238                        } else {
6239                            mInstaller.rmdex(ps.codePathString,
6240                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6241                        }
6242                    }
6243                }
6244            }
6245        }
6246    }
6247
6248    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6249        synchronized (mPackages) {
6250            mResolverReplaced = true;
6251            // Set up information for custom user intent resolution activity.
6252            mResolveActivity.applicationInfo = pkg.applicationInfo;
6253            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6254            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6255            mResolveActivity.processName = null;
6256            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6257            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6258                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6259            mResolveActivity.theme = 0;
6260            mResolveActivity.exported = true;
6261            mResolveActivity.enabled = true;
6262            mResolveInfo.activityInfo = mResolveActivity;
6263            mResolveInfo.priority = 0;
6264            mResolveInfo.preferredOrder = 0;
6265            mResolveInfo.match = 0;
6266            mResolveComponentName = mCustomResolverComponentName;
6267            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6268                    mResolveComponentName);
6269        }
6270    }
6271
6272    private static String calculateBundledApkRoot(final String codePathString) {
6273        final File codePath = new File(codePathString);
6274        final File codeRoot;
6275        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6276            codeRoot = Environment.getRootDirectory();
6277        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6278            codeRoot = Environment.getOemDirectory();
6279        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6280            codeRoot = Environment.getVendorDirectory();
6281        } else {
6282            // Unrecognized code path; take its top real segment as the apk root:
6283            // e.g. /something/app/blah.apk => /something
6284            try {
6285                File f = codePath.getCanonicalFile();
6286                File parent = f.getParentFile();    // non-null because codePath is a file
6287                File tmp;
6288                while ((tmp = parent.getParentFile()) != null) {
6289                    f = parent;
6290                    parent = tmp;
6291                }
6292                codeRoot = f;
6293                Slog.w(TAG, "Unrecognized code path "
6294                        + codePath + " - using " + codeRoot);
6295            } catch (IOException e) {
6296                // Can't canonicalize the code path -- shenanigans?
6297                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6298                return Environment.getRootDirectory().getPath();
6299            }
6300        }
6301        return codeRoot.getPath();
6302    }
6303
6304    /**
6305     * Derive and set the location of native libraries for the given package,
6306     * which varies depending on where and how the package was installed.
6307     */
6308    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6309        final ApplicationInfo info = pkg.applicationInfo;
6310        final String codePath = pkg.codePath;
6311        final File codeFile = new File(codePath);
6312        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6313        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6314
6315        info.nativeLibraryRootDir = null;
6316        info.nativeLibraryRootRequiresIsa = false;
6317        info.nativeLibraryDir = null;
6318        info.secondaryNativeLibraryDir = null;
6319
6320        if (isApkFile(codeFile)) {
6321            // Monolithic install
6322            if (bundledApp) {
6323                // If "/system/lib64/apkname" exists, assume that is the per-package
6324                // native library directory to use; otherwise use "/system/lib/apkname".
6325                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6326                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6327                        getPrimaryInstructionSet(info));
6328
6329                // This is a bundled system app so choose the path based on the ABI.
6330                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6331                // is just the default path.
6332                final String apkName = deriveCodePathName(codePath);
6333                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6334                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6335                        apkName).getAbsolutePath();
6336
6337                if (info.secondaryCpuAbi != null) {
6338                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6339                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6340                            secondaryLibDir, apkName).getAbsolutePath();
6341                }
6342            } else if (asecApp) {
6343                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6344                        .getAbsolutePath();
6345            } else {
6346                final String apkName = deriveCodePathName(codePath);
6347                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6348                        .getAbsolutePath();
6349            }
6350
6351            info.nativeLibraryRootRequiresIsa = false;
6352            info.nativeLibraryDir = info.nativeLibraryRootDir;
6353        } else {
6354            // Cluster install
6355            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6356            info.nativeLibraryRootRequiresIsa = true;
6357
6358            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6359                    getPrimaryInstructionSet(info)).getAbsolutePath();
6360
6361            if (info.secondaryCpuAbi != null) {
6362                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6363                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6364            }
6365        }
6366    }
6367
6368    /**
6369     * Calculate the abis and roots for a bundled app. These can uniquely
6370     * be determined from the contents of the system partition, i.e whether
6371     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6372     * of this information, and instead assume that the system was built
6373     * sensibly.
6374     */
6375    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6376                                           PackageSetting pkgSetting) {
6377        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6378
6379        // If "/system/lib64/apkname" exists, assume that is the per-package
6380        // native library directory to use; otherwise use "/system/lib/apkname".
6381        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6382        setBundledAppAbi(pkg, apkRoot, apkName);
6383        // pkgSetting might be null during rescan following uninstall of updates
6384        // to a bundled app, so accommodate that possibility.  The settings in
6385        // that case will be established later from the parsed package.
6386        //
6387        // If the settings aren't null, sync them up with what we've just derived.
6388        // note that apkRoot isn't stored in the package settings.
6389        if (pkgSetting != null) {
6390            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6391            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6392        }
6393    }
6394
6395    /**
6396     * Deduces the ABI of a bundled app and sets the relevant fields on the
6397     * parsed pkg object.
6398     *
6399     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6400     *        under which system libraries are installed.
6401     * @param apkName the name of the installed package.
6402     */
6403    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6404        final File codeFile = new File(pkg.codePath);
6405
6406        final boolean has64BitLibs;
6407        final boolean has32BitLibs;
6408        if (isApkFile(codeFile)) {
6409            // Monolithic install
6410            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6411            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6412        } else {
6413            // Cluster install
6414            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6415            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6416                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6417                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6418                has64BitLibs = (new File(rootDir, isa)).exists();
6419            } else {
6420                has64BitLibs = false;
6421            }
6422            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6423                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6424                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6425                has32BitLibs = (new File(rootDir, isa)).exists();
6426            } else {
6427                has32BitLibs = false;
6428            }
6429        }
6430
6431        if (has64BitLibs && !has32BitLibs) {
6432            // The package has 64 bit libs, but not 32 bit libs. Its primary
6433            // ABI should be 64 bit. We can safely assume here that the bundled
6434            // native libraries correspond to the most preferred ABI in the list.
6435
6436            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6437            pkg.applicationInfo.secondaryCpuAbi = null;
6438        } else if (has32BitLibs && !has64BitLibs) {
6439            // The package has 32 bit libs but not 64 bit libs. Its primary
6440            // ABI should be 32 bit.
6441
6442            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6443            pkg.applicationInfo.secondaryCpuAbi = null;
6444        } else if (has32BitLibs && has64BitLibs) {
6445            // The application has both 64 and 32 bit bundled libraries. We check
6446            // here that the app declares multiArch support, and warn if it doesn't.
6447            //
6448            // We will be lenient here and record both ABIs. The primary will be the
6449            // ABI that's higher on the list, i.e, a device that's configured to prefer
6450            // 64 bit apps will see a 64 bit primary ABI,
6451
6452            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6453                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6454            }
6455
6456            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6457                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6458                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6459            } else {
6460                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6461                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6462            }
6463        } else {
6464            pkg.applicationInfo.primaryCpuAbi = null;
6465            pkg.applicationInfo.secondaryCpuAbi = null;
6466        }
6467    }
6468
6469    private void killApplication(String pkgName, int appId, String reason) {
6470        // Request the ActivityManager to kill the process(only for existing packages)
6471        // so that we do not end up in a confused state while the user is still using the older
6472        // version of the application while the new one gets installed.
6473        IActivityManager am = ActivityManagerNative.getDefault();
6474        if (am != null) {
6475            try {
6476                am.killApplicationWithAppId(pkgName, appId, reason);
6477            } catch (RemoteException e) {
6478            }
6479        }
6480    }
6481
6482    void removePackageLI(PackageSetting ps, boolean chatty) {
6483        if (DEBUG_INSTALL) {
6484            if (chatty)
6485                Log.d(TAG, "Removing package " + ps.name);
6486        }
6487
6488        // writer
6489        synchronized (mPackages) {
6490            mPackages.remove(ps.name);
6491            if (ps.codePathString != null) {
6492                mAppDirs.remove(ps.codePathString);
6493            }
6494
6495            final PackageParser.Package pkg = ps.pkg;
6496            if (pkg != null) {
6497                cleanPackageDataStructuresLILPw(pkg, chatty);
6498            }
6499        }
6500    }
6501
6502    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6503        if (DEBUG_INSTALL) {
6504            if (chatty)
6505                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6506        }
6507
6508        // writer
6509        synchronized (mPackages) {
6510            mPackages.remove(pkg.applicationInfo.packageName);
6511            if (pkg.codePath != null) {
6512                mAppDirs.remove(pkg.codePath);
6513            }
6514            cleanPackageDataStructuresLILPw(pkg, chatty);
6515        }
6516    }
6517
6518    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6519        int N = pkg.providers.size();
6520        StringBuilder r = null;
6521        int i;
6522        for (i=0; i<N; i++) {
6523            PackageParser.Provider p = pkg.providers.get(i);
6524            mProviders.removeProvider(p);
6525            if (p.info.authority == null) {
6526
6527                /* There was another ContentProvider with this authority when
6528                 * this app was installed so this authority is null,
6529                 * Ignore it as we don't have to unregister the provider.
6530                 */
6531                continue;
6532            }
6533            String names[] = p.info.authority.split(";");
6534            for (int j = 0; j < names.length; j++) {
6535                if (mProvidersByAuthority.get(names[j]) == p) {
6536                    mProvidersByAuthority.remove(names[j]);
6537                    if (DEBUG_REMOVE) {
6538                        if (chatty)
6539                            Log.d(TAG, "Unregistered content provider: " + names[j]
6540                                    + ", className = " + p.info.name + ", isSyncable = "
6541                                    + p.info.isSyncable);
6542                    }
6543                }
6544            }
6545            if (DEBUG_REMOVE && chatty) {
6546                if (r == null) {
6547                    r = new StringBuilder(256);
6548                } else {
6549                    r.append(' ');
6550                }
6551                r.append(p.info.name);
6552            }
6553        }
6554        if (r != null) {
6555            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6556        }
6557
6558        N = pkg.services.size();
6559        r = null;
6560        for (i=0; i<N; i++) {
6561            PackageParser.Service s = pkg.services.get(i);
6562            mServices.removeService(s);
6563            if (chatty) {
6564                if (r == null) {
6565                    r = new StringBuilder(256);
6566                } else {
6567                    r.append(' ');
6568                }
6569                r.append(s.info.name);
6570            }
6571        }
6572        if (r != null) {
6573            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6574        }
6575
6576        N = pkg.receivers.size();
6577        r = null;
6578        for (i=0; i<N; i++) {
6579            PackageParser.Activity a = pkg.receivers.get(i);
6580            mReceivers.removeActivity(a, "receiver");
6581            if (DEBUG_REMOVE && chatty) {
6582                if (r == null) {
6583                    r = new StringBuilder(256);
6584                } else {
6585                    r.append(' ');
6586                }
6587                r.append(a.info.name);
6588            }
6589        }
6590        if (r != null) {
6591            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6592        }
6593
6594        N = pkg.activities.size();
6595        r = null;
6596        for (i=0; i<N; i++) {
6597            PackageParser.Activity a = pkg.activities.get(i);
6598            mActivities.removeActivity(a, "activity");
6599            if (DEBUG_REMOVE && chatty) {
6600                if (r == null) {
6601                    r = new StringBuilder(256);
6602                } else {
6603                    r.append(' ');
6604                }
6605                r.append(a.info.name);
6606            }
6607        }
6608        if (r != null) {
6609            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6610        }
6611
6612        N = pkg.permissions.size();
6613        r = null;
6614        for (i=0; i<N; i++) {
6615            PackageParser.Permission p = pkg.permissions.get(i);
6616            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6617            if (bp == null) {
6618                bp = mSettings.mPermissionTrees.get(p.info.name);
6619            }
6620            if (bp != null && bp.perm == p) {
6621                bp.perm = null;
6622                if (DEBUG_REMOVE && chatty) {
6623                    if (r == null) {
6624                        r = new StringBuilder(256);
6625                    } else {
6626                        r.append(' ');
6627                    }
6628                    r.append(p.info.name);
6629                }
6630            }
6631            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6632                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6633                if (appOpPerms != null) {
6634                    appOpPerms.remove(pkg.packageName);
6635                }
6636            }
6637        }
6638        if (r != null) {
6639            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6640        }
6641
6642        N = pkg.requestedPermissions.size();
6643        r = null;
6644        for (i=0; i<N; i++) {
6645            String perm = pkg.requestedPermissions.get(i);
6646            BasePermission bp = mSettings.mPermissions.get(perm);
6647            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6648                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6649                if (appOpPerms != null) {
6650                    appOpPerms.remove(pkg.packageName);
6651                    if (appOpPerms.isEmpty()) {
6652                        mAppOpPermissionPackages.remove(perm);
6653                    }
6654                }
6655            }
6656        }
6657        if (r != null) {
6658            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6659        }
6660
6661        N = pkg.instrumentation.size();
6662        r = null;
6663        for (i=0; i<N; i++) {
6664            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6665            mInstrumentation.remove(a.getComponentName());
6666            if (DEBUG_REMOVE && chatty) {
6667                if (r == null) {
6668                    r = new StringBuilder(256);
6669                } else {
6670                    r.append(' ');
6671                }
6672                r.append(a.info.name);
6673            }
6674        }
6675        if (r != null) {
6676            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6677        }
6678
6679        r = null;
6680        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6681            // Only system apps can hold shared libraries.
6682            if (pkg.libraryNames != null) {
6683                for (i=0; i<pkg.libraryNames.size(); i++) {
6684                    String name = pkg.libraryNames.get(i);
6685                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6686                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6687                        mSharedLibraries.remove(name);
6688                        if (DEBUG_REMOVE && chatty) {
6689                            if (r == null) {
6690                                r = new StringBuilder(256);
6691                            } else {
6692                                r.append(' ');
6693                            }
6694                            r.append(name);
6695                        }
6696                    }
6697                }
6698            }
6699        }
6700        if (r != null) {
6701            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6702        }
6703    }
6704
6705    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6706        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6707            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6708                return true;
6709            }
6710        }
6711        return false;
6712    }
6713
6714    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6715    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6716    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6717
6718    private void updatePermissionsLPw(String changingPkg,
6719            PackageParser.Package pkgInfo, int flags) {
6720        // Make sure there are no dangling permission trees.
6721        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6722        while (it.hasNext()) {
6723            final BasePermission bp = it.next();
6724            if (bp.packageSetting == null) {
6725                // We may not yet have parsed the package, so just see if
6726                // we still know about its settings.
6727                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6728            }
6729            if (bp.packageSetting == null) {
6730                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6731                        + " from package " + bp.sourcePackage);
6732                it.remove();
6733            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6734                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6735                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6736                            + " from package " + bp.sourcePackage);
6737                    flags |= UPDATE_PERMISSIONS_ALL;
6738                    it.remove();
6739                }
6740            }
6741        }
6742
6743        // Make sure all dynamic permissions have been assigned to a package,
6744        // and make sure there are no dangling permissions.
6745        it = mSettings.mPermissions.values().iterator();
6746        while (it.hasNext()) {
6747            final BasePermission bp = it.next();
6748            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6749                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6750                        + bp.name + " pkg=" + bp.sourcePackage
6751                        + " info=" + bp.pendingInfo);
6752                if (bp.packageSetting == null && bp.pendingInfo != null) {
6753                    final BasePermission tree = findPermissionTreeLP(bp.name);
6754                    if (tree != null && tree.perm != null) {
6755                        bp.packageSetting = tree.packageSetting;
6756                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6757                                new PermissionInfo(bp.pendingInfo));
6758                        bp.perm.info.packageName = tree.perm.info.packageName;
6759                        bp.perm.info.name = bp.name;
6760                        bp.uid = tree.uid;
6761                    }
6762                }
6763            }
6764            if (bp.packageSetting == null) {
6765                // We may not yet have parsed the package, so just see if
6766                // we still know about its settings.
6767                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6768            }
6769            if (bp.packageSetting == null) {
6770                Slog.w(TAG, "Removing dangling permission: " + bp.name
6771                        + " from package " + bp.sourcePackage);
6772                it.remove();
6773            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6774                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6775                    Slog.i(TAG, "Removing old permission: " + bp.name
6776                            + " from package " + bp.sourcePackage);
6777                    flags |= UPDATE_PERMISSIONS_ALL;
6778                    it.remove();
6779                }
6780            }
6781        }
6782
6783        // Now update the permissions for all packages, in particular
6784        // replace the granted permissions of the system packages.
6785        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6786            for (PackageParser.Package pkg : mPackages.values()) {
6787                if (pkg != pkgInfo) {
6788                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6789                }
6790            }
6791        }
6792
6793        if (pkgInfo != null) {
6794            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6795        }
6796    }
6797
6798    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6799        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6800        if (ps == null) {
6801            return;
6802        }
6803        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6804        HashSet<String> origPermissions = gp.grantedPermissions;
6805        boolean changedPermission = false;
6806
6807        if (replace) {
6808            ps.permissionsFixed = false;
6809            if (gp == ps) {
6810                origPermissions = new HashSet<String>(gp.grantedPermissions);
6811                gp.grantedPermissions.clear();
6812                gp.gids = mGlobalGids;
6813            }
6814        }
6815
6816        if (gp.gids == null) {
6817            gp.gids = mGlobalGids;
6818        }
6819
6820        final int N = pkg.requestedPermissions.size();
6821        for (int i=0; i<N; i++) {
6822            final String name = pkg.requestedPermissions.get(i);
6823            final boolean required = pkg.requestedPermissionsRequired.get(i);
6824            final BasePermission bp = mSettings.mPermissions.get(name);
6825            if (DEBUG_INSTALL) {
6826                if (gp != ps) {
6827                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6828                }
6829            }
6830
6831            if (bp == null || bp.packageSetting == null) {
6832                Slog.w(TAG, "Unknown permission " + name
6833                        + " in package " + pkg.packageName);
6834                continue;
6835            }
6836
6837            final String perm = bp.name;
6838            boolean allowed;
6839            boolean allowedSig = false;
6840            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6841                // Keep track of app op permissions.
6842                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6843                if (pkgs == null) {
6844                    pkgs = new ArraySet<>();
6845                    mAppOpPermissionPackages.put(bp.name, pkgs);
6846                }
6847                pkgs.add(pkg.packageName);
6848            }
6849            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6850            if (level == PermissionInfo.PROTECTION_NORMAL
6851                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6852                // We grant a normal or dangerous permission if any of the following
6853                // are true:
6854                // 1) The permission is required
6855                // 2) The permission is optional, but was granted in the past
6856                // 3) The permission is optional, but was requested by an
6857                //    app in /system (not /data)
6858                //
6859                // Otherwise, reject the permission.
6860                allowed = (required || origPermissions.contains(perm)
6861                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6862            } else if (bp.packageSetting == null) {
6863                // This permission is invalid; skip it.
6864                allowed = false;
6865            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6866                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6867                if (allowed) {
6868                    allowedSig = true;
6869                }
6870            } else {
6871                allowed = false;
6872            }
6873            if (DEBUG_INSTALL) {
6874                if (gp != ps) {
6875                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6876                }
6877            }
6878            if (allowed) {
6879                if (!isSystemApp(ps) && ps.permissionsFixed) {
6880                    // If this is an existing, non-system package, then
6881                    // we can't add any new permissions to it.
6882                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6883                        // Except...  if this is a permission that was added
6884                        // to the platform (note: need to only do this when
6885                        // updating the platform).
6886                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6887                    }
6888                }
6889                if (allowed) {
6890                    if (!gp.grantedPermissions.contains(perm)) {
6891                        changedPermission = true;
6892                        gp.grantedPermissions.add(perm);
6893                        gp.gids = appendInts(gp.gids, bp.gids);
6894                    } else if (!ps.haveGids) {
6895                        gp.gids = appendInts(gp.gids, bp.gids);
6896                    }
6897                } else {
6898                    Slog.w(TAG, "Not granting permission " + perm
6899                            + " to package " + pkg.packageName
6900                            + " because it was previously installed without");
6901                }
6902            } else {
6903                if (gp.grantedPermissions.remove(perm)) {
6904                    changedPermission = true;
6905                    gp.gids = removeInts(gp.gids, bp.gids);
6906                    Slog.i(TAG, "Un-granting permission " + perm
6907                            + " from package " + pkg.packageName
6908                            + " (protectionLevel=" + bp.protectionLevel
6909                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6910                            + ")");
6911                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6912                    // Don't print warning for app op permissions, since it is fine for them
6913                    // not to be granted, there is a UI for the user to decide.
6914                    Slog.w(TAG, "Not granting permission " + perm
6915                            + " to package " + pkg.packageName
6916                            + " (protectionLevel=" + bp.protectionLevel
6917                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6918                            + ")");
6919                }
6920            }
6921        }
6922
6923        if ((changedPermission || replace) && !ps.permissionsFixed &&
6924                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6925            // This is the first that we have heard about this package, so the
6926            // permissions we have now selected are fixed until explicitly
6927            // changed.
6928            ps.permissionsFixed = true;
6929        }
6930        ps.haveGids = true;
6931    }
6932
6933    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6934        boolean allowed = false;
6935        final int NP = PackageParser.NEW_PERMISSIONS.length;
6936        for (int ip=0; ip<NP; ip++) {
6937            final PackageParser.NewPermissionInfo npi
6938                    = PackageParser.NEW_PERMISSIONS[ip];
6939            if (npi.name.equals(perm)
6940                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6941                allowed = true;
6942                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6943                        + pkg.packageName);
6944                break;
6945            }
6946        }
6947        return allowed;
6948    }
6949
6950    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6951                                          BasePermission bp, HashSet<String> origPermissions) {
6952        boolean allowed;
6953        allowed = (compareSignatures(
6954                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6955                        == PackageManager.SIGNATURE_MATCH)
6956                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6957                        == PackageManager.SIGNATURE_MATCH);
6958        if (!allowed && (bp.protectionLevel
6959                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6960            if (isSystemApp(pkg)) {
6961                // For updated system applications, a system permission
6962                // is granted only if it had been defined by the original application.
6963                if (isUpdatedSystemApp(pkg)) {
6964                    final PackageSetting sysPs = mSettings
6965                            .getDisabledSystemPkgLPr(pkg.packageName);
6966                    final GrantedPermissions origGp = sysPs.sharedUser != null
6967                            ? sysPs.sharedUser : sysPs;
6968
6969                    if (origGp.grantedPermissions.contains(perm)) {
6970                        // If the original was granted this permission, we take
6971                        // that grant decision as read and propagate it to the
6972                        // update.
6973                        allowed = true;
6974                    } else {
6975                        // The system apk may have been updated with an older
6976                        // version of the one on the data partition, but which
6977                        // granted a new system permission that it didn't have
6978                        // before.  In this case we do want to allow the app to
6979                        // now get the new permission if the ancestral apk is
6980                        // privileged to get it.
6981                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6982                            for (int j=0;
6983                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6984                                if (perm.equals(
6985                                        sysPs.pkg.requestedPermissions.get(j))) {
6986                                    allowed = true;
6987                                    break;
6988                                }
6989                            }
6990                        }
6991                    }
6992                } else {
6993                    allowed = isPrivilegedApp(pkg);
6994                }
6995            }
6996        }
6997        if (!allowed && (bp.protectionLevel
6998                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6999            // For development permissions, a development permission
7000            // is granted only if it was already granted.
7001            allowed = origPermissions.contains(perm);
7002        }
7003        return allowed;
7004    }
7005
7006    final class ActivityIntentResolver
7007            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7009                boolean defaultOnly, int userId) {
7010            if (!sUserManager.exists(userId)) return null;
7011            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7012            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7013        }
7014
7015        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7016                int userId) {
7017            if (!sUserManager.exists(userId)) return null;
7018            mFlags = flags;
7019            return super.queryIntent(intent, resolvedType,
7020                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7021        }
7022
7023        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7024                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7025            if (!sUserManager.exists(userId)) return null;
7026            if (packageActivities == null) {
7027                return null;
7028            }
7029            mFlags = flags;
7030            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7031            final int N = packageActivities.size();
7032            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7033                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7034
7035            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7036            for (int i = 0; i < N; ++i) {
7037                intentFilters = packageActivities.get(i).intents;
7038                if (intentFilters != null && intentFilters.size() > 0) {
7039                    PackageParser.ActivityIntentInfo[] array =
7040                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7041                    intentFilters.toArray(array);
7042                    listCut.add(array);
7043                }
7044            }
7045            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7046        }
7047
7048        public final void addActivity(PackageParser.Activity a, String type) {
7049            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7050            mActivities.put(a.getComponentName(), a);
7051            if (DEBUG_SHOW_INFO)
7052                Log.v(
7053                TAG, "  " + type + " " +
7054                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7055            if (DEBUG_SHOW_INFO)
7056                Log.v(TAG, "    Class=" + a.info.name);
7057            final int NI = a.intents.size();
7058            for (int j=0; j<NI; j++) {
7059                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7060                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7061                    intent.setPriority(0);
7062                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7063                            + a.className + " with priority > 0, forcing to 0");
7064                }
7065                if (DEBUG_SHOW_INFO) {
7066                    Log.v(TAG, "    IntentFilter:");
7067                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7068                }
7069                if (!intent.debugCheck()) {
7070                    Log.w(TAG, "==> For Activity " + a.info.name);
7071                }
7072                addFilter(intent);
7073            }
7074        }
7075
7076        public final void removeActivity(PackageParser.Activity a, String type) {
7077            mActivities.remove(a.getComponentName());
7078            if (DEBUG_SHOW_INFO) {
7079                Log.v(TAG, "  " + type + " "
7080                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7081                                : a.info.name) + ":");
7082                Log.v(TAG, "    Class=" + a.info.name);
7083            }
7084            final int NI = a.intents.size();
7085            for (int j=0; j<NI; j++) {
7086                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7087                if (DEBUG_SHOW_INFO) {
7088                    Log.v(TAG, "    IntentFilter:");
7089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7090                }
7091                removeFilter(intent);
7092            }
7093        }
7094
7095        @Override
7096        protected boolean allowFilterResult(
7097                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7098            ActivityInfo filterAi = filter.activity.info;
7099            for (int i=dest.size()-1; i>=0; i--) {
7100                ActivityInfo destAi = dest.get(i).activityInfo;
7101                if (destAi.name == filterAi.name
7102                        && destAi.packageName == filterAi.packageName) {
7103                    return false;
7104                }
7105            }
7106            return true;
7107        }
7108
7109        @Override
7110        protected ActivityIntentInfo[] newArray(int size) {
7111            return new ActivityIntentInfo[size];
7112        }
7113
7114        @Override
7115        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7116            if (!sUserManager.exists(userId)) return true;
7117            PackageParser.Package p = filter.activity.owner;
7118            if (p != null) {
7119                PackageSetting ps = (PackageSetting)p.mExtras;
7120                if (ps != null) {
7121                    // System apps are never considered stopped for purposes of
7122                    // filtering, because there may be no way for the user to
7123                    // actually re-launch them.
7124                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7125                            && ps.getStopped(userId);
7126                }
7127            }
7128            return false;
7129        }
7130
7131        @Override
7132        protected boolean isPackageForFilter(String packageName,
7133                PackageParser.ActivityIntentInfo info) {
7134            return packageName.equals(info.activity.owner.packageName);
7135        }
7136
7137        @Override
7138        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7139                int match, int userId) {
7140            if (!sUserManager.exists(userId)) return null;
7141            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7142                return null;
7143            }
7144            final PackageParser.Activity activity = info.activity;
7145            if (mSafeMode && (activity.info.applicationInfo.flags
7146                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7147                return null;
7148            }
7149            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7150            if (ps == null) {
7151                return null;
7152            }
7153            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7154                    ps.readUserState(userId), userId);
7155            if (ai == null) {
7156                return null;
7157            }
7158            final ResolveInfo res = new ResolveInfo();
7159            res.activityInfo = ai;
7160            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7161                res.filter = info;
7162            }
7163            res.priority = info.getPriority();
7164            res.preferredOrder = activity.owner.mPreferredOrder;
7165            //System.out.println("Result: " + res.activityInfo.className +
7166            //                   " = " + res.priority);
7167            res.match = match;
7168            res.isDefault = info.hasDefault;
7169            res.labelRes = info.labelRes;
7170            res.nonLocalizedLabel = info.nonLocalizedLabel;
7171            if (userNeedsBadging(userId)) {
7172                res.noResourceId = true;
7173            } else {
7174                res.icon = info.icon;
7175            }
7176            res.system = isSystemApp(res.activityInfo.applicationInfo);
7177            return res;
7178        }
7179
7180        @Override
7181        protected void sortResults(List<ResolveInfo> results) {
7182            Collections.sort(results, mResolvePrioritySorter);
7183        }
7184
7185        @Override
7186        protected void dumpFilter(PrintWriter out, String prefix,
7187                PackageParser.ActivityIntentInfo filter) {
7188            out.print(prefix); out.print(
7189                    Integer.toHexString(System.identityHashCode(filter.activity)));
7190                    out.print(' ');
7191                    filter.activity.printComponentShortName(out);
7192                    out.print(" filter ");
7193                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7194        }
7195
7196//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7197//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7198//            final List<ResolveInfo> retList = Lists.newArrayList();
7199//            while (i.hasNext()) {
7200//                final ResolveInfo resolveInfo = i.next();
7201//                if (isEnabledLP(resolveInfo.activityInfo)) {
7202//                    retList.add(resolveInfo);
7203//                }
7204//            }
7205//            return retList;
7206//        }
7207
7208        // Keys are String (activity class name), values are Activity.
7209        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7210                = new HashMap<ComponentName, PackageParser.Activity>();
7211        private int mFlags;
7212    }
7213
7214    private final class ServiceIntentResolver
7215            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7216        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7217                boolean defaultOnly, int userId) {
7218            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7219            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7220        }
7221
7222        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7223                int userId) {
7224            if (!sUserManager.exists(userId)) return null;
7225            mFlags = flags;
7226            return super.queryIntent(intent, resolvedType,
7227                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7228        }
7229
7230        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7231                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7232            if (!sUserManager.exists(userId)) return null;
7233            if (packageServices == null) {
7234                return null;
7235            }
7236            mFlags = flags;
7237            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7238            final int N = packageServices.size();
7239            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7240                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7241
7242            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7243            for (int i = 0; i < N; ++i) {
7244                intentFilters = packageServices.get(i).intents;
7245                if (intentFilters != null && intentFilters.size() > 0) {
7246                    PackageParser.ServiceIntentInfo[] array =
7247                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7248                    intentFilters.toArray(array);
7249                    listCut.add(array);
7250                }
7251            }
7252            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7253        }
7254
7255        public final void addService(PackageParser.Service s) {
7256            mServices.put(s.getComponentName(), s);
7257            if (DEBUG_SHOW_INFO) {
7258                Log.v(TAG, "  "
7259                        + (s.info.nonLocalizedLabel != null
7260                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7261                Log.v(TAG, "    Class=" + s.info.name);
7262            }
7263            final int NI = s.intents.size();
7264            int j;
7265            for (j=0; j<NI; j++) {
7266                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7267                if (DEBUG_SHOW_INFO) {
7268                    Log.v(TAG, "    IntentFilter:");
7269                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7270                }
7271                if (!intent.debugCheck()) {
7272                    Log.w(TAG, "==> For Service " + s.info.name);
7273                }
7274                addFilter(intent);
7275            }
7276        }
7277
7278        public final void removeService(PackageParser.Service s) {
7279            mServices.remove(s.getComponentName());
7280            if (DEBUG_SHOW_INFO) {
7281                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7282                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7283                Log.v(TAG, "    Class=" + s.info.name);
7284            }
7285            final int NI = s.intents.size();
7286            int j;
7287            for (j=0; j<NI; j++) {
7288                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7289                if (DEBUG_SHOW_INFO) {
7290                    Log.v(TAG, "    IntentFilter:");
7291                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7292                }
7293                removeFilter(intent);
7294            }
7295        }
7296
7297        @Override
7298        protected boolean allowFilterResult(
7299                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7300            ServiceInfo filterSi = filter.service.info;
7301            for (int i=dest.size()-1; i>=0; i--) {
7302                ServiceInfo destAi = dest.get(i).serviceInfo;
7303                if (destAi.name == filterSi.name
7304                        && destAi.packageName == filterSi.packageName) {
7305                    return false;
7306                }
7307            }
7308            return true;
7309        }
7310
7311        @Override
7312        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7313            return new PackageParser.ServiceIntentInfo[size];
7314        }
7315
7316        @Override
7317        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7318            if (!sUserManager.exists(userId)) return true;
7319            PackageParser.Package p = filter.service.owner;
7320            if (p != null) {
7321                PackageSetting ps = (PackageSetting)p.mExtras;
7322                if (ps != null) {
7323                    // System apps are never considered stopped for purposes of
7324                    // filtering, because there may be no way for the user to
7325                    // actually re-launch them.
7326                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7327                            && ps.getStopped(userId);
7328                }
7329            }
7330            return false;
7331        }
7332
7333        @Override
7334        protected boolean isPackageForFilter(String packageName,
7335                PackageParser.ServiceIntentInfo info) {
7336            return packageName.equals(info.service.owner.packageName);
7337        }
7338
7339        @Override
7340        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7341                int match, int userId) {
7342            if (!sUserManager.exists(userId)) return null;
7343            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7344            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7345                return null;
7346            }
7347            final PackageParser.Service service = info.service;
7348            if (mSafeMode && (service.info.applicationInfo.flags
7349                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7350                return null;
7351            }
7352            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7353            if (ps == null) {
7354                return null;
7355            }
7356            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7357                    ps.readUserState(userId), userId);
7358            if (si == null) {
7359                return null;
7360            }
7361            final ResolveInfo res = new ResolveInfo();
7362            res.serviceInfo = si;
7363            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7364                res.filter = filter;
7365            }
7366            res.priority = info.getPriority();
7367            res.preferredOrder = service.owner.mPreferredOrder;
7368            //System.out.println("Result: " + res.activityInfo.className +
7369            //                   " = " + res.priority);
7370            res.match = match;
7371            res.isDefault = info.hasDefault;
7372            res.labelRes = info.labelRes;
7373            res.nonLocalizedLabel = info.nonLocalizedLabel;
7374            res.icon = info.icon;
7375            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7376            return res;
7377        }
7378
7379        @Override
7380        protected void sortResults(List<ResolveInfo> results) {
7381            Collections.sort(results, mResolvePrioritySorter);
7382        }
7383
7384        @Override
7385        protected void dumpFilter(PrintWriter out, String prefix,
7386                PackageParser.ServiceIntentInfo filter) {
7387            out.print(prefix); out.print(
7388                    Integer.toHexString(System.identityHashCode(filter.service)));
7389                    out.print(' ');
7390                    filter.service.printComponentShortName(out);
7391                    out.print(" filter ");
7392                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7393        }
7394
7395//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7396//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7397//            final List<ResolveInfo> retList = Lists.newArrayList();
7398//            while (i.hasNext()) {
7399//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7400//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7401//                    retList.add(resolveInfo);
7402//                }
7403//            }
7404//            return retList;
7405//        }
7406
7407        // Keys are String (activity class name), values are Activity.
7408        private final HashMap<ComponentName, PackageParser.Service> mServices
7409                = new HashMap<ComponentName, PackageParser.Service>();
7410        private int mFlags;
7411    };
7412
7413    private final class ProviderIntentResolver
7414            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7415        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7416                boolean defaultOnly, int userId) {
7417            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7418            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7419        }
7420
7421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7422                int userId) {
7423            if (!sUserManager.exists(userId))
7424                return null;
7425            mFlags = flags;
7426            return super.queryIntent(intent, resolvedType,
7427                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7428        }
7429
7430        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7431                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7432            if (!sUserManager.exists(userId))
7433                return null;
7434            if (packageProviders == null) {
7435                return null;
7436            }
7437            mFlags = flags;
7438            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7439            final int N = packageProviders.size();
7440            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7441                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7442
7443            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7444            for (int i = 0; i < N; ++i) {
7445                intentFilters = packageProviders.get(i).intents;
7446                if (intentFilters != null && intentFilters.size() > 0) {
7447                    PackageParser.ProviderIntentInfo[] array =
7448                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7449                    intentFilters.toArray(array);
7450                    listCut.add(array);
7451                }
7452            }
7453            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7454        }
7455
7456        public final void addProvider(PackageParser.Provider p) {
7457            if (mProviders.containsKey(p.getComponentName())) {
7458                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7459                return;
7460            }
7461
7462            mProviders.put(p.getComponentName(), p);
7463            if (DEBUG_SHOW_INFO) {
7464                Log.v(TAG, "  "
7465                        + (p.info.nonLocalizedLabel != null
7466                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7467                Log.v(TAG, "    Class=" + p.info.name);
7468            }
7469            final int NI = p.intents.size();
7470            int j;
7471            for (j = 0; j < NI; j++) {
7472                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7473                if (DEBUG_SHOW_INFO) {
7474                    Log.v(TAG, "    IntentFilter:");
7475                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7476                }
7477                if (!intent.debugCheck()) {
7478                    Log.w(TAG, "==> For Provider " + p.info.name);
7479                }
7480                addFilter(intent);
7481            }
7482        }
7483
7484        public final void removeProvider(PackageParser.Provider p) {
7485            mProviders.remove(p.getComponentName());
7486            if (DEBUG_SHOW_INFO) {
7487                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7488                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7489                Log.v(TAG, "    Class=" + p.info.name);
7490            }
7491            final int NI = p.intents.size();
7492            int j;
7493            for (j = 0; j < NI; j++) {
7494                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7495                if (DEBUG_SHOW_INFO) {
7496                    Log.v(TAG, "    IntentFilter:");
7497                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7498                }
7499                removeFilter(intent);
7500            }
7501        }
7502
7503        @Override
7504        protected boolean allowFilterResult(
7505                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7506            ProviderInfo filterPi = filter.provider.info;
7507            for (int i = dest.size() - 1; i >= 0; i--) {
7508                ProviderInfo destPi = dest.get(i).providerInfo;
7509                if (destPi.name == filterPi.name
7510                        && destPi.packageName == filterPi.packageName) {
7511                    return false;
7512                }
7513            }
7514            return true;
7515        }
7516
7517        @Override
7518        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7519            return new PackageParser.ProviderIntentInfo[size];
7520        }
7521
7522        @Override
7523        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7524            if (!sUserManager.exists(userId))
7525                return true;
7526            PackageParser.Package p = filter.provider.owner;
7527            if (p != null) {
7528                PackageSetting ps = (PackageSetting) p.mExtras;
7529                if (ps != null) {
7530                    // System apps are never considered stopped for purposes of
7531                    // filtering, because there may be no way for the user to
7532                    // actually re-launch them.
7533                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7534                            && ps.getStopped(userId);
7535                }
7536            }
7537            return false;
7538        }
7539
7540        @Override
7541        protected boolean isPackageForFilter(String packageName,
7542                PackageParser.ProviderIntentInfo info) {
7543            return packageName.equals(info.provider.owner.packageName);
7544        }
7545
7546        @Override
7547        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7548                int match, int userId) {
7549            if (!sUserManager.exists(userId))
7550                return null;
7551            final PackageParser.ProviderIntentInfo info = filter;
7552            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7553                return null;
7554            }
7555            final PackageParser.Provider provider = info.provider;
7556            if (mSafeMode && (provider.info.applicationInfo.flags
7557                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7558                return null;
7559            }
7560            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7561            if (ps == null) {
7562                return null;
7563            }
7564            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7565                    ps.readUserState(userId), userId);
7566            if (pi == null) {
7567                return null;
7568            }
7569            final ResolveInfo res = new ResolveInfo();
7570            res.providerInfo = pi;
7571            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7572                res.filter = filter;
7573            }
7574            res.priority = info.getPriority();
7575            res.preferredOrder = provider.owner.mPreferredOrder;
7576            res.match = match;
7577            res.isDefault = info.hasDefault;
7578            res.labelRes = info.labelRes;
7579            res.nonLocalizedLabel = info.nonLocalizedLabel;
7580            res.icon = info.icon;
7581            res.system = isSystemApp(res.providerInfo.applicationInfo);
7582            return res;
7583        }
7584
7585        @Override
7586        protected void sortResults(List<ResolveInfo> results) {
7587            Collections.sort(results, mResolvePrioritySorter);
7588        }
7589
7590        @Override
7591        protected void dumpFilter(PrintWriter out, String prefix,
7592                PackageParser.ProviderIntentInfo filter) {
7593            out.print(prefix);
7594            out.print(
7595                    Integer.toHexString(System.identityHashCode(filter.provider)));
7596            out.print(' ');
7597            filter.provider.printComponentShortName(out);
7598            out.print(" filter ");
7599            out.println(Integer.toHexString(System.identityHashCode(filter)));
7600        }
7601
7602        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7603                = new HashMap<ComponentName, PackageParser.Provider>();
7604        private int mFlags;
7605    };
7606
7607    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7608            new Comparator<ResolveInfo>() {
7609        public int compare(ResolveInfo r1, ResolveInfo r2) {
7610            int v1 = r1.priority;
7611            int v2 = r2.priority;
7612            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7613            if (v1 != v2) {
7614                return (v1 > v2) ? -1 : 1;
7615            }
7616            v1 = r1.preferredOrder;
7617            v2 = r2.preferredOrder;
7618            if (v1 != v2) {
7619                return (v1 > v2) ? -1 : 1;
7620            }
7621            if (r1.isDefault != r2.isDefault) {
7622                return r1.isDefault ? -1 : 1;
7623            }
7624            v1 = r1.match;
7625            v2 = r2.match;
7626            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7627            if (v1 != v2) {
7628                return (v1 > v2) ? -1 : 1;
7629            }
7630            if (r1.system != r2.system) {
7631                return r1.system ? -1 : 1;
7632            }
7633            return 0;
7634        }
7635    };
7636
7637    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7638            new Comparator<ProviderInfo>() {
7639        public int compare(ProviderInfo p1, ProviderInfo p2) {
7640            final int v1 = p1.initOrder;
7641            final int v2 = p2.initOrder;
7642            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7643        }
7644    };
7645
7646    static final void sendPackageBroadcast(String action, String pkg,
7647            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7648            int[] userIds) {
7649        IActivityManager am = ActivityManagerNative.getDefault();
7650        if (am != null) {
7651            try {
7652                if (userIds == null) {
7653                    userIds = am.getRunningUserIds();
7654                }
7655                for (int id : userIds) {
7656                    final Intent intent = new Intent(action,
7657                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7658                    if (extras != null) {
7659                        intent.putExtras(extras);
7660                    }
7661                    if (targetPkg != null) {
7662                        intent.setPackage(targetPkg);
7663                    }
7664                    // Modify the UID when posting to other users
7665                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7666                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7667                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7668                        intent.putExtra(Intent.EXTRA_UID, uid);
7669                    }
7670                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7671                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7672                    if (DEBUG_BROADCASTS) {
7673                        RuntimeException here = new RuntimeException("here");
7674                        here.fillInStackTrace();
7675                        Slog.d(TAG, "Sending to user " + id + ": "
7676                                + intent.toShortString(false, true, false, false)
7677                                + " " + intent.getExtras(), here);
7678                    }
7679                    am.broadcastIntent(null, intent, null, finishedReceiver,
7680                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7681                            finishedReceiver != null, false, id);
7682                }
7683            } catch (RemoteException ex) {
7684            }
7685        }
7686    }
7687
7688    /**
7689     * Check if the external storage media is available. This is true if there
7690     * is a mounted external storage medium or if the external storage is
7691     * emulated.
7692     */
7693    private boolean isExternalMediaAvailable() {
7694        return mMediaMounted || Environment.isExternalStorageEmulated();
7695    }
7696
7697    @Override
7698    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7699        // writer
7700        synchronized (mPackages) {
7701            if (!isExternalMediaAvailable()) {
7702                // If the external storage is no longer mounted at this point,
7703                // the caller may not have been able to delete all of this
7704                // packages files and can not delete any more.  Bail.
7705                return null;
7706            }
7707            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7708            if (lastPackage != null) {
7709                pkgs.remove(lastPackage);
7710            }
7711            if (pkgs.size() > 0) {
7712                return pkgs.get(0);
7713            }
7714        }
7715        return null;
7716    }
7717
7718    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7719        if (false) {
7720            RuntimeException here = new RuntimeException("here");
7721            here.fillInStackTrace();
7722            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7723                    + " andCode=" + andCode, here);
7724        }
7725        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7726                userId, andCode ? 1 : 0, packageName));
7727    }
7728
7729    void startCleaningPackages() {
7730        // reader
7731        synchronized (mPackages) {
7732            if (!isExternalMediaAvailable()) {
7733                return;
7734            }
7735            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7736                return;
7737            }
7738        }
7739        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7740        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7741        IActivityManager am = ActivityManagerNative.getDefault();
7742        if (am != null) {
7743            try {
7744                am.startService(null, intent, null, UserHandle.USER_OWNER);
7745            } catch (RemoteException e) {
7746            }
7747        }
7748    }
7749
7750    @Override
7751    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7752            String installerPackageName, VerificationParams verificationParams,
7753            String packageAbiOverride) {
7754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7755                null);
7756
7757        final File originFile = new File(originPath);
7758        final int uid = Binder.getCallingUid();
7759        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7760            try {
7761                if (observer != null) {
7762                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7763                }
7764            } catch (RemoteException re) {
7765            }
7766            return;
7767        }
7768
7769        UserHandle user;
7770        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7771            user = UserHandle.ALL;
7772        } else {
7773            user = new UserHandle(UserHandle.getUserId(uid));
7774        }
7775
7776        final int filteredFlags;
7777        if (uid == Process.SHELL_UID || uid == 0) {
7778            if (DEBUG_INSTALL) {
7779                Slog.v(TAG, "Install from ADB");
7780            }
7781            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7782        } else {
7783            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7784        }
7785
7786        verificationParams.setInstallerUid(uid);
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        final OriginInfo origin = new OriginInfo(originFile, null, false);
7790        msg.obj = new InstallParams(origin, observer, filteredFlags,
7791                installerPackageName, verificationParams, user, packageAbiOverride);
7792        mHandler.sendMessage(msg);
7793    }
7794
7795    void installStage(String packageName, File stagedDir, String stagedCid,
7796            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7797            String installerPackageName, int installerUid, UserHandle user) {
7798        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7799                params.referrerUri, installerUid, null);
7800
7801        final Message msg = mHandler.obtainMessage(INIT_COPY);
7802        final OriginInfo origin = new OriginInfo(stagedDir, stagedCid, true);
7803        msg.obj = new InstallParams(origin, observer, params.installFlags,
7804                installerPackageName, verifParams, user, params.abiOverride);
7805        mHandler.sendMessage(msg);
7806    }
7807
7808    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7809        Bundle extras = new Bundle(1);
7810        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7811
7812        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7813                packageName, extras, null, null, new int[] {userId});
7814        try {
7815            IActivityManager am = ActivityManagerNative.getDefault();
7816            final boolean isSystem =
7817                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7818            if (isSystem && am.isUserRunning(userId, false)) {
7819                // The just-installed/enabled app is bundled on the system, so presumed
7820                // to be able to run automatically without needing an explicit launch.
7821                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7822                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7823                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7824                        .setPackage(packageName);
7825                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7826                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7827            }
7828        } catch (RemoteException e) {
7829            // shouldn't happen
7830            Slog.w(TAG, "Unable to bootstrap installed package", e);
7831        }
7832    }
7833
7834    @Override
7835    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7836            int userId) {
7837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7838        PackageSetting pkgSetting;
7839        final int uid = Binder.getCallingUid();
7840        if (UserHandle.getUserId(uid) != userId) {
7841            mContext.enforceCallingOrSelfPermission(
7842                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7843                    "setApplicationHiddenSetting for user " + userId);
7844        }
7845
7846        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7847            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7848            return false;
7849        }
7850
7851        long callingId = Binder.clearCallingIdentity();
7852        try {
7853            boolean sendAdded = false;
7854            boolean sendRemoved = false;
7855            // writer
7856            synchronized (mPackages) {
7857                pkgSetting = mSettings.mPackages.get(packageName);
7858                if (pkgSetting == null) {
7859                    return false;
7860                }
7861                if (pkgSetting.getHidden(userId) != hidden) {
7862                    pkgSetting.setHidden(hidden, userId);
7863                    mSettings.writePackageRestrictionsLPr(userId);
7864                    if (hidden) {
7865                        sendRemoved = true;
7866                    } else {
7867                        sendAdded = true;
7868                    }
7869                }
7870            }
7871            if (sendAdded) {
7872                sendPackageAddedForUser(packageName, pkgSetting, userId);
7873                return true;
7874            }
7875            if (sendRemoved) {
7876                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7877                        "hiding pkg");
7878                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7879            }
7880        } finally {
7881            Binder.restoreCallingIdentity(callingId);
7882        }
7883        return false;
7884    }
7885
7886    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7887            int userId) {
7888        final PackageRemovedInfo info = new PackageRemovedInfo();
7889        info.removedPackage = packageName;
7890        info.removedUsers = new int[] {userId};
7891        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7892        info.sendBroadcast(false, false, false);
7893    }
7894
7895    /**
7896     * Returns true if application is not found or there was an error. Otherwise it returns
7897     * the hidden state of the package for the given user.
7898     */
7899    @Override
7900    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7902        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7903                "getApplicationHidden for user " + userId);
7904        PackageSetting pkgSetting;
7905        long callingId = Binder.clearCallingIdentity();
7906        try {
7907            // writer
7908            synchronized (mPackages) {
7909                pkgSetting = mSettings.mPackages.get(packageName);
7910                if (pkgSetting == null) {
7911                    return true;
7912                }
7913                return pkgSetting.getHidden(userId);
7914            }
7915        } finally {
7916            Binder.restoreCallingIdentity(callingId);
7917        }
7918    }
7919
7920    /**
7921     * @hide
7922     */
7923    @Override
7924    public int installExistingPackageAsUser(String packageName, int userId) {
7925        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7926                null);
7927        PackageSetting pkgSetting;
7928        final int uid = Binder.getCallingUid();
7929        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7930        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7931            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7932        }
7933
7934        long callingId = Binder.clearCallingIdentity();
7935        try {
7936            boolean sendAdded = false;
7937            Bundle extras = new Bundle(1);
7938
7939            // writer
7940            synchronized (mPackages) {
7941                pkgSetting = mSettings.mPackages.get(packageName);
7942                if (pkgSetting == null) {
7943                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7944                }
7945                if (!pkgSetting.getInstalled(userId)) {
7946                    pkgSetting.setInstalled(true, userId);
7947                    pkgSetting.setHidden(false, userId);
7948                    mSettings.writePackageRestrictionsLPr(userId);
7949                    sendAdded = true;
7950                }
7951            }
7952
7953            if (sendAdded) {
7954                sendPackageAddedForUser(packageName, pkgSetting, userId);
7955            }
7956        } finally {
7957            Binder.restoreCallingIdentity(callingId);
7958        }
7959
7960        return PackageManager.INSTALL_SUCCEEDED;
7961    }
7962
7963    boolean isUserRestricted(int userId, String restrictionKey) {
7964        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7965        if (restrictions.getBoolean(restrictionKey, false)) {
7966            Log.w(TAG, "User is restricted: " + restrictionKey);
7967            return true;
7968        }
7969        return false;
7970    }
7971
7972    @Override
7973    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7974        mContext.enforceCallingOrSelfPermission(
7975                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7976                "Only package verification agents can verify applications");
7977
7978        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7979        final PackageVerificationResponse response = new PackageVerificationResponse(
7980                verificationCode, Binder.getCallingUid());
7981        msg.arg1 = id;
7982        msg.obj = response;
7983        mHandler.sendMessage(msg);
7984    }
7985
7986    @Override
7987    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7988            long millisecondsToDelay) {
7989        mContext.enforceCallingOrSelfPermission(
7990                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7991                "Only package verification agents can extend verification timeouts");
7992
7993        final PackageVerificationState state = mPendingVerification.get(id);
7994        final PackageVerificationResponse response = new PackageVerificationResponse(
7995                verificationCodeAtTimeout, Binder.getCallingUid());
7996
7997        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7998            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7999        }
8000        if (millisecondsToDelay < 0) {
8001            millisecondsToDelay = 0;
8002        }
8003        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8004                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8005            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8006        }
8007
8008        if ((state != null) && !state.timeoutExtended()) {
8009            state.extendTimeout();
8010
8011            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8012            msg.arg1 = id;
8013            msg.obj = response;
8014            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8015        }
8016    }
8017
8018    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8019            int verificationCode, UserHandle user) {
8020        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8021        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8022        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8023        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8024        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8025
8026        mContext.sendBroadcastAsUser(intent, user,
8027                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8028    }
8029
8030    private ComponentName matchComponentForVerifier(String packageName,
8031            List<ResolveInfo> receivers) {
8032        ActivityInfo targetReceiver = null;
8033
8034        final int NR = receivers.size();
8035        for (int i = 0; i < NR; i++) {
8036            final ResolveInfo info = receivers.get(i);
8037            if (info.activityInfo == null) {
8038                continue;
8039            }
8040
8041            if (packageName.equals(info.activityInfo.packageName)) {
8042                targetReceiver = info.activityInfo;
8043                break;
8044            }
8045        }
8046
8047        if (targetReceiver == null) {
8048            return null;
8049        }
8050
8051        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8052    }
8053
8054    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8055            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8056        if (pkgInfo.verifiers.length == 0) {
8057            return null;
8058        }
8059
8060        final int N = pkgInfo.verifiers.length;
8061        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8062        for (int i = 0; i < N; i++) {
8063            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8064
8065            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8066                    receivers);
8067            if (comp == null) {
8068                continue;
8069            }
8070
8071            final int verifierUid = getUidForVerifier(verifierInfo);
8072            if (verifierUid == -1) {
8073                continue;
8074            }
8075
8076            if (DEBUG_VERIFY) {
8077                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8078                        + " with the correct signature");
8079            }
8080            sufficientVerifiers.add(comp);
8081            verificationState.addSufficientVerifier(verifierUid);
8082        }
8083
8084        return sufficientVerifiers;
8085    }
8086
8087    private int getUidForVerifier(VerifierInfo verifierInfo) {
8088        synchronized (mPackages) {
8089            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8090            if (pkg == null) {
8091                return -1;
8092            } else if (pkg.mSignatures.length != 1) {
8093                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8094                        + " has more than one signature; ignoring");
8095                return -1;
8096            }
8097
8098            /*
8099             * If the public key of the package's signature does not match
8100             * our expected public key, then this is a different package and
8101             * we should skip.
8102             */
8103
8104            final byte[] expectedPublicKey;
8105            try {
8106                final Signature verifierSig = pkg.mSignatures[0];
8107                final PublicKey publicKey = verifierSig.getPublicKey();
8108                expectedPublicKey = publicKey.getEncoded();
8109            } catch (CertificateException e) {
8110                return -1;
8111            }
8112
8113            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8114
8115            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8116                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8117                        + " does not have the expected public key; ignoring");
8118                return -1;
8119            }
8120
8121            return pkg.applicationInfo.uid;
8122        }
8123    }
8124
8125    @Override
8126    public void finishPackageInstall(int token) {
8127        enforceSystemOrRoot("Only the system is allowed to finish installs");
8128
8129        if (DEBUG_INSTALL) {
8130            Slog.v(TAG, "BM finishing package install for " + token);
8131        }
8132
8133        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8134        mHandler.sendMessage(msg);
8135    }
8136
8137    /**
8138     * Get the verification agent timeout.
8139     *
8140     * @return verification timeout in milliseconds
8141     */
8142    private long getVerificationTimeout() {
8143        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8144                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8145                DEFAULT_VERIFICATION_TIMEOUT);
8146    }
8147
8148    /**
8149     * Get the default verification agent response code.
8150     *
8151     * @return default verification response code
8152     */
8153    private int getDefaultVerificationResponse() {
8154        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8155                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8156                DEFAULT_VERIFICATION_RESPONSE);
8157    }
8158
8159    /**
8160     * Check whether or not package verification has been enabled.
8161     *
8162     * @return true if verification should be performed
8163     */
8164    private boolean isVerificationEnabled(int userId, int flags) {
8165        if (!DEFAULT_VERIFY_ENABLE) {
8166            return false;
8167        }
8168
8169        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8170
8171        // Check if installing from ADB
8172        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8173            // Do not run verification in a test harness environment
8174            if (ActivityManager.isRunningInTestHarness()) {
8175                return false;
8176            }
8177            if (ensureVerifyAppsEnabled) {
8178                return true;
8179            }
8180            // Check if the developer does not want package verification for ADB installs
8181            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8182                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8183                return false;
8184            }
8185        }
8186
8187        if (ensureVerifyAppsEnabled) {
8188            return true;
8189        }
8190
8191        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8192                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8193    }
8194
8195    /**
8196     * Get the "allow unknown sources" setting.
8197     *
8198     * @return the current "allow unknown sources" setting
8199     */
8200    private int getUnknownSourcesSettings() {
8201        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8202                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8203                -1);
8204    }
8205
8206    @Override
8207    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8208        final int uid = Binder.getCallingUid();
8209        // writer
8210        synchronized (mPackages) {
8211            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8212            if (targetPackageSetting == null) {
8213                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8214            }
8215
8216            PackageSetting installerPackageSetting;
8217            if (installerPackageName != null) {
8218                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8219                if (installerPackageSetting == null) {
8220                    throw new IllegalArgumentException("Unknown installer package: "
8221                            + installerPackageName);
8222                }
8223            } else {
8224                installerPackageSetting = null;
8225            }
8226
8227            Signature[] callerSignature;
8228            Object obj = mSettings.getUserIdLPr(uid);
8229            if (obj != null) {
8230                if (obj instanceof SharedUserSetting) {
8231                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8232                } else if (obj instanceof PackageSetting) {
8233                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8234                } else {
8235                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8236                }
8237            } else {
8238                throw new SecurityException("Unknown calling uid " + uid);
8239            }
8240
8241            // Verify: can't set installerPackageName to a package that is
8242            // not signed with the same cert as the caller.
8243            if (installerPackageSetting != null) {
8244                if (compareSignatures(callerSignature,
8245                        installerPackageSetting.signatures.mSignatures)
8246                        != PackageManager.SIGNATURE_MATCH) {
8247                    throw new SecurityException(
8248                            "Caller does not have same cert as new installer package "
8249                            + installerPackageName);
8250                }
8251            }
8252
8253            // Verify: if target already has an installer package, it must
8254            // be signed with the same cert as the caller.
8255            if (targetPackageSetting.installerPackageName != null) {
8256                PackageSetting setting = mSettings.mPackages.get(
8257                        targetPackageSetting.installerPackageName);
8258                // If the currently set package isn't valid, then it's always
8259                // okay to change it.
8260                if (setting != null) {
8261                    if (compareSignatures(callerSignature,
8262                            setting.signatures.mSignatures)
8263                            != PackageManager.SIGNATURE_MATCH) {
8264                        throw new SecurityException(
8265                                "Caller does not have same cert as old installer package "
8266                                + targetPackageSetting.installerPackageName);
8267                    }
8268                }
8269            }
8270
8271            // Okay!
8272            targetPackageSetting.installerPackageName = installerPackageName;
8273            scheduleWriteSettingsLocked();
8274        }
8275    }
8276
8277    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8278        // Queue up an async operation since the package installation may take a little while.
8279        mHandler.post(new Runnable() {
8280            public void run() {
8281                mHandler.removeCallbacks(this);
8282                 // Result object to be returned
8283                PackageInstalledInfo res = new PackageInstalledInfo();
8284                res.returnCode = currentStatus;
8285                res.uid = -1;
8286                res.pkg = null;
8287                res.removedInfo = new PackageRemovedInfo();
8288                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8289                    args.doPreInstall(res.returnCode);
8290                    synchronized (mInstallLock) {
8291                        installPackageLI(args, true, res);
8292                    }
8293                    args.doPostInstall(res.returnCode, res.uid);
8294                }
8295
8296                // A restore should be performed at this point if (a) the install
8297                // succeeded, (b) the operation is not an update, and (c) the new
8298                // package has not opted out of backup participation.
8299                final boolean update = res.removedInfo.removedPackage != null;
8300                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8301                boolean doRestore = !update
8302                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8303
8304                // Set up the post-install work request bookkeeping.  This will be used
8305                // and cleaned up by the post-install event handling regardless of whether
8306                // there's a restore pass performed.  Token values are >= 1.
8307                int token;
8308                if (mNextInstallToken < 0) mNextInstallToken = 1;
8309                token = mNextInstallToken++;
8310
8311                PostInstallData data = new PostInstallData(args, res);
8312                mRunningInstalls.put(token, data);
8313                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8314
8315                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8316                    // Pass responsibility to the Backup Manager.  It will perform a
8317                    // restore if appropriate, then pass responsibility back to the
8318                    // Package Manager to run the post-install observer callbacks
8319                    // and broadcasts.
8320                    IBackupManager bm = IBackupManager.Stub.asInterface(
8321                            ServiceManager.getService(Context.BACKUP_SERVICE));
8322                    if (bm != null) {
8323                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8324                                + " to BM for possible restore");
8325                        try {
8326                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8327                        } catch (RemoteException e) {
8328                            // can't happen; the backup manager is local
8329                        } catch (Exception e) {
8330                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8331                            doRestore = false;
8332                        }
8333                    } else {
8334                        Slog.e(TAG, "Backup Manager not found!");
8335                        doRestore = false;
8336                    }
8337                }
8338
8339                if (!doRestore) {
8340                    // No restore possible, or the Backup Manager was mysteriously not
8341                    // available -- just fire the post-install work request directly.
8342                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8343                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8344                    mHandler.sendMessage(msg);
8345                }
8346            }
8347        });
8348    }
8349
8350    private abstract class HandlerParams {
8351        private static final int MAX_RETRIES = 4;
8352
8353        /**
8354         * Number of times startCopy() has been attempted and had a non-fatal
8355         * error.
8356         */
8357        private int mRetries = 0;
8358
8359        /** User handle for the user requesting the information or installation. */
8360        private final UserHandle mUser;
8361
8362        HandlerParams(UserHandle user) {
8363            mUser = user;
8364        }
8365
8366        UserHandle getUser() {
8367            return mUser;
8368        }
8369
8370        final boolean startCopy() {
8371            boolean res;
8372            try {
8373                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8374
8375                if (++mRetries > MAX_RETRIES) {
8376                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8377                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8378                    handleServiceError();
8379                    return false;
8380                } else {
8381                    handleStartCopy();
8382                    res = true;
8383                }
8384            } catch (RemoteException e) {
8385                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8386                mHandler.sendEmptyMessage(MCS_RECONNECT);
8387                res = false;
8388            }
8389            handleReturnCode();
8390            return res;
8391        }
8392
8393        final void serviceError() {
8394            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8395            handleServiceError();
8396            handleReturnCode();
8397        }
8398
8399        abstract void handleStartCopy() throws RemoteException;
8400        abstract void handleServiceError();
8401        abstract void handleReturnCode();
8402    }
8403
8404    class MeasureParams extends HandlerParams {
8405        private final PackageStats mStats;
8406        private boolean mSuccess;
8407
8408        private final IPackageStatsObserver mObserver;
8409
8410        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8411            super(new UserHandle(stats.userHandle));
8412            mObserver = observer;
8413            mStats = stats;
8414        }
8415
8416        @Override
8417        public String toString() {
8418            return "MeasureParams{"
8419                + Integer.toHexString(System.identityHashCode(this))
8420                + " " + mStats.packageName + "}";
8421        }
8422
8423        @Override
8424        void handleStartCopy() throws RemoteException {
8425            synchronized (mInstallLock) {
8426                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8427            }
8428
8429            if (mSuccess) {
8430                final boolean mounted;
8431                if (Environment.isExternalStorageEmulated()) {
8432                    mounted = true;
8433                } else {
8434                    final String status = Environment.getExternalStorageState();
8435                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8436                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8437                }
8438
8439                if (mounted) {
8440                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8441
8442                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8443                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8444
8445                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8446                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8447
8448                    // Always subtract cache size, since it's a subdirectory
8449                    mStats.externalDataSize -= mStats.externalCacheSize;
8450
8451                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8452                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8453
8454                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8455                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8456                }
8457            }
8458        }
8459
8460        @Override
8461        void handleReturnCode() {
8462            if (mObserver != null) {
8463                try {
8464                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8465                } catch (RemoteException e) {
8466                    Slog.i(TAG, "Observer no longer exists.");
8467                }
8468            }
8469        }
8470
8471        @Override
8472        void handleServiceError() {
8473            Slog.e(TAG, "Could not measure application " + mStats.packageName
8474                            + " external storage");
8475        }
8476    }
8477
8478    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8479            throws RemoteException {
8480        long result = 0;
8481        for (File path : paths) {
8482            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8483        }
8484        return result;
8485    }
8486
8487    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8488        for (File path : paths) {
8489            try {
8490                mcs.clearDirectory(path.getAbsolutePath());
8491            } catch (RemoteException e) {
8492            }
8493        }
8494    }
8495
8496    static class OriginInfo {
8497        /**
8498         * Location where install is coming from, before it has been
8499         * copied/renamed into place. This could be a single monolithic APK
8500         * file, or a cluster directory. This location may be untrusted.
8501         */
8502        final File file;
8503        final String cid;
8504
8505        /**
8506         * Flag indicating that {@link #file} or {@link #cid} has already been
8507         * staged, meaning downstream users don't need to defensively copy the
8508         * contents.
8509         */
8510        final boolean staged;
8511
8512        final String resolvedPath;
8513        final File resolvedFile;
8514
8515        public OriginInfo(File file, String cid, boolean staged) {
8516            this.file = file;
8517            this.cid = cid;
8518            this.staged = staged;
8519
8520            if (cid != null) {
8521                resolvedPath = PackageHelper.getSdDir(cid);
8522                resolvedFile = new File(resolvedPath);
8523            } else if (file != null) {
8524                resolvedPath = file.getAbsolutePath();
8525                resolvedFile = file;
8526            } else {
8527                resolvedPath = null;
8528                resolvedFile = null;
8529            }
8530        }
8531    }
8532
8533    class InstallParams extends HandlerParams {
8534        final OriginInfo origin;
8535        final IPackageInstallObserver2 observer;
8536        int flags;
8537        final String installerPackageName;
8538        final VerificationParams verificationParams;
8539        private InstallArgs mArgs;
8540        private int mRet;
8541        final String packageAbiOverride;
8542
8543        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int flags,
8544                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8545                String packageAbiOverride) {
8546            super(user);
8547            this.origin = origin;
8548            this.observer = observer;
8549            this.flags = flags;
8550            this.installerPackageName = installerPackageName;
8551            this.verificationParams = verificationParams;
8552            this.packageAbiOverride = packageAbiOverride;
8553        }
8554
8555        @Override
8556        public String toString() {
8557            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8558                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8559        }
8560
8561        public ManifestDigest getManifestDigest() {
8562            if (verificationParams == null) {
8563                return null;
8564            }
8565            return verificationParams.getManifestDigest();
8566        }
8567
8568        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8569            String packageName = pkgLite.packageName;
8570            int installLocation = pkgLite.installLocation;
8571            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8572            // reader
8573            synchronized (mPackages) {
8574                PackageParser.Package pkg = mPackages.get(packageName);
8575                if (pkg != null) {
8576                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8577                        // Check for downgrading.
8578                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8579                            if (pkgLite.versionCode < pkg.mVersionCode) {
8580                                Slog.w(TAG, "Can't install update of " + packageName
8581                                        + " update version " + pkgLite.versionCode
8582                                        + " is older than installed version "
8583                                        + pkg.mVersionCode);
8584                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8585                            }
8586                        }
8587                        // Check for updated system application.
8588                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8589                            if (onSd) {
8590                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8591                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8592                            }
8593                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8594                        } else {
8595                            if (onSd) {
8596                                // Install flag overrides everything.
8597                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8598                            }
8599                            // If current upgrade specifies particular preference
8600                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8601                                // Application explicitly specified internal.
8602                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8603                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8604                                // App explictly prefers external. Let policy decide
8605                            } else {
8606                                // Prefer previous location
8607                                if (isExternal(pkg)) {
8608                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8609                                }
8610                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8611                            }
8612                        }
8613                    } else {
8614                        // Invalid install. Return error code
8615                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8616                    }
8617                }
8618            }
8619            // All the special cases have been taken care of.
8620            // Return result based on recommended install location.
8621            if (onSd) {
8622                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8623            }
8624            return pkgLite.recommendedInstallLocation;
8625        }
8626
8627        /*
8628         * Invoke remote method to get package information and install
8629         * location values. Override install location based on default
8630         * policy if needed and then create install arguments based
8631         * on the install location.
8632         */
8633        public void handleStartCopy() throws RemoteException {
8634            int ret = PackageManager.INSTALL_SUCCEEDED;
8635
8636            // If we're already staged, we've firmly committed to an install location
8637            if (origin.staged) {
8638                if (origin.file != null) {
8639                    flags |= PackageManager.INSTALL_INTERNAL;
8640                    flags &= ~PackageManager.INSTALL_EXTERNAL;
8641                } else if (origin.cid != null) {
8642                    flags |= PackageManager.INSTALL_EXTERNAL;
8643                    flags &= ~PackageManager.INSTALL_INTERNAL;
8644                } else {
8645                    throw new IllegalStateException("Invalid stage location");
8646                }
8647            }
8648
8649            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8650            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8651
8652            PackageInfoLite pkgLite = null;
8653
8654            if (onInt && onSd) {
8655                // Check if both bits are set.
8656                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8657                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8658            } else {
8659                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, flags,
8660                        packageAbiOverride);
8661
8662                /*
8663                 * If we have too little free space, try to free cache
8664                 * before giving up.
8665                 */
8666                if (!origin.staged && pkgLite.recommendedInstallLocation
8667                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8668                    // TODO: focus freeing disk space on the target device
8669                    final StorageManager storage = StorageManager.from(mContext);
8670                    final long lowThreshold = storage.getStorageLowBytes(
8671                            Environment.getDataDirectory());
8672
8673                    final long sizeBytes = mContainerService.calculateInstalledSize(
8674                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8675
8676                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8677                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8678                                flags, packageAbiOverride);
8679                    }
8680
8681                    /*
8682                     * The cache free must have deleted the file we
8683                     * downloaded to install.
8684                     *
8685                     * TODO: fix the "freeCache" call to not delete
8686                     *       the file we care about.
8687                     */
8688                    if (pkgLite.recommendedInstallLocation
8689                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8690                        pkgLite.recommendedInstallLocation
8691                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8692                    }
8693                }
8694            }
8695
8696            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8697                int loc = pkgLite.recommendedInstallLocation;
8698                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8699                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8700                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8701                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8702                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8703                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8704                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8705                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8706                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8707                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8708                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8709                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8710                } else {
8711                    // Override with defaults if needed.
8712                    loc = installLocationPolicy(pkgLite, flags);
8713                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8714                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8715                    } else if (!onSd && !onInt) {
8716                        // Override install location with flags
8717                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8718                            // Set the flag to install on external media.
8719                            flags |= PackageManager.INSTALL_EXTERNAL;
8720                            flags &= ~PackageManager.INSTALL_INTERNAL;
8721                        } else {
8722                            // Make sure the flag for installing on external
8723                            // media is unset
8724                            flags |= PackageManager.INSTALL_INTERNAL;
8725                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8726                        }
8727                    }
8728                }
8729            }
8730
8731            final InstallArgs args = createInstallArgs(this);
8732            mArgs = args;
8733
8734            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8735                 /*
8736                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8737                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8738                 */
8739                int userIdentifier = getUser().getIdentifier();
8740                if (userIdentifier == UserHandle.USER_ALL
8741                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8742                    userIdentifier = UserHandle.USER_OWNER;
8743                }
8744
8745                /*
8746                 * Determine if we have any installed package verifiers. If we
8747                 * do, then we'll defer to them to verify the packages.
8748                 */
8749                final int requiredUid = mRequiredVerifierPackage == null ? -1
8750                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8751                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8752                    final Intent verification = new Intent(
8753                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8754                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8755                            PACKAGE_MIME_TYPE);
8756                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8757
8758                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8759                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8760                            0 /* TODO: Which userId? */);
8761
8762                    if (DEBUG_VERIFY) {
8763                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8764                                + verification.toString() + " with " + pkgLite.verifiers.length
8765                                + " optional verifiers");
8766                    }
8767
8768                    final int verificationId = mPendingVerificationToken++;
8769
8770                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8771
8772                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8773                            installerPackageName);
8774
8775                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8776
8777                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8778                            pkgLite.packageName);
8779
8780                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8781                            pkgLite.versionCode);
8782
8783                    if (verificationParams != null) {
8784                        if (verificationParams.getVerificationURI() != null) {
8785                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8786                                 verificationParams.getVerificationURI());
8787                        }
8788                        if (verificationParams.getOriginatingURI() != null) {
8789                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8790                                  verificationParams.getOriginatingURI());
8791                        }
8792                        if (verificationParams.getReferrer() != null) {
8793                            verification.putExtra(Intent.EXTRA_REFERRER,
8794                                  verificationParams.getReferrer());
8795                        }
8796                        if (verificationParams.getOriginatingUid() >= 0) {
8797                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8798                                  verificationParams.getOriginatingUid());
8799                        }
8800                        if (verificationParams.getInstallerUid() >= 0) {
8801                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8802                                  verificationParams.getInstallerUid());
8803                        }
8804                    }
8805
8806                    final PackageVerificationState verificationState = new PackageVerificationState(
8807                            requiredUid, args);
8808
8809                    mPendingVerification.append(verificationId, verificationState);
8810
8811                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8812                            receivers, verificationState);
8813
8814                    /*
8815                     * If any sufficient verifiers were listed in the package
8816                     * manifest, attempt to ask them.
8817                     */
8818                    if (sufficientVerifiers != null) {
8819                        final int N = sufficientVerifiers.size();
8820                        if (N == 0) {
8821                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8823                        } else {
8824                            for (int i = 0; i < N; i++) {
8825                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8826
8827                                final Intent sufficientIntent = new Intent(verification);
8828                                sufficientIntent.setComponent(verifierComponent);
8829
8830                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8831                            }
8832                        }
8833                    }
8834
8835                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8836                            mRequiredVerifierPackage, receivers);
8837                    if (ret == PackageManager.INSTALL_SUCCEEDED
8838                            && mRequiredVerifierPackage != null) {
8839                        /*
8840                         * Send the intent to the required verification agent,
8841                         * but only start the verification timeout after the
8842                         * target BroadcastReceivers have run.
8843                         */
8844                        verification.setComponent(requiredVerifierComponent);
8845                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8846                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8847                                new BroadcastReceiver() {
8848                                    @Override
8849                                    public void onReceive(Context context, Intent intent) {
8850                                        final Message msg = mHandler
8851                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8852                                        msg.arg1 = verificationId;
8853                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8854                                    }
8855                                }, null, 0, null, null);
8856
8857                        /*
8858                         * We don't want the copy to proceed until verification
8859                         * succeeds, so null out this field.
8860                         */
8861                        mArgs = null;
8862                    }
8863                } else {
8864                    /*
8865                     * No package verification is enabled, so immediately start
8866                     * the remote call to initiate copy using temporary file.
8867                     */
8868                    ret = args.copyApk(mContainerService, true);
8869                }
8870            }
8871
8872            mRet = ret;
8873        }
8874
8875        @Override
8876        void handleReturnCode() {
8877            // If mArgs is null, then MCS couldn't be reached. When it
8878            // reconnects, it will try again to install. At that point, this
8879            // will succeed.
8880            if (mArgs != null) {
8881                processPendingInstall(mArgs, mRet);
8882            }
8883        }
8884
8885        @Override
8886        void handleServiceError() {
8887            mArgs = createInstallArgs(this);
8888            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8889        }
8890
8891        public boolean isForwardLocked() {
8892            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8893        }
8894    }
8895
8896    /*
8897     * Utility class used in movePackage api.
8898     * srcArgs and targetArgs are not set for invalid flags and make
8899     * sure to do null checks when invoking methods on them.
8900     * We probably want to return ErrorPrams for both failed installs
8901     * and moves.
8902     */
8903    class MoveParams extends HandlerParams {
8904        final IPackageMoveObserver observer;
8905        final int flags;
8906        final String packageName;
8907        final InstallArgs srcArgs;
8908        final InstallArgs targetArgs;
8909        int uid;
8910        int mRet;
8911
8912        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8913                String packageName, String[] instructionSets, int uid, UserHandle user) {
8914            super(user);
8915            this.srcArgs = srcArgs;
8916            this.observer = observer;
8917            this.flags = flags;
8918            this.packageName = packageName;
8919            this.uid = uid;
8920            if (srcArgs != null) {
8921                final String codePath = srcArgs.getCodePath();
8922                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8923                        instructionSets);
8924            } else {
8925                targetArgs = null;
8926            }
8927        }
8928
8929        @Override
8930        public String toString() {
8931            return "MoveParams{"
8932                + Integer.toHexString(System.identityHashCode(this))
8933                + " " + packageName + "}";
8934        }
8935
8936        public void handleStartCopy() throws RemoteException {
8937            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8938            // Check for storage space on target medium
8939            if (!targetArgs.checkFreeStorage(mContainerService)) {
8940                Log.w(TAG, "Insufficient storage to install");
8941                return;
8942            }
8943
8944            mRet = srcArgs.doPreCopy();
8945            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8946                return;
8947            }
8948
8949            mRet = targetArgs.copyApk(mContainerService, false);
8950            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8951                srcArgs.doPostCopy(uid);
8952                return;
8953            }
8954
8955            mRet = srcArgs.doPostCopy(uid);
8956            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8957                return;
8958            }
8959
8960            mRet = targetArgs.doPreInstall(mRet);
8961            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8962                return;
8963            }
8964
8965            if (DEBUG_SD_INSTALL) {
8966                StringBuilder builder = new StringBuilder();
8967                if (srcArgs != null) {
8968                    builder.append("src: ");
8969                    builder.append(srcArgs.getCodePath());
8970                }
8971                if (targetArgs != null) {
8972                    builder.append(" target : ");
8973                    builder.append(targetArgs.getCodePath());
8974                }
8975                Log.i(TAG, builder.toString());
8976            }
8977        }
8978
8979        @Override
8980        void handleReturnCode() {
8981            targetArgs.doPostInstall(mRet, uid);
8982            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8983            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8984                currentStatus = PackageManager.MOVE_SUCCEEDED;
8985            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8986                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8987            }
8988            processPendingMove(this, currentStatus);
8989        }
8990
8991        @Override
8992        void handleServiceError() {
8993            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8994        }
8995    }
8996
8997    /**
8998     * Used during creation of InstallArgs
8999     *
9000     * @param flags package installation flags
9001     * @return true if should be installed on external storage
9002     */
9003    private static boolean installOnSd(int flags) {
9004        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9005            return false;
9006        }
9007        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9008            return true;
9009        }
9010        return false;
9011    }
9012
9013    /**
9014     * Used during creation of InstallArgs
9015     *
9016     * @param flags package installation flags
9017     * @return true if should be installed as forward locked
9018     */
9019    private static boolean installForwardLocked(int flags) {
9020        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9021    }
9022
9023    private InstallArgs createInstallArgs(InstallParams params) {
9024        if (installOnSd(params.flags) || params.isForwardLocked()) {
9025            return new AsecInstallArgs(params);
9026        } else {
9027            return new FileInstallArgs(params);
9028        }
9029    }
9030
9031    /**
9032     * Create args that describe an existing installed package. Typically used
9033     * when cleaning up old installs, or used as a move source.
9034     */
9035    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9036            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9037        final boolean isInAsec;
9038        if (installOnSd(flags)) {
9039            /* Apps on SD card are always in ASEC containers. */
9040            isInAsec = true;
9041        } else if (installForwardLocked(flags)
9042                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9043            /*
9044             * Forward-locked apps are only in ASEC containers if they're the
9045             * new style
9046             */
9047            isInAsec = true;
9048        } else {
9049            isInAsec = false;
9050        }
9051
9052        if (isInAsec) {
9053            return new AsecInstallArgs(codePath, instructionSets,
9054                    installOnSd(flags), installForwardLocked(flags));
9055        } else {
9056            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9057                    instructionSets);
9058        }
9059    }
9060
9061    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9062            String[] instructionSets) {
9063        final File codeFile = new File(codePath);
9064        if (installOnSd(flags) || installForwardLocked(flags)) {
9065            String cid = getNextCodePath(codePath, pkgName, "/"
9066                    + AsecInstallArgs.RES_FILE_NAME);
9067            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9068                    installForwardLocked(flags));
9069        } else {
9070            return new FileInstallArgs(codeFile, instructionSets);
9071        }
9072    }
9073
9074    static abstract class InstallArgs {
9075        /** @see InstallParams#origin */
9076        final OriginInfo origin;
9077
9078        final IPackageInstallObserver2 observer;
9079        // Always refers to PackageManager flags only
9080        final int flags;
9081        final String installerPackageName;
9082        final ManifestDigest manifestDigest;
9083        final UserHandle user;
9084        final String abiOverride;
9085
9086        // The list of instruction sets supported by this app. This is currently
9087        // only used during the rmdex() phase to clean up resources. We can get rid of this
9088        // if we move dex files under the common app path.
9089        /* nullable */ String[] instructionSets;
9090
9091        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int flags,
9092                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9093                String[] instructionSets, String abiOverride) {
9094            this.origin = origin;
9095            this.flags = flags;
9096            this.observer = observer;
9097            this.installerPackageName = installerPackageName;
9098            this.manifestDigest = manifestDigest;
9099            this.user = user;
9100            this.instructionSets = instructionSets;
9101            this.abiOverride = abiOverride;
9102        }
9103
9104        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9105        abstract int doPreInstall(int status);
9106
9107        /**
9108         * Rename package into final resting place. All paths on the given
9109         * scanned package should be updated to reflect the rename.
9110         */
9111        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9112        abstract int doPostInstall(int status, int uid);
9113
9114        /** @see PackageSettingBase#codePathString */
9115        abstract String getCodePath();
9116        /** @see PackageSettingBase#resourcePathString */
9117        abstract String getResourcePath();
9118        abstract String getLegacyNativeLibraryPath();
9119
9120        // Need installer lock especially for dex file removal.
9121        abstract void cleanUpResourcesLI();
9122        abstract boolean doPostDeleteLI(boolean delete);
9123        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9124
9125        /**
9126         * Called before the source arguments are copied. This is used mostly
9127         * for MoveParams when it needs to read the source file to put it in the
9128         * destination.
9129         */
9130        int doPreCopy() {
9131            return PackageManager.INSTALL_SUCCEEDED;
9132        }
9133
9134        /**
9135         * Called after the source arguments are copied. This is used mostly for
9136         * MoveParams when it needs to read the source file to put it in the
9137         * destination.
9138         *
9139         * @return
9140         */
9141        int doPostCopy(int uid) {
9142            return PackageManager.INSTALL_SUCCEEDED;
9143        }
9144
9145        protected boolean isFwdLocked() {
9146            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9147        }
9148
9149        UserHandle getUser() {
9150            return user;
9151        }
9152    }
9153
9154    /**
9155     * Logic to handle installation of non-ASEC applications, including copying
9156     * and renaming logic.
9157     */
9158    class FileInstallArgs extends InstallArgs {
9159        private File codeFile;
9160        private File resourceFile;
9161        private File legacyNativeLibraryPath;
9162
9163        // Example topology:
9164        // /data/app/com.example/base.apk
9165        // /data/app/com.example/split_foo.apk
9166        // /data/app/com.example/lib/arm/libfoo.so
9167        // /data/app/com.example/lib/arm64/libfoo.so
9168        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9169
9170        /** New install */
9171        FileInstallArgs(InstallParams params) {
9172            super(params.origin, params.observer, params.flags,
9173                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9174                    null /* instruction sets */, params.packageAbiOverride);
9175            if (isFwdLocked()) {
9176                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9177            }
9178        }
9179
9180        /** Existing install */
9181        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9182                String[] instructionSets) {
9183            super(new OriginInfo(null, null, false), null, 0, null, null, null, instructionSets, null);
9184            this.codeFile = (codePath != null) ? new File(codePath) : null;
9185            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9186            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9187                    new File(legacyNativeLibraryPath) : null;
9188        }
9189
9190        /** New install from existing */
9191        FileInstallArgs(File originFile, String[] instructionSets) {
9192            super(new OriginInfo(originFile, null, false), null, 0, null, null, null, instructionSets, null);
9193        }
9194
9195        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9196            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9197                    isFwdLocked(), abiOverride);
9198
9199            final StorageManager storage = StorageManager.from(mContext);
9200            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9201        }
9202
9203        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9204            if (origin.staged) {
9205                Slog.d(TAG, origin.file + " already staged; skipping copy");
9206                codeFile = origin.file;
9207                resourceFile = origin.file;
9208                return PackageManager.INSTALL_SUCCEEDED;
9209            }
9210
9211            try {
9212                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9213                codeFile = tempDir;
9214                resourceFile = tempDir;
9215            } catch (IOException e) {
9216                Slog.w(TAG, "Failed to create copy file: " + e);
9217                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9218            }
9219
9220            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9221                @Override
9222                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9223                    if (!FileUtils.isValidExtFilename(name)) {
9224                        throw new IllegalArgumentException("Invalid filename: " + name);
9225                    }
9226                    try {
9227                        final File file = new File(codeFile, name);
9228                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9229                                O_RDWR | O_CREAT, 0644);
9230                        Os.chmod(file.getAbsolutePath(), 0644);
9231                        return new ParcelFileDescriptor(fd);
9232                    } catch (ErrnoException e) {
9233                        throw new RemoteException("Failed to open: " + e.getMessage());
9234                    }
9235                }
9236            };
9237
9238            int ret = PackageManager.INSTALL_SUCCEEDED;
9239            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9240            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9241                Slog.e(TAG, "Failed to copy package");
9242                return ret;
9243            }
9244
9245            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9246            NativeLibraryHelper.Handle handle = null;
9247            try {
9248                handle = NativeLibraryHelper.Handle.create(codeFile);
9249                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9250                        abiOverride);
9251            } catch (IOException e) {
9252                Slog.e(TAG, "Copying native libraries failed", e);
9253                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9254            } finally {
9255                IoUtils.closeQuietly(handle);
9256            }
9257
9258            return ret;
9259        }
9260
9261        int doPreInstall(int status) {
9262            if (status != PackageManager.INSTALL_SUCCEEDED) {
9263                cleanUp();
9264            }
9265            return status;
9266        }
9267
9268        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9269            if (status != PackageManager.INSTALL_SUCCEEDED) {
9270                cleanUp();
9271                return false;
9272            } else {
9273                final File beforeCodeFile = codeFile;
9274                final File afterCodeFile = getNextCodePath(pkg.packageName);
9275
9276                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9277                try {
9278                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9279                } catch (ErrnoException e) {
9280                    Slog.d(TAG, "Failed to rename", e);
9281                    return false;
9282                }
9283
9284                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9285                    Slog.d(TAG, "Failed to restorecon");
9286                    return false;
9287                }
9288
9289                // Reflect the rename internally
9290                codeFile = afterCodeFile;
9291                resourceFile = afterCodeFile;
9292
9293                // Reflect the rename in scanned details
9294                pkg.codePath = afterCodeFile.getAbsolutePath();
9295                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9296                        pkg.baseCodePath);
9297                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9298                        pkg.splitCodePaths);
9299
9300                // Reflect the rename in app info
9301                pkg.applicationInfo.setCodePath(pkg.codePath);
9302                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9303                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9304                pkg.applicationInfo.setResourcePath(pkg.codePath);
9305                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9306                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9307
9308                return true;
9309            }
9310        }
9311
9312        int doPostInstall(int status, int uid) {
9313            if (status != PackageManager.INSTALL_SUCCEEDED) {
9314                cleanUp();
9315            }
9316            return status;
9317        }
9318
9319        @Override
9320        String getCodePath() {
9321            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9322        }
9323
9324        @Override
9325        String getResourcePath() {
9326            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9327        }
9328
9329        @Override
9330        String getLegacyNativeLibraryPath() {
9331            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9332        }
9333
9334        private boolean cleanUp() {
9335            if (codeFile == null || !codeFile.exists()) {
9336                return false;
9337            }
9338
9339            if (codeFile.isDirectory()) {
9340                FileUtils.deleteContents(codeFile);
9341            }
9342            codeFile.delete();
9343
9344            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9345                resourceFile.delete();
9346            }
9347
9348            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9349                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9350                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9351                }
9352                legacyNativeLibraryPath.delete();
9353            }
9354
9355            return true;
9356        }
9357
9358        void cleanUpResourcesLI() {
9359            // Try enumerating all code paths before deleting
9360            List<String> allCodePaths = Collections.EMPTY_LIST;
9361            if (codeFile != null && codeFile.exists()) {
9362                try {
9363                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9364                    allCodePaths = pkg.getAllCodePaths();
9365                } catch (PackageParserException e) {
9366                    // Ignored; we tried our best
9367                }
9368            }
9369
9370            cleanUp();
9371
9372            if (!allCodePaths.isEmpty()) {
9373                if (instructionSets == null) {
9374                    throw new IllegalStateException("instructionSet == null");
9375                }
9376                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9377                for (String codePath : allCodePaths) {
9378                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9379                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9380                        if (retCode < 0) {
9381                            Slog.w(TAG, "Couldn't remove dex file for package: "
9382                                    + " at location " + codePath + ", retcode=" + retCode);
9383                            // we don't consider this to be a failure of the core package deletion
9384                        }
9385                    }
9386                }
9387            }
9388        }
9389
9390        boolean doPostDeleteLI(boolean delete) {
9391            // XXX err, shouldn't we respect the delete flag?
9392            cleanUpResourcesLI();
9393            return true;
9394        }
9395    }
9396
9397    private boolean isAsecExternal(String cid) {
9398        final String asecPath = PackageHelper.getSdFilesystem(cid);
9399        return !asecPath.startsWith(mAsecInternalPath);
9400    }
9401
9402    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9403            PackageManagerException {
9404        if (copyRet < 0) {
9405            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9406                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9407                throw new PackageManagerException(copyRet, message);
9408            }
9409        }
9410    }
9411
9412    /**
9413     * Extract the MountService "container ID" from the full code path of an
9414     * .apk.
9415     */
9416    static String cidFromCodePath(String fullCodePath) {
9417        int eidx = fullCodePath.lastIndexOf("/");
9418        String subStr1 = fullCodePath.substring(0, eidx);
9419        int sidx = subStr1.lastIndexOf("/");
9420        return subStr1.substring(sidx+1, eidx);
9421    }
9422
9423    /**
9424     * Logic to handle installation of ASEC applications, including copying and
9425     * renaming logic.
9426     */
9427    class AsecInstallArgs extends InstallArgs {
9428        static final String RES_FILE_NAME = "pkg.apk";
9429        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9430
9431        String cid;
9432        String packagePath;
9433        String resourcePath;
9434        String legacyNativeLibraryDir;
9435
9436        /** New install */
9437        AsecInstallArgs(InstallParams params) {
9438            super(params.origin, params.observer, params.flags,
9439                    params.installerPackageName, params.getManifestDigest(),
9440                    params.getUser(), null /* instruction sets */,
9441                    params.packageAbiOverride);
9442        }
9443
9444        /** Existing install */
9445        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9446                        boolean isExternal, boolean isForwardLocked) {
9447            super(new OriginInfo(null, null, false), null, (isExternal ? INSTALL_EXTERNAL : 0)
9448                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9449                    instructionSets, null);
9450            // Hackily pretend we're still looking at a full code path
9451            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9452                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9453            }
9454
9455            // Extract cid from fullCodePath
9456            int eidx = fullCodePath.lastIndexOf("/");
9457            String subStr1 = fullCodePath.substring(0, eidx);
9458            int sidx = subStr1.lastIndexOf("/");
9459            cid = subStr1.substring(sidx+1, eidx);
9460            setMountPath(subStr1);
9461        }
9462
9463        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9464            super(new OriginInfo(null, null, false), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9465                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9466                    instructionSets, null);
9467            this.cid = cid;
9468            setMountPath(PackageHelper.getSdDir(cid));
9469        }
9470
9471        /** New install from existing */
9472        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9473                boolean isExternal, boolean isForwardLocked) {
9474            super(new OriginInfo(originPackageFile, null, false), null, (isExternal ? INSTALL_EXTERNAL : 0)
9475                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9476                    instructionSets, null);
9477            this.cid = cid;
9478        }
9479
9480        void createCopyFile() {
9481            cid = mInstallerService.allocateExternalStageCidLegacy();
9482        }
9483
9484        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9485            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9486                    abiOverride);
9487
9488            final File target;
9489            if (isExternal()) {
9490                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9491            } else {
9492                target = Environment.getDataDirectory();
9493            }
9494
9495            final StorageManager storage = StorageManager.from(mContext);
9496            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9497        }
9498
9499        private final boolean isExternal() {
9500            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9501        }
9502
9503        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9504            if (origin.staged) {
9505                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9506                cid = origin.cid;
9507                setMountPath(PackageHelper.getSdDir(cid));
9508                return PackageManager.INSTALL_SUCCEEDED;
9509            }
9510
9511            if (temp) {
9512                createCopyFile();
9513            } else {
9514                /*
9515                 * Pre-emptively destroy the container since it's destroyed if
9516                 * copying fails due to it existing anyway.
9517                 */
9518                PackageHelper.destroySdDir(cid);
9519            }
9520
9521            final String newMountPath = imcs.copyPackageToContainer(
9522                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9523                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9524
9525            if (newMountPath != null) {
9526                setMountPath(newMountPath);
9527                return PackageManager.INSTALL_SUCCEEDED;
9528            } else {
9529                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9530            }
9531        }
9532
9533        @Override
9534        String getCodePath() {
9535            return packagePath;
9536        }
9537
9538        @Override
9539        String getResourcePath() {
9540            return resourcePath;
9541        }
9542
9543        @Override
9544        String getLegacyNativeLibraryPath() {
9545            return legacyNativeLibraryDir;
9546        }
9547
9548        int doPreInstall(int status) {
9549            if (status != PackageManager.INSTALL_SUCCEEDED) {
9550                // Destroy container
9551                PackageHelper.destroySdDir(cid);
9552            } else {
9553                boolean mounted = PackageHelper.isContainerMounted(cid);
9554                if (!mounted) {
9555                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9556                            Process.SYSTEM_UID);
9557                    if (newMountPath != null) {
9558                        setMountPath(newMountPath);
9559                    } else {
9560                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9561                    }
9562                }
9563            }
9564            return status;
9565        }
9566
9567        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9568            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9569            String newMountPath = null;
9570            if (PackageHelper.isContainerMounted(cid)) {
9571                // Unmount the container
9572                if (!PackageHelper.unMountSdDir(cid)) {
9573                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9574                    return false;
9575                }
9576            }
9577            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9578                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9579                        " which might be stale. Will try to clean up.");
9580                // Clean up the stale container and proceed to recreate.
9581                if (!PackageHelper.destroySdDir(newCacheId)) {
9582                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9583                    return false;
9584                }
9585                // Successfully cleaned up stale container. Try to rename again.
9586                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9587                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9588                            + " inspite of cleaning it up.");
9589                    return false;
9590                }
9591            }
9592            if (!PackageHelper.isContainerMounted(newCacheId)) {
9593                Slog.w(TAG, "Mounting container " + newCacheId);
9594                newMountPath = PackageHelper.mountSdDir(newCacheId,
9595                        getEncryptKey(), Process.SYSTEM_UID);
9596            } else {
9597                newMountPath = PackageHelper.getSdDir(newCacheId);
9598            }
9599            if (newMountPath == null) {
9600                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9601                return false;
9602            }
9603            Log.i(TAG, "Succesfully renamed " + cid +
9604                    " to " + newCacheId +
9605                    " at new path: " + newMountPath);
9606            cid = newCacheId;
9607
9608            final File beforeCodeFile = new File(packagePath);
9609            setMountPath(newMountPath);
9610            final File afterCodeFile = new File(packagePath);
9611
9612            // Reflect the rename in scanned details
9613            pkg.codePath = afterCodeFile.getAbsolutePath();
9614            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9615                    pkg.baseCodePath);
9616            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9617                    pkg.splitCodePaths);
9618
9619            // Reflect the rename in app info
9620            pkg.applicationInfo.setCodePath(pkg.codePath);
9621            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9622            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9623            pkg.applicationInfo.setResourcePath(pkg.codePath);
9624            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9625            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9626
9627            return true;
9628        }
9629
9630        private void setMountPath(String mountPath) {
9631            final File mountFile = new File(mountPath);
9632
9633            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9634            if (monolithicFile.exists()) {
9635                packagePath = monolithicFile.getAbsolutePath();
9636                if (isFwdLocked()) {
9637                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9638                } else {
9639                    resourcePath = packagePath;
9640                }
9641            } else {
9642                packagePath = mountFile.getAbsolutePath();
9643                resourcePath = packagePath;
9644            }
9645
9646            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9647        }
9648
9649        int doPostInstall(int status, int uid) {
9650            if (status != PackageManager.INSTALL_SUCCEEDED) {
9651                cleanUp();
9652            } else {
9653                final int groupOwner;
9654                final String protectedFile;
9655                if (isFwdLocked()) {
9656                    groupOwner = UserHandle.getSharedAppGid(uid);
9657                    protectedFile = RES_FILE_NAME;
9658                } else {
9659                    groupOwner = -1;
9660                    protectedFile = null;
9661                }
9662
9663                if (uid < Process.FIRST_APPLICATION_UID
9664                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9665                    Slog.e(TAG, "Failed to finalize " + cid);
9666                    PackageHelper.destroySdDir(cid);
9667                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9668                }
9669
9670                boolean mounted = PackageHelper.isContainerMounted(cid);
9671                if (!mounted) {
9672                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9673                }
9674            }
9675            return status;
9676        }
9677
9678        private void cleanUp() {
9679            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9680
9681            // Destroy secure container
9682            PackageHelper.destroySdDir(cid);
9683        }
9684
9685        private List<String> getAllCodePaths() {
9686            final File codeFile = new File(getCodePath());
9687            if (codeFile != null && codeFile.exists()) {
9688                try {
9689                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9690                    return pkg.getAllCodePaths();
9691                } catch (PackageParserException e) {
9692                    // Ignored; we tried our best
9693                }
9694            }
9695            return Collections.EMPTY_LIST;
9696        }
9697
9698        void cleanUpResourcesLI() {
9699            // Enumerate all code paths before deleting
9700            cleanUpResourcesLI(getAllCodePaths());
9701        }
9702
9703        private void cleanUpResourcesLI(List<String> allCodePaths) {
9704            cleanUp();
9705
9706            if (!allCodePaths.isEmpty()) {
9707                if (instructionSets == null) {
9708                    throw new IllegalStateException("instructionSet == null");
9709                }
9710                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9711                for (String codePath : allCodePaths) {
9712                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9713                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9714                        if (retCode < 0) {
9715                            Slog.w(TAG, "Couldn't remove dex file for package: "
9716                                    + " at location " + codePath + ", retcode=" + retCode);
9717                            // we don't consider this to be a failure of the core package deletion
9718                        }
9719                    }
9720                }
9721            }
9722        }
9723
9724        boolean matchContainer(String app) {
9725            if (cid.startsWith(app)) {
9726                return true;
9727            }
9728            return false;
9729        }
9730
9731        String getPackageName() {
9732            return getAsecPackageName(cid);
9733        }
9734
9735        boolean doPostDeleteLI(boolean delete) {
9736            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9737            final List<String> allCodePaths = getAllCodePaths();
9738            boolean mounted = PackageHelper.isContainerMounted(cid);
9739            if (mounted) {
9740                // Unmount first
9741                if (PackageHelper.unMountSdDir(cid)) {
9742                    mounted = false;
9743                }
9744            }
9745            if (!mounted && delete) {
9746                cleanUpResourcesLI(allCodePaths);
9747            }
9748            return !mounted;
9749        }
9750
9751        @Override
9752        int doPreCopy() {
9753            if (isFwdLocked()) {
9754                if (!PackageHelper.fixSdPermissions(cid,
9755                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9756                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9757                }
9758            }
9759
9760            return PackageManager.INSTALL_SUCCEEDED;
9761        }
9762
9763        @Override
9764        int doPostCopy(int uid) {
9765            if (isFwdLocked()) {
9766                if (uid < Process.FIRST_APPLICATION_UID
9767                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9768                                RES_FILE_NAME)) {
9769                    Slog.e(TAG, "Failed to finalize " + cid);
9770                    PackageHelper.destroySdDir(cid);
9771                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9772                }
9773            }
9774
9775            return PackageManager.INSTALL_SUCCEEDED;
9776        }
9777    }
9778
9779    static String getAsecPackageName(String packageCid) {
9780        int idx = packageCid.lastIndexOf("-");
9781        if (idx == -1) {
9782            return packageCid;
9783        }
9784        return packageCid.substring(0, idx);
9785    }
9786
9787    // Utility method used to create code paths based on package name and available index.
9788    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9789        String idxStr = "";
9790        int idx = 1;
9791        // Fall back to default value of idx=1 if prefix is not
9792        // part of oldCodePath
9793        if (oldCodePath != null) {
9794            String subStr = oldCodePath;
9795            // Drop the suffix right away
9796            if (suffix != null && subStr.endsWith(suffix)) {
9797                subStr = subStr.substring(0, subStr.length() - suffix.length());
9798            }
9799            // If oldCodePath already contains prefix find out the
9800            // ending index to either increment or decrement.
9801            int sidx = subStr.lastIndexOf(prefix);
9802            if (sidx != -1) {
9803                subStr = subStr.substring(sidx + prefix.length());
9804                if (subStr != null) {
9805                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9806                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9807                    }
9808                    try {
9809                        idx = Integer.parseInt(subStr);
9810                        if (idx <= 1) {
9811                            idx++;
9812                        } else {
9813                            idx--;
9814                        }
9815                    } catch(NumberFormatException e) {
9816                    }
9817                }
9818            }
9819        }
9820        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9821        return prefix + idxStr;
9822    }
9823
9824    private File getNextCodePath(String packageName) {
9825        int suffix = 1;
9826        File result;
9827        do {
9828            result = new File(mAppInstallDir, packageName + "-" + suffix);
9829            suffix++;
9830        } while (result.exists());
9831        return result;
9832    }
9833
9834    // Utility method used to ignore ADD/REMOVE events
9835    // by directory observer.
9836    private static boolean ignoreCodePath(String fullPathStr) {
9837        String apkName = deriveCodePathName(fullPathStr);
9838        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9839        if (idx != -1 && ((idx+1) < apkName.length())) {
9840            // Make sure the package ends with a numeral
9841            String version = apkName.substring(idx+1);
9842            try {
9843                Integer.parseInt(version);
9844                return true;
9845            } catch (NumberFormatException e) {}
9846        }
9847        return false;
9848    }
9849
9850    // Utility method that returns the relative package path with respect
9851    // to the installation directory. Like say for /data/data/com.test-1.apk
9852    // string com.test-1 is returned.
9853    static String deriveCodePathName(String codePath) {
9854        if (codePath == null) {
9855            return null;
9856        }
9857        final File codeFile = new File(codePath);
9858        final String name = codeFile.getName();
9859        if (codeFile.isDirectory()) {
9860            return name;
9861        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9862            final int lastDot = name.lastIndexOf('.');
9863            return name.substring(0, lastDot);
9864        } else {
9865            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9866            return null;
9867        }
9868    }
9869
9870    class PackageInstalledInfo {
9871        String name;
9872        int uid;
9873        // The set of users that originally had this package installed.
9874        int[] origUsers;
9875        // The set of users that now have this package installed.
9876        int[] newUsers;
9877        PackageParser.Package pkg;
9878        int returnCode;
9879        String returnMsg;
9880        PackageRemovedInfo removedInfo;
9881
9882        public void setError(int code, String msg) {
9883            returnCode = code;
9884            returnMsg = msg;
9885            Slog.w(TAG, msg);
9886        }
9887
9888        public void setError(String msg, PackageParserException e) {
9889            returnCode = e.error;
9890            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9891            Slog.w(TAG, msg, e);
9892        }
9893
9894        public void setError(String msg, PackageManagerException e) {
9895            returnCode = e.error;
9896            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9897            Slog.w(TAG, msg, e);
9898        }
9899
9900        // In some error cases we want to convey more info back to the observer
9901        String origPackage;
9902        String origPermission;
9903    }
9904
9905    /*
9906     * Install a non-existing package.
9907     */
9908    private void installNewPackageLI(PackageParser.Package pkg,
9909            int parseFlags, int scanMode, UserHandle user,
9910            String installerPackageName, PackageInstalledInfo res) {
9911        // Remember this for later, in case we need to rollback this install
9912        String pkgName = pkg.packageName;
9913
9914        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9915        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9916        synchronized(mPackages) {
9917            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9918                // A package with the same name is already installed, though
9919                // it has been renamed to an older name.  The package we
9920                // are trying to install should be installed as an update to
9921                // the existing one, but that has not been requested, so bail.
9922                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9923                        + " without first uninstalling package running as "
9924                        + mSettings.mRenamedPackages.get(pkgName));
9925                return;
9926            }
9927            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9928                // Don't allow installation over an existing package with the same name.
9929                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9930                        + " without first uninstalling.");
9931                return;
9932            }
9933        }
9934
9935        try {
9936            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9937                    System.currentTimeMillis(), user);
9938
9939            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9940            // delete the partially installed application. the data directory will have to be
9941            // restored if it was already existing
9942            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9943                // remove package from internal structures.  Note that we want deletePackageX to
9944                // delete the package data and cache directories that it created in
9945                // scanPackageLocked, unless those directories existed before we even tried to
9946                // install.
9947                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9948                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9949                                res.removedInfo, true);
9950            }
9951
9952        } catch (PackageManagerException e) {
9953            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9954        }
9955    }
9956
9957    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9958        // Upgrade keysets are being used.  Determine if new package has a superset of the
9959        // required keys.
9960        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9961        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9962        for (int i = 0; i < upgradeKeySets.length; i++) {
9963            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9964            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9965                return true;
9966            }
9967        }
9968        return false;
9969    }
9970
9971    private void replacePackageLI(PackageParser.Package pkg,
9972            int parseFlags, int scanMode, UserHandle user,
9973            String installerPackageName, PackageInstalledInfo res) {
9974        PackageParser.Package oldPackage;
9975        String pkgName = pkg.packageName;
9976        int[] allUsers;
9977        boolean[] perUserInstalled;
9978
9979        // First find the old package info and check signatures
9980        synchronized(mPackages) {
9981            oldPackage = mPackages.get(pkgName);
9982            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9983            PackageSetting ps = mSettings.mPackages.get(pkgName);
9984            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9985                // default to original signature matching
9986                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9987                    != PackageManager.SIGNATURE_MATCH) {
9988                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9989                            "New package has a different signature: " + pkgName);
9990                    return;
9991                }
9992            } else {
9993                if(!checkUpgradeKeySetLP(ps, pkg)) {
9994                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9995                            "New package not signed by keys specified by upgrade-keysets: "
9996                            + pkgName);
9997                    return;
9998                }
9999            }
10000
10001            // In case of rollback, remember per-user/profile install state
10002            allUsers = sUserManager.getUserIds();
10003            perUserInstalled = new boolean[allUsers.length];
10004            for (int i = 0; i < allUsers.length; i++) {
10005                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10006            }
10007        }
10008
10009        boolean sysPkg = (isSystemApp(oldPackage));
10010        if (sysPkg) {
10011            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10012                    user, allUsers, perUserInstalled, installerPackageName, res);
10013        } else {
10014            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10015                    user, allUsers, perUserInstalled, installerPackageName, res);
10016        }
10017    }
10018
10019    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10020            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10021            int[] allUsers, boolean[] perUserInstalled,
10022            String installerPackageName, PackageInstalledInfo res) {
10023        String pkgName = deletedPackage.packageName;
10024        boolean deletedPkg = true;
10025        boolean updatedSettings = false;
10026
10027        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10028                + deletedPackage);
10029        long origUpdateTime;
10030        if (pkg.mExtras != null) {
10031            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10032        } else {
10033            origUpdateTime = 0;
10034        }
10035
10036        // First delete the existing package while retaining the data directory
10037        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10038                res.removedInfo, true)) {
10039            // If the existing package wasn't successfully deleted
10040            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10041            deletedPkg = false;
10042        } else {
10043            // Successfully deleted the old package. Now proceed with re-installation
10044            deleteCodeCacheDirsLI(pkgName);
10045            try {
10046                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10047                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10048                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10049                updatedSettings = true;
10050            } catch (PackageManagerException e) {
10051                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10052            }
10053        }
10054
10055        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10056            // remove package from internal structures.  Note that we want deletePackageX to
10057            // delete the package data and cache directories that it created in
10058            // scanPackageLocked, unless those directories existed before we even tried to
10059            // install.
10060            if(updatedSettings) {
10061                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10062                deletePackageLI(
10063                        pkgName, null, true, allUsers, perUserInstalled,
10064                        PackageManager.DELETE_KEEP_DATA,
10065                                res.removedInfo, true);
10066            }
10067            // Since we failed to install the new package we need to restore the old
10068            // package that we deleted.
10069            if (deletedPkg) {
10070                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10071                File restoreFile = new File(deletedPackage.codePath);
10072                // Parse old package
10073                boolean oldOnSd = isExternal(deletedPackage);
10074                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10075                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10076                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10077                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10078                        | SCAN_UPDATE_TIME;
10079                try {
10080                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null);
10081                } catch (PackageManagerException e) {
10082                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10083                            + e.getMessage());
10084                    return;
10085                }
10086                // Restore of old package succeeded. Update permissions.
10087                // writer
10088                synchronized (mPackages) {
10089                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10090                            UPDATE_PERMISSIONS_ALL);
10091                    // can downgrade to reader
10092                    mSettings.writeLPr();
10093                }
10094                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10095            }
10096        }
10097    }
10098
10099    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10100            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10101            int[] allUsers, boolean[] perUserInstalled,
10102            String installerPackageName, PackageInstalledInfo res) {
10103        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10104                + ", old=" + deletedPackage);
10105        boolean updatedSettings = false;
10106        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10107                PackageParser.PARSE_IS_SYSTEM;
10108        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10109            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10110        }
10111        String packageName = deletedPackage.packageName;
10112        if (packageName == null) {
10113            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10114                    "Attempt to delete null packageName.");
10115            return;
10116        }
10117        PackageParser.Package oldPkg;
10118        PackageSetting oldPkgSetting;
10119        // reader
10120        synchronized (mPackages) {
10121            oldPkg = mPackages.get(packageName);
10122            oldPkgSetting = mSettings.mPackages.get(packageName);
10123            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10124                    (oldPkgSetting == null)) {
10125                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10126                        "Couldn't find package:" + packageName + " information");
10127                return;
10128            }
10129        }
10130
10131        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10132
10133        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10134        res.removedInfo.removedPackage = packageName;
10135        // Remove existing system package
10136        removePackageLI(oldPkgSetting, true);
10137        // writer
10138        synchronized (mPackages) {
10139            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10140                // We didn't need to disable the .apk as a current system package,
10141                // which means we are replacing another update that is already
10142                // installed.  We need to make sure to delete the older one's .apk.
10143                res.removedInfo.args = createInstallArgsForExisting(0,
10144                        deletedPackage.applicationInfo.getCodePath(),
10145                        deletedPackage.applicationInfo.getResourcePath(),
10146                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10147                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10148            } else {
10149                res.removedInfo.args = null;
10150            }
10151        }
10152
10153        // Successfully disabled the old package. Now proceed with re-installation
10154        deleteCodeCacheDirsLI(packageName);
10155
10156        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10157        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10158
10159        PackageParser.Package newPackage = null;
10160        try {
10161            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
10162            if (newPackage.mExtras != null) {
10163                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10164                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10165                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10166
10167                // is the update attempting to change shared user? that isn't going to work...
10168                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10169                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10170                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10171                            + " to " + newPkgSetting.sharedUser);
10172                    updatedSettings = true;
10173                }
10174            }
10175
10176            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10177                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10178                updatedSettings = true;
10179            }
10180
10181        } catch (PackageManagerException e) {
10182            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10183        }
10184
10185        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10186            // Re installation failed. Restore old information
10187            // Remove new pkg information
10188            if (newPackage != null) {
10189                removeInstalledPackageLI(newPackage, true);
10190            }
10191            // Add back the old system package
10192            try {
10193                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
10194            } catch (PackageManagerException e) {
10195                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10196            }
10197            // Restore the old system information in Settings
10198            synchronized(mPackages) {
10199                if (updatedSettings) {
10200                    mSettings.enableSystemPackageLPw(packageName);
10201                    mSettings.setInstallerPackageName(packageName,
10202                            oldPkgSetting.installerPackageName);
10203                }
10204                mSettings.writeLPr();
10205            }
10206        }
10207    }
10208
10209    // Utility method used to move dex files during install.
10210    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10211        // TODO: extend to move split APK dex files
10212        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10213            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10214            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10215            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10216                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10217                        dexCodeInstructionSet);
10218                if (retCode != 0) {
10219                /*
10220                 * Programs may be lazily run through dexopt, so the
10221                 * source may not exist. However, something seems to
10222                 * have gone wrong, so note that dexopt needs to be
10223                 * run again and remove the source file. In addition,
10224                 * remove the target to make sure there isn't a stale
10225                 * file from a previous version of the package.
10226                 */
10227                    newPackage.mDexOptPerformed.clear();
10228                    mInstaller.rmdex(oldCodePath, dexCodeInstructionSet);
10229                    mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet);
10230                }
10231            }
10232        }
10233        return PackageManager.INSTALL_SUCCEEDED;
10234    }
10235
10236    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10237            int[] allUsers, boolean[] perUserInstalled,
10238            PackageInstalledInfo res) {
10239        String pkgName = newPackage.packageName;
10240        synchronized (mPackages) {
10241            //write settings. the installStatus will be incomplete at this stage.
10242            //note that the new package setting would have already been
10243            //added to mPackages. It hasn't been persisted yet.
10244            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10245            mSettings.writeLPr();
10246        }
10247
10248        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10249
10250        synchronized (mPackages) {
10251            updatePermissionsLPw(newPackage.packageName, newPackage,
10252                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10253                            ? UPDATE_PERMISSIONS_ALL : 0));
10254            // For system-bundled packages, we assume that installing an upgraded version
10255            // of the package implies that the user actually wants to run that new code,
10256            // so we enable the package.
10257            if (isSystemApp(newPackage)) {
10258                // NB: implicit assumption that system package upgrades apply to all users
10259                if (DEBUG_INSTALL) {
10260                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10261                }
10262                PackageSetting ps = mSettings.mPackages.get(pkgName);
10263                if (ps != null) {
10264                    if (res.origUsers != null) {
10265                        for (int userHandle : res.origUsers) {
10266                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10267                                    userHandle, installerPackageName);
10268                        }
10269                    }
10270                    // Also convey the prior install/uninstall state
10271                    if (allUsers != null && perUserInstalled != null) {
10272                        for (int i = 0; i < allUsers.length; i++) {
10273                            if (DEBUG_INSTALL) {
10274                                Slog.d(TAG, "    user " + allUsers[i]
10275                                        + " => " + perUserInstalled[i]);
10276                            }
10277                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10278                        }
10279                        // these install state changes will be persisted in the
10280                        // upcoming call to mSettings.writeLPr().
10281                    }
10282                }
10283            }
10284            res.name = pkgName;
10285            res.uid = newPackage.applicationInfo.uid;
10286            res.pkg = newPackage;
10287            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10288            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10289            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10290            //to update install status
10291            mSettings.writeLPr();
10292        }
10293    }
10294
10295    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10296        int pFlags = args.flags;
10297        String installerPackageName = args.installerPackageName;
10298        File tmpPackageFile = new File(args.getCodePath());
10299        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10300        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10301        boolean replace = false;
10302        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10303                | (newInstall ? SCAN_NEW_INSTALL : 0);
10304        // Result object to be returned
10305        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10306
10307        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10308        // Retrieve PackageSettings and parse package
10309        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10310                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10311                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10312        PackageParser pp = new PackageParser();
10313        pp.setSeparateProcesses(mSeparateProcesses);
10314        pp.setDisplayMetrics(mMetrics);
10315
10316        final PackageParser.Package pkg;
10317        try {
10318            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10319        } catch (PackageParserException e) {
10320            res.setError("Failed parse during installPackageLI", e);
10321            return;
10322        }
10323
10324        // Mark that we have an install time CPU ABI override.
10325        pkg.cpuAbiOverride = args.abiOverride;
10326
10327        String pkgName = res.name = pkg.packageName;
10328        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10329            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10330                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10331                return;
10332            }
10333        }
10334
10335        try {
10336            pp.collectCertificates(pkg, parseFlags);
10337            pp.collectManifestDigest(pkg);
10338        } catch (PackageParserException e) {
10339            res.setError("Failed collect during installPackageLI", e);
10340            return;
10341        }
10342
10343        /* If the installer passed in a manifest digest, compare it now. */
10344        if (args.manifestDigest != null) {
10345            if (DEBUG_INSTALL) {
10346                final String parsedManifest = pkg.manifestDigest == null ? "null"
10347                        : pkg.manifestDigest.toString();
10348                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10349                        + parsedManifest);
10350            }
10351
10352            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10353                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10354                return;
10355            }
10356        } else if (DEBUG_INSTALL) {
10357            final String parsedManifest = pkg.manifestDigest == null
10358                    ? "null" : pkg.manifestDigest.toString();
10359            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10360        }
10361
10362        // Get rid of all references to package scan path via parser.
10363        pp = null;
10364        String oldCodePath = null;
10365        boolean systemApp = false;
10366        synchronized (mPackages) {
10367            // Check whether the newly-scanned package wants to define an already-defined perm
10368            int N = pkg.permissions.size();
10369            for (int i = N-1; i >= 0; i--) {
10370                PackageParser.Permission perm = pkg.permissions.get(i);
10371                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10372                if (bp != null) {
10373                    // If the defining package is signed with our cert, it's okay.  This
10374                    // also includes the "updating the same package" case, of course.
10375                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10376                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10377                        // If the owning package is the system itself, we log but allow
10378                        // install to proceed; we fail the install on all other permission
10379                        // redefinitions.
10380                        if (!bp.sourcePackage.equals("android")) {
10381                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10382                                    + pkg.packageName + " attempting to redeclare permission "
10383                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10384                            res.origPermission = perm.info.name;
10385                            res.origPackage = bp.sourcePackage;
10386                            return;
10387                        } else {
10388                            Slog.w(TAG, "Package " + pkg.packageName
10389                                    + " attempting to redeclare system permission "
10390                                    + perm.info.name + "; ignoring new declaration");
10391                            pkg.permissions.remove(i);
10392                        }
10393                    }
10394                }
10395            }
10396
10397            // Check if installing already existing package
10398            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10399                String oldName = mSettings.mRenamedPackages.get(pkgName);
10400                if (pkg.mOriginalPackages != null
10401                        && pkg.mOriginalPackages.contains(oldName)
10402                        && mPackages.containsKey(oldName)) {
10403                    // This package is derived from an original package,
10404                    // and this device has been updating from that original
10405                    // name.  We must continue using the original name, so
10406                    // rename the new package here.
10407                    pkg.setPackageName(oldName);
10408                    pkgName = pkg.packageName;
10409                    replace = true;
10410                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10411                            + oldName + " pkgName=" + pkgName);
10412                } else if (mPackages.containsKey(pkgName)) {
10413                    // This package, under its official name, already exists
10414                    // on the device; we should replace it.
10415                    replace = true;
10416                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10417                }
10418            }
10419            PackageSetting ps = mSettings.mPackages.get(pkgName);
10420            if (ps != null) {
10421                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10422                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10423                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10424                    systemApp = (ps.pkg.applicationInfo.flags &
10425                            ApplicationInfo.FLAG_SYSTEM) != 0;
10426                }
10427                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10428            }
10429        }
10430
10431        if (systemApp && onSd) {
10432            // Disable updates to system apps on sdcard
10433            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10434                    "Cannot install updates to system apps on sdcard");
10435            return;
10436        }
10437
10438        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10439            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10440            return;
10441        }
10442
10443        if (replace) {
10444            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10445                    installerPackageName, res);
10446        } else {
10447            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10448                    installerPackageName, res);
10449        }
10450        synchronized (mPackages) {
10451            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10452            if (ps != null) {
10453                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10454            }
10455        }
10456    }
10457
10458    private static boolean isForwardLocked(PackageParser.Package pkg) {
10459        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10460    }
10461
10462    private static boolean isForwardLocked(ApplicationInfo info) {
10463        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10464    }
10465
10466    private boolean isForwardLocked(PackageSetting ps) {
10467        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10468    }
10469
10470    private static boolean isMultiArch(PackageSetting ps) {
10471        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10472    }
10473
10474    private static boolean isMultiArch(ApplicationInfo info) {
10475        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10476    }
10477
10478    private static boolean isExternal(PackageParser.Package pkg) {
10479        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10480    }
10481
10482    private static boolean isExternal(PackageSetting ps) {
10483        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10484    }
10485
10486    private static boolean isExternal(ApplicationInfo info) {
10487        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10488    }
10489
10490    private static boolean isSystemApp(PackageParser.Package pkg) {
10491        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10492    }
10493
10494    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10495        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10496    }
10497
10498    private static boolean isSystemApp(ApplicationInfo info) {
10499        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10500    }
10501
10502    private static boolean isSystemApp(PackageSetting ps) {
10503        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10504    }
10505
10506    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10507        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10508    }
10509
10510    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10511        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10512    }
10513
10514    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10515        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10516    }
10517
10518    private int packageFlagsToInstallFlags(PackageSetting ps) {
10519        int installFlags = 0;
10520        if (isExternal(ps)) {
10521            installFlags |= PackageManager.INSTALL_EXTERNAL;
10522        }
10523        if (isForwardLocked(ps)) {
10524            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10525        }
10526        return installFlags;
10527    }
10528
10529    private void deleteTempPackageFiles() {
10530        final FilenameFilter filter = new FilenameFilter() {
10531            public boolean accept(File dir, String name) {
10532                return name.startsWith("vmdl") && name.endsWith(".tmp");
10533            }
10534        };
10535        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10536            file.delete();
10537        }
10538    }
10539
10540    @Override
10541    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10542            int flags) {
10543        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10544                flags);
10545    }
10546
10547    @Override
10548    public void deletePackage(final String packageName,
10549            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10550        mContext.enforceCallingOrSelfPermission(
10551                android.Manifest.permission.DELETE_PACKAGES, null);
10552        final int uid = Binder.getCallingUid();
10553        if (UserHandle.getUserId(uid) != userId) {
10554            mContext.enforceCallingPermission(
10555                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10556                    "deletePackage for user " + userId);
10557        }
10558        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10559            try {
10560                observer.onPackageDeleted(packageName,
10561                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10562            } catch (RemoteException re) {
10563            }
10564            return;
10565        }
10566
10567        boolean uninstallBlocked = false;
10568        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10569            int[] users = sUserManager.getUserIds();
10570            for (int i = 0; i < users.length; ++i) {
10571                if (getBlockUninstallForUser(packageName, users[i])) {
10572                    uninstallBlocked = true;
10573                    break;
10574                }
10575            }
10576        } else {
10577            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10578        }
10579        if (uninstallBlocked) {
10580            try {
10581                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10582                        null);
10583            } catch (RemoteException re) {
10584            }
10585            return;
10586        }
10587
10588        if (DEBUG_REMOVE) {
10589            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10590        }
10591        // Queue up an async operation since the package deletion may take a little while.
10592        mHandler.post(new Runnable() {
10593            public void run() {
10594                mHandler.removeCallbacks(this);
10595                final int returnCode = deletePackageX(packageName, userId, flags);
10596                if (observer != null) {
10597                    try {
10598                        observer.onPackageDeleted(packageName, returnCode, null);
10599                    } catch (RemoteException e) {
10600                        Log.i(TAG, "Observer no longer exists.");
10601                    } //end catch
10602                } //end if
10603            } //end run
10604        });
10605    }
10606
10607    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10608        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10609                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10610        try {
10611            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10612                    || dpm.isDeviceOwner(packageName))) {
10613                return true;
10614            }
10615        } catch (RemoteException e) {
10616        }
10617        return false;
10618    }
10619
10620    /**
10621     *  This method is an internal method that could be get invoked either
10622     *  to delete an installed package or to clean up a failed installation.
10623     *  After deleting an installed package, a broadcast is sent to notify any
10624     *  listeners that the package has been installed. For cleaning up a failed
10625     *  installation, the broadcast is not necessary since the package's
10626     *  installation wouldn't have sent the initial broadcast either
10627     *  The key steps in deleting a package are
10628     *  deleting the package information in internal structures like mPackages,
10629     *  deleting the packages base directories through installd
10630     *  updating mSettings to reflect current status
10631     *  persisting settings for later use
10632     *  sending a broadcast if necessary
10633     */
10634    private int deletePackageX(String packageName, int userId, int flags) {
10635        final PackageRemovedInfo info = new PackageRemovedInfo();
10636        final boolean res;
10637
10638        if (isPackageDeviceAdmin(packageName, userId)) {
10639            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10640            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10641        }
10642
10643        boolean removedForAllUsers = false;
10644        boolean systemUpdate = false;
10645
10646        // for the uninstall-updates case and restricted profiles, remember the per-
10647        // userhandle installed state
10648        int[] allUsers;
10649        boolean[] perUserInstalled;
10650        synchronized (mPackages) {
10651            PackageSetting ps = mSettings.mPackages.get(packageName);
10652            allUsers = sUserManager.getUserIds();
10653            perUserInstalled = new boolean[allUsers.length];
10654            for (int i = 0; i < allUsers.length; i++) {
10655                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10656            }
10657        }
10658
10659        synchronized (mInstallLock) {
10660            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10661            res = deletePackageLI(packageName,
10662                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10663                            ? UserHandle.ALL : new UserHandle(userId),
10664                    true, allUsers, perUserInstalled,
10665                    flags | REMOVE_CHATTY, info, true);
10666            systemUpdate = info.isRemovedPackageSystemUpdate;
10667            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10668                removedForAllUsers = true;
10669            }
10670            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10671                    + " removedForAllUsers=" + removedForAllUsers);
10672        }
10673
10674        if (res) {
10675            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10676
10677            // If the removed package was a system update, the old system package
10678            // was re-enabled; we need to broadcast this information
10679            if (systemUpdate) {
10680                Bundle extras = new Bundle(1);
10681                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10682                        ? info.removedAppId : info.uid);
10683                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10684
10685                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10686                        extras, null, null, null);
10687                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10688                        extras, null, null, null);
10689                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10690                        null, packageName, null, null);
10691            }
10692        }
10693        // Force a gc here.
10694        Runtime.getRuntime().gc();
10695        // Delete the resources here after sending the broadcast to let
10696        // other processes clean up before deleting resources.
10697        if (info.args != null) {
10698            synchronized (mInstallLock) {
10699                info.args.doPostDeleteLI(true);
10700            }
10701        }
10702
10703        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10704    }
10705
10706    static class PackageRemovedInfo {
10707        String removedPackage;
10708        int uid = -1;
10709        int removedAppId = -1;
10710        int[] removedUsers = null;
10711        boolean isRemovedPackageSystemUpdate = false;
10712        // Clean up resources deleted packages.
10713        InstallArgs args = null;
10714
10715        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10716            Bundle extras = new Bundle(1);
10717            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10718            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10719            if (replacing) {
10720                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10721            }
10722            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10723            if (removedPackage != null) {
10724                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10725                        extras, null, null, removedUsers);
10726                if (fullRemove && !replacing) {
10727                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10728                            extras, null, null, removedUsers);
10729                }
10730            }
10731            if (removedAppId >= 0) {
10732                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10733                        removedUsers);
10734            }
10735        }
10736    }
10737
10738    /*
10739     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10740     * flag is not set, the data directory is removed as well.
10741     * make sure this flag is set for partially installed apps. If not its meaningless to
10742     * delete a partially installed application.
10743     */
10744    private void removePackageDataLI(PackageSetting ps,
10745            int[] allUserHandles, boolean[] perUserInstalled,
10746            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10747        String packageName = ps.name;
10748        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10749        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10750        // Retrieve object to delete permissions for shared user later on
10751        final PackageSetting deletedPs;
10752        // reader
10753        synchronized (mPackages) {
10754            deletedPs = mSettings.mPackages.get(packageName);
10755            if (outInfo != null) {
10756                outInfo.removedPackage = packageName;
10757                outInfo.removedUsers = deletedPs != null
10758                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10759                        : null;
10760            }
10761        }
10762        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10763            removeDataDirsLI(packageName);
10764            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10765        }
10766        // writer
10767        synchronized (mPackages) {
10768            if (deletedPs != null) {
10769                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10770                    if (outInfo != null) {
10771                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10772                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10773                    }
10774                    if (deletedPs != null) {
10775                        updatePermissionsLPw(deletedPs.name, null, 0);
10776                        if (deletedPs.sharedUser != null) {
10777                            // remove permissions associated with package
10778                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10779                        }
10780                    }
10781                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10782                }
10783                // make sure to preserve per-user disabled state if this removal was just
10784                // a downgrade of a system app to the factory package
10785                if (allUserHandles != null && perUserInstalled != null) {
10786                    if (DEBUG_REMOVE) {
10787                        Slog.d(TAG, "Propagating install state across downgrade");
10788                    }
10789                    for (int i = 0; i < allUserHandles.length; i++) {
10790                        if (DEBUG_REMOVE) {
10791                            Slog.d(TAG, "    user " + allUserHandles[i]
10792                                    + " => " + perUserInstalled[i]);
10793                        }
10794                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10795                    }
10796                }
10797            }
10798            // can downgrade to reader
10799            if (writeSettings) {
10800                // Save settings now
10801                mSettings.writeLPr();
10802            }
10803        }
10804        if (outInfo != null) {
10805            // A user ID was deleted here. Go through all users and remove it
10806            // from KeyStore.
10807            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10808        }
10809    }
10810
10811    static boolean locationIsPrivileged(File path) {
10812        try {
10813            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10814                    .getCanonicalPath();
10815            return path.getCanonicalPath().startsWith(privilegedAppDir);
10816        } catch (IOException e) {
10817            Slog.e(TAG, "Unable to access code path " + path);
10818        }
10819        return false;
10820    }
10821
10822    /*
10823     * Tries to delete system package.
10824     */
10825    private boolean deleteSystemPackageLI(PackageSetting newPs,
10826            int[] allUserHandles, boolean[] perUserInstalled,
10827            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10828        final boolean applyUserRestrictions
10829                = (allUserHandles != null) && (perUserInstalled != null);
10830        PackageSetting disabledPs = null;
10831        // Confirm if the system package has been updated
10832        // An updated system app can be deleted. This will also have to restore
10833        // the system pkg from system partition
10834        // reader
10835        synchronized (mPackages) {
10836            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10837        }
10838        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10839                + " disabledPs=" + disabledPs);
10840        if (disabledPs == null) {
10841            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10842            return false;
10843        } else if (DEBUG_REMOVE) {
10844            Slog.d(TAG, "Deleting system pkg from data partition");
10845        }
10846        if (DEBUG_REMOVE) {
10847            if (applyUserRestrictions) {
10848                Slog.d(TAG, "Remembering install states:");
10849                for (int i = 0; i < allUserHandles.length; i++) {
10850                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10851                }
10852            }
10853        }
10854        // Delete the updated package
10855        outInfo.isRemovedPackageSystemUpdate = true;
10856        if (disabledPs.versionCode < newPs.versionCode) {
10857            // Delete data for downgrades
10858            flags &= ~PackageManager.DELETE_KEEP_DATA;
10859        } else {
10860            // Preserve data by setting flag
10861            flags |= PackageManager.DELETE_KEEP_DATA;
10862        }
10863        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10864                allUserHandles, perUserInstalled, outInfo, writeSettings);
10865        if (!ret) {
10866            return false;
10867        }
10868        // writer
10869        synchronized (mPackages) {
10870            // Reinstate the old system package
10871            mSettings.enableSystemPackageLPw(newPs.name);
10872            // Remove any native libraries from the upgraded package.
10873            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10874        }
10875        // Install the system package
10876        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10877        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10878        if (locationIsPrivileged(disabledPs.codePath)) {
10879            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10880        }
10881
10882        final PackageParser.Package newPkg;
10883        try {
10884            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10885        } catch (PackageManagerException e) {
10886            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10887            return false;
10888        }
10889
10890        // writer
10891        synchronized (mPackages) {
10892            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10893            updatePermissionsLPw(newPkg.packageName, newPkg,
10894                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10895            if (applyUserRestrictions) {
10896                if (DEBUG_REMOVE) {
10897                    Slog.d(TAG, "Propagating install state across reinstall");
10898                }
10899                for (int i = 0; i < allUserHandles.length; i++) {
10900                    if (DEBUG_REMOVE) {
10901                        Slog.d(TAG, "    user " + allUserHandles[i]
10902                                + " => " + perUserInstalled[i]);
10903                    }
10904                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10905                }
10906                // Regardless of writeSettings we need to ensure that this restriction
10907                // state propagation is persisted
10908                mSettings.writeAllUsersPackageRestrictionsLPr();
10909            }
10910            // can downgrade to reader here
10911            if (writeSettings) {
10912                mSettings.writeLPr();
10913            }
10914        }
10915        return true;
10916    }
10917
10918    private boolean deleteInstalledPackageLI(PackageSetting ps,
10919            boolean deleteCodeAndResources, int flags,
10920            int[] allUserHandles, boolean[] perUserInstalled,
10921            PackageRemovedInfo outInfo, boolean writeSettings) {
10922        if (outInfo != null) {
10923            outInfo.uid = ps.appId;
10924        }
10925
10926        // Delete package data from internal structures and also remove data if flag is set
10927        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10928
10929        // Delete application code and resources
10930        if (deleteCodeAndResources && (outInfo != null)) {
10931            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10932                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10933                    getAppDexInstructionSets(ps));
10934            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10935        }
10936        return true;
10937    }
10938
10939    @Override
10940    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10941            int userId) {
10942        mContext.enforceCallingOrSelfPermission(
10943                android.Manifest.permission.DELETE_PACKAGES, null);
10944        synchronized (mPackages) {
10945            PackageSetting ps = mSettings.mPackages.get(packageName);
10946            if (ps == null) {
10947                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10948                return false;
10949            }
10950            if (!ps.getInstalled(userId)) {
10951                // Can't block uninstall for an app that is not installed or enabled.
10952                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10953                return false;
10954            }
10955            ps.setBlockUninstall(blockUninstall, userId);
10956            mSettings.writePackageRestrictionsLPr(userId);
10957        }
10958        return true;
10959    }
10960
10961    @Override
10962    public boolean getBlockUninstallForUser(String packageName, int userId) {
10963        synchronized (mPackages) {
10964            PackageSetting ps = mSettings.mPackages.get(packageName);
10965            if (ps == null) {
10966                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10967                return false;
10968            }
10969            return ps.getBlockUninstall(userId);
10970        }
10971    }
10972
10973    /*
10974     * This method handles package deletion in general
10975     */
10976    private boolean deletePackageLI(String packageName, UserHandle user,
10977            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10978            int flags, PackageRemovedInfo outInfo,
10979            boolean writeSettings) {
10980        if (packageName == null) {
10981            Slog.w(TAG, "Attempt to delete null packageName.");
10982            return false;
10983        }
10984        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10985        PackageSetting ps;
10986        boolean dataOnly = false;
10987        int removeUser = -1;
10988        int appId = -1;
10989        synchronized (mPackages) {
10990            ps = mSettings.mPackages.get(packageName);
10991            if (ps == null) {
10992                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10993                return false;
10994            }
10995            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10996                    && user.getIdentifier() != UserHandle.USER_ALL) {
10997                // The caller is asking that the package only be deleted for a single
10998                // user.  To do this, we just mark its uninstalled state and delete
10999                // its data.  If this is a system app, we only allow this to happen if
11000                // they have set the special DELETE_SYSTEM_APP which requests different
11001                // semantics than normal for uninstalling system apps.
11002                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11003                ps.setUserState(user.getIdentifier(),
11004                        COMPONENT_ENABLED_STATE_DEFAULT,
11005                        false, //installed
11006                        true,  //stopped
11007                        true,  //notLaunched
11008                        false, //hidden
11009                        null, null, null,
11010                        false // blockUninstall
11011                        );
11012                if (!isSystemApp(ps)) {
11013                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11014                        // Other user still have this package installed, so all
11015                        // we need to do is clear this user's data and save that
11016                        // it is uninstalled.
11017                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11018                        removeUser = user.getIdentifier();
11019                        appId = ps.appId;
11020                        mSettings.writePackageRestrictionsLPr(removeUser);
11021                    } else {
11022                        // We need to set it back to 'installed' so the uninstall
11023                        // broadcasts will be sent correctly.
11024                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11025                        ps.setInstalled(true, user.getIdentifier());
11026                    }
11027                } else {
11028                    // This is a system app, so we assume that the
11029                    // other users still have this package installed, so all
11030                    // we need to do is clear this user's data and save that
11031                    // it is uninstalled.
11032                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11033                    removeUser = user.getIdentifier();
11034                    appId = ps.appId;
11035                    mSettings.writePackageRestrictionsLPr(removeUser);
11036                }
11037            }
11038        }
11039
11040        if (removeUser >= 0) {
11041            // From above, we determined that we are deleting this only
11042            // for a single user.  Continue the work here.
11043            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11044            if (outInfo != null) {
11045                outInfo.removedPackage = packageName;
11046                outInfo.removedAppId = appId;
11047                outInfo.removedUsers = new int[] {removeUser};
11048            }
11049            mInstaller.clearUserData(packageName, removeUser);
11050            removeKeystoreDataIfNeeded(removeUser, appId);
11051            schedulePackageCleaning(packageName, removeUser, false);
11052            return true;
11053        }
11054
11055        if (dataOnly) {
11056            // Delete application data first
11057            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11058            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11059            return true;
11060        }
11061
11062        boolean ret = false;
11063        if (isSystemApp(ps)) {
11064            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11065            // When an updated system application is deleted we delete the existing resources as well and
11066            // fall back to existing code in system partition
11067            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11068                    flags, outInfo, writeSettings);
11069        } else {
11070            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11071            // Kill application pre-emptively especially for apps on sd.
11072            killApplication(packageName, ps.appId, "uninstall pkg");
11073            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11074                    allUserHandles, perUserInstalled,
11075                    outInfo, writeSettings);
11076        }
11077
11078        return ret;
11079    }
11080
11081    private final class ClearStorageConnection implements ServiceConnection {
11082        IMediaContainerService mContainerService;
11083
11084        @Override
11085        public void onServiceConnected(ComponentName name, IBinder service) {
11086            synchronized (this) {
11087                mContainerService = IMediaContainerService.Stub.asInterface(service);
11088                notifyAll();
11089            }
11090        }
11091
11092        @Override
11093        public void onServiceDisconnected(ComponentName name) {
11094        }
11095    }
11096
11097    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11098        final boolean mounted;
11099        if (Environment.isExternalStorageEmulated()) {
11100            mounted = true;
11101        } else {
11102            final String status = Environment.getExternalStorageState();
11103
11104            mounted = status.equals(Environment.MEDIA_MOUNTED)
11105                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11106        }
11107
11108        if (!mounted) {
11109            return;
11110        }
11111
11112        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11113        int[] users;
11114        if (userId == UserHandle.USER_ALL) {
11115            users = sUserManager.getUserIds();
11116        } else {
11117            users = new int[] { userId };
11118        }
11119        final ClearStorageConnection conn = new ClearStorageConnection();
11120        if (mContext.bindServiceAsUser(
11121                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11122            try {
11123                for (int curUser : users) {
11124                    long timeout = SystemClock.uptimeMillis() + 5000;
11125                    synchronized (conn) {
11126                        long now = SystemClock.uptimeMillis();
11127                        while (conn.mContainerService == null && now < timeout) {
11128                            try {
11129                                conn.wait(timeout - now);
11130                            } catch (InterruptedException e) {
11131                            }
11132                        }
11133                    }
11134                    if (conn.mContainerService == null) {
11135                        return;
11136                    }
11137
11138                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11139                    clearDirectory(conn.mContainerService,
11140                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11141                    if (allData) {
11142                        clearDirectory(conn.mContainerService,
11143                                userEnv.buildExternalStorageAppDataDirs(packageName));
11144                        clearDirectory(conn.mContainerService,
11145                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11146                    }
11147                }
11148            } finally {
11149                mContext.unbindService(conn);
11150            }
11151        }
11152    }
11153
11154    @Override
11155    public void clearApplicationUserData(final String packageName,
11156            final IPackageDataObserver observer, final int userId) {
11157        mContext.enforceCallingOrSelfPermission(
11158                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11159        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11160        // Queue up an async operation since the package deletion may take a little while.
11161        mHandler.post(new Runnable() {
11162            public void run() {
11163                mHandler.removeCallbacks(this);
11164                final boolean succeeded;
11165                synchronized (mInstallLock) {
11166                    succeeded = clearApplicationUserDataLI(packageName, userId);
11167                }
11168                clearExternalStorageDataSync(packageName, userId, true);
11169                if (succeeded) {
11170                    // invoke DeviceStorageMonitor's update method to clear any notifications
11171                    DeviceStorageMonitorInternal
11172                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11173                    if (dsm != null) {
11174                        dsm.checkMemory();
11175                    }
11176                }
11177                if(observer != null) {
11178                    try {
11179                        observer.onRemoveCompleted(packageName, succeeded);
11180                    } catch (RemoteException e) {
11181                        Log.i(TAG, "Observer no longer exists.");
11182                    }
11183                } //end if observer
11184            } //end run
11185        });
11186    }
11187
11188    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11189        if (packageName == null) {
11190            Slog.w(TAG, "Attempt to delete null packageName.");
11191            return false;
11192        }
11193        PackageParser.Package p;
11194        boolean dataOnly = false;
11195        final int appId;
11196        synchronized (mPackages) {
11197            p = mPackages.get(packageName);
11198            if (p == null) {
11199                dataOnly = true;
11200                PackageSetting ps = mSettings.mPackages.get(packageName);
11201                if ((ps == null) || (ps.pkg == null)) {
11202                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11203                    return false;
11204                }
11205                p = ps.pkg;
11206            }
11207            if (!dataOnly) {
11208                // need to check this only for fully installed applications
11209                if (p == null) {
11210                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11211                    return false;
11212                }
11213                final ApplicationInfo applicationInfo = p.applicationInfo;
11214                if (applicationInfo == null) {
11215                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11216                    return false;
11217                }
11218            }
11219            if (p != null && p.applicationInfo != null) {
11220                appId = p.applicationInfo.uid;
11221            } else {
11222                appId = -1;
11223            }
11224        }
11225        int retCode = mInstaller.clearUserData(packageName, userId);
11226        if (retCode < 0) {
11227            Slog.w(TAG, "Couldn't remove cache files for package: "
11228                    + packageName);
11229            return false;
11230        }
11231        removeKeystoreDataIfNeeded(userId, appId);
11232        return true;
11233    }
11234
11235    /**
11236     * Remove entries from the keystore daemon. Will only remove it if the
11237     * {@code appId} is valid.
11238     */
11239    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11240        if (appId < 0) {
11241            return;
11242        }
11243
11244        final KeyStore keyStore = KeyStore.getInstance();
11245        if (keyStore != null) {
11246            if (userId == UserHandle.USER_ALL) {
11247                for (final int individual : sUserManager.getUserIds()) {
11248                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11249                }
11250            } else {
11251                keyStore.clearUid(UserHandle.getUid(userId, appId));
11252            }
11253        } else {
11254            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11255        }
11256    }
11257
11258    @Override
11259    public void deleteApplicationCacheFiles(final String packageName,
11260            final IPackageDataObserver observer) {
11261        mContext.enforceCallingOrSelfPermission(
11262                android.Manifest.permission.DELETE_CACHE_FILES, null);
11263        // Queue up an async operation since the package deletion may take a little while.
11264        final int userId = UserHandle.getCallingUserId();
11265        mHandler.post(new Runnable() {
11266            public void run() {
11267                mHandler.removeCallbacks(this);
11268                final boolean succeded;
11269                synchronized (mInstallLock) {
11270                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11271                }
11272                clearExternalStorageDataSync(packageName, userId, false);
11273                if(observer != null) {
11274                    try {
11275                        observer.onRemoveCompleted(packageName, succeded);
11276                    } catch (RemoteException e) {
11277                        Log.i(TAG, "Observer no longer exists.");
11278                    }
11279                } //end if observer
11280            } //end run
11281        });
11282    }
11283
11284    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11285        if (packageName == null) {
11286            Slog.w(TAG, "Attempt to delete null packageName.");
11287            return false;
11288        }
11289        PackageParser.Package p;
11290        synchronized (mPackages) {
11291            p = mPackages.get(packageName);
11292        }
11293        if (p == null) {
11294            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11295            return false;
11296        }
11297        final ApplicationInfo applicationInfo = p.applicationInfo;
11298        if (applicationInfo == null) {
11299            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11300            return false;
11301        }
11302        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11303        if (retCode < 0) {
11304            Slog.w(TAG, "Couldn't remove cache files for package: "
11305                       + packageName + " u" + userId);
11306            return false;
11307        }
11308        return true;
11309    }
11310
11311    @Override
11312    public void getPackageSizeInfo(final String packageName, int userHandle,
11313            final IPackageStatsObserver observer) {
11314        mContext.enforceCallingOrSelfPermission(
11315                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11316        if (packageName == null) {
11317            throw new IllegalArgumentException("Attempt to get size of null packageName");
11318        }
11319
11320        PackageStats stats = new PackageStats(packageName, userHandle);
11321
11322        /*
11323         * Queue up an async operation since the package measurement may take a
11324         * little while.
11325         */
11326        Message msg = mHandler.obtainMessage(INIT_COPY);
11327        msg.obj = new MeasureParams(stats, observer);
11328        mHandler.sendMessage(msg);
11329    }
11330
11331    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11332            PackageStats pStats) {
11333        if (packageName == null) {
11334            Slog.w(TAG, "Attempt to get size of null packageName.");
11335            return false;
11336        }
11337        PackageParser.Package p;
11338        boolean dataOnly = false;
11339        String libDirRoot = null;
11340        String asecPath = null;
11341        PackageSetting ps = null;
11342        synchronized (mPackages) {
11343            p = mPackages.get(packageName);
11344            ps = mSettings.mPackages.get(packageName);
11345            if(p == null) {
11346                dataOnly = true;
11347                if((ps == null) || (ps.pkg == null)) {
11348                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11349                    return false;
11350                }
11351                p = ps.pkg;
11352            }
11353            if (ps != null) {
11354                libDirRoot = ps.legacyNativeLibraryPathString;
11355            }
11356            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11357                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11358                if (secureContainerId != null) {
11359                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11360                }
11361            }
11362        }
11363        String publicSrcDir = null;
11364        if(!dataOnly) {
11365            final ApplicationInfo applicationInfo = p.applicationInfo;
11366            if (applicationInfo == null) {
11367                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11368                return false;
11369            }
11370            if (isForwardLocked(p)) {
11371                publicSrcDir = applicationInfo.getBaseResourcePath();
11372            }
11373        }
11374        // TODO: extend to measure size of split APKs
11375        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11376        // not just the first level.
11377        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11378        // just the primary.
11379        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11380        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11381                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11382        if (res < 0) {
11383            return false;
11384        }
11385
11386        // Fix-up for forward-locked applications in ASEC containers.
11387        if (!isExternal(p)) {
11388            pStats.codeSize += pStats.externalCodeSize;
11389            pStats.externalCodeSize = 0L;
11390        }
11391
11392        return true;
11393    }
11394
11395
11396    @Override
11397    public void addPackageToPreferred(String packageName) {
11398        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11399    }
11400
11401    @Override
11402    public void removePackageFromPreferred(String packageName) {
11403        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11404    }
11405
11406    @Override
11407    public List<PackageInfo> getPreferredPackages(int flags) {
11408        return new ArrayList<PackageInfo>();
11409    }
11410
11411    private int getUidTargetSdkVersionLockedLPr(int uid) {
11412        Object obj = mSettings.getUserIdLPr(uid);
11413        if (obj instanceof SharedUserSetting) {
11414            final SharedUserSetting sus = (SharedUserSetting) obj;
11415            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11416            final Iterator<PackageSetting> it = sus.packages.iterator();
11417            while (it.hasNext()) {
11418                final PackageSetting ps = it.next();
11419                if (ps.pkg != null) {
11420                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11421                    if (v < vers) vers = v;
11422                }
11423            }
11424            return vers;
11425        } else if (obj instanceof PackageSetting) {
11426            final PackageSetting ps = (PackageSetting) obj;
11427            if (ps.pkg != null) {
11428                return ps.pkg.applicationInfo.targetSdkVersion;
11429            }
11430        }
11431        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11432    }
11433
11434    @Override
11435    public void addPreferredActivity(IntentFilter filter, int match,
11436            ComponentName[] set, ComponentName activity, int userId) {
11437        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11438                "Adding preferred");
11439    }
11440
11441    private void addPreferredActivityInternal(IntentFilter filter, int match,
11442            ComponentName[] set, ComponentName activity, boolean always, int userId,
11443            String opname) {
11444        // writer
11445        int callingUid = Binder.getCallingUid();
11446        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11447        if (filter.countActions() == 0) {
11448            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11449            return;
11450        }
11451        synchronized (mPackages) {
11452            if (mContext.checkCallingOrSelfPermission(
11453                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11454                    != PackageManager.PERMISSION_GRANTED) {
11455                if (getUidTargetSdkVersionLockedLPr(callingUid)
11456                        < Build.VERSION_CODES.FROYO) {
11457                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11458                            + callingUid);
11459                    return;
11460                }
11461                mContext.enforceCallingOrSelfPermission(
11462                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11463            }
11464
11465            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11466            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11467                    + userId + ":");
11468            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11469            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11470            mSettings.writePackageRestrictionsLPr(userId);
11471        }
11472    }
11473
11474    @Override
11475    public void replacePreferredActivity(IntentFilter filter, int match,
11476            ComponentName[] set, ComponentName activity, int userId) {
11477        if (filter.countActions() != 1) {
11478            throw new IllegalArgumentException(
11479                    "replacePreferredActivity expects filter to have only 1 action.");
11480        }
11481        if (filter.countDataAuthorities() != 0
11482                || filter.countDataPaths() != 0
11483                || filter.countDataSchemes() > 1
11484                || filter.countDataTypes() != 0) {
11485            throw new IllegalArgumentException(
11486                    "replacePreferredActivity expects filter to have no data authorities, " +
11487                    "paths, or types; and at most one scheme.");
11488        }
11489
11490        final int callingUid = Binder.getCallingUid();
11491        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11492        synchronized (mPackages) {
11493            if (mContext.checkCallingOrSelfPermission(
11494                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11495                    != PackageManager.PERMISSION_GRANTED) {
11496                if (getUidTargetSdkVersionLockedLPr(callingUid)
11497                        < Build.VERSION_CODES.FROYO) {
11498                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11499                            + Binder.getCallingUid());
11500                    return;
11501                }
11502                mContext.enforceCallingOrSelfPermission(
11503                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11504            }
11505
11506            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11507            if (pir != null) {
11508                // Get all of the existing entries that exactly match this filter.
11509                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11510                if (existing != null && existing.size() == 1) {
11511                    PreferredActivity cur = existing.get(0);
11512                    if (DEBUG_PREFERRED) {
11513                        Slog.i(TAG, "Checking replace of preferred:");
11514                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11515                        if (!cur.mPref.mAlways) {
11516                            Slog.i(TAG, "  -- CUR; not mAlways!");
11517                        } else {
11518                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11519                            Slog.i(TAG, "  -- CUR: mSet="
11520                                    + Arrays.toString(cur.mPref.mSetComponents));
11521                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11522                            Slog.i(TAG, "  -- NEW: mMatch="
11523                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11524                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11525                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11526                        }
11527                    }
11528                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11529                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11530                            && cur.mPref.sameSet(set)) {
11531                        if (DEBUG_PREFERRED) {
11532                            Slog.i(TAG, "Replacing with same preferred activity "
11533                                    + cur.mPref.mShortComponent + " for user "
11534                                    + userId + ":");
11535                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11536                        } else {
11537                            Slog.i(TAG, "Replacing with same preferred activity "
11538                                    + cur.mPref.mShortComponent + " for user "
11539                                    + userId);
11540                        }
11541                        return;
11542                    }
11543                }
11544
11545                if (existing != null) {
11546                    if (DEBUG_PREFERRED) {
11547                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11548                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11549                    }
11550                    for (int i = 0; i < existing.size(); i++) {
11551                        PreferredActivity pa = existing.get(i);
11552                        if (DEBUG_PREFERRED) {
11553                            Slog.i(TAG, "Removing existing preferred activity "
11554                                    + pa.mPref.mComponent + ":");
11555                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11556                        }
11557                        pir.removeFilter(pa);
11558                    }
11559                }
11560            }
11561            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11562                    "Replacing preferred");
11563        }
11564    }
11565
11566    @Override
11567    public void clearPackagePreferredActivities(String packageName) {
11568        final int uid = Binder.getCallingUid();
11569        // writer
11570        synchronized (mPackages) {
11571            PackageParser.Package pkg = mPackages.get(packageName);
11572            if (pkg == null || pkg.applicationInfo.uid != uid) {
11573                if (mContext.checkCallingOrSelfPermission(
11574                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11575                        != PackageManager.PERMISSION_GRANTED) {
11576                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11577                            < Build.VERSION_CODES.FROYO) {
11578                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11579                                + Binder.getCallingUid());
11580                        return;
11581                    }
11582                    mContext.enforceCallingOrSelfPermission(
11583                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11584                }
11585            }
11586
11587            int user = UserHandle.getCallingUserId();
11588            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11589                mSettings.writePackageRestrictionsLPr(user);
11590                scheduleWriteSettingsLocked();
11591            }
11592        }
11593    }
11594
11595    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11596    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11597        ArrayList<PreferredActivity> removed = null;
11598        boolean changed = false;
11599        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11600            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11601            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11602            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11603                continue;
11604            }
11605            Iterator<PreferredActivity> it = pir.filterIterator();
11606            while (it.hasNext()) {
11607                PreferredActivity pa = it.next();
11608                // Mark entry for removal only if it matches the package name
11609                // and the entry is of type "always".
11610                if (packageName == null ||
11611                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11612                                && pa.mPref.mAlways)) {
11613                    if (removed == null) {
11614                        removed = new ArrayList<PreferredActivity>();
11615                    }
11616                    removed.add(pa);
11617                }
11618            }
11619            if (removed != null) {
11620                for (int j=0; j<removed.size(); j++) {
11621                    PreferredActivity pa = removed.get(j);
11622                    pir.removeFilter(pa);
11623                }
11624                changed = true;
11625            }
11626        }
11627        return changed;
11628    }
11629
11630    @Override
11631    public void resetPreferredActivities(int userId) {
11632        mContext.enforceCallingOrSelfPermission(
11633                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11634        // writer
11635        synchronized (mPackages) {
11636            int user = UserHandle.getCallingUserId();
11637            clearPackagePreferredActivitiesLPw(null, user);
11638            mSettings.readDefaultPreferredAppsLPw(this, user);
11639            mSettings.writePackageRestrictionsLPr(user);
11640            scheduleWriteSettingsLocked();
11641        }
11642    }
11643
11644    @Override
11645    public int getPreferredActivities(List<IntentFilter> outFilters,
11646            List<ComponentName> outActivities, String packageName) {
11647
11648        int num = 0;
11649        final int userId = UserHandle.getCallingUserId();
11650        // reader
11651        synchronized (mPackages) {
11652            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11653            if (pir != null) {
11654                final Iterator<PreferredActivity> it = pir.filterIterator();
11655                while (it.hasNext()) {
11656                    final PreferredActivity pa = it.next();
11657                    if (packageName == null
11658                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11659                                    && pa.mPref.mAlways)) {
11660                        if (outFilters != null) {
11661                            outFilters.add(new IntentFilter(pa));
11662                        }
11663                        if (outActivities != null) {
11664                            outActivities.add(pa.mPref.mComponent);
11665                        }
11666                    }
11667                }
11668            }
11669        }
11670
11671        return num;
11672    }
11673
11674    @Override
11675    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11676            int userId) {
11677        int callingUid = Binder.getCallingUid();
11678        if (callingUid != Process.SYSTEM_UID) {
11679            throw new SecurityException(
11680                    "addPersistentPreferredActivity can only be run by the system");
11681        }
11682        if (filter.countActions() == 0) {
11683            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11684            return;
11685        }
11686        synchronized (mPackages) {
11687            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11688                    " :");
11689            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11690            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11691                    new PersistentPreferredActivity(filter, activity));
11692            mSettings.writePackageRestrictionsLPr(userId);
11693        }
11694    }
11695
11696    @Override
11697    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11698        int callingUid = Binder.getCallingUid();
11699        if (callingUid != Process.SYSTEM_UID) {
11700            throw new SecurityException(
11701                    "clearPackagePersistentPreferredActivities can only be run by the system");
11702        }
11703        ArrayList<PersistentPreferredActivity> removed = null;
11704        boolean changed = false;
11705        synchronized (mPackages) {
11706            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11707                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11708                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11709                        .valueAt(i);
11710                if (userId != thisUserId) {
11711                    continue;
11712                }
11713                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11714                while (it.hasNext()) {
11715                    PersistentPreferredActivity ppa = it.next();
11716                    // Mark entry for removal only if it matches the package name.
11717                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11718                        if (removed == null) {
11719                            removed = new ArrayList<PersistentPreferredActivity>();
11720                        }
11721                        removed.add(ppa);
11722                    }
11723                }
11724                if (removed != null) {
11725                    for (int j=0; j<removed.size(); j++) {
11726                        PersistentPreferredActivity ppa = removed.get(j);
11727                        ppir.removeFilter(ppa);
11728                    }
11729                    changed = true;
11730                }
11731            }
11732
11733            if (changed) {
11734                mSettings.writePackageRestrictionsLPr(userId);
11735            }
11736        }
11737    }
11738
11739    @Override
11740    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11741            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11742        mContext.enforceCallingOrSelfPermission(
11743                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11744        int callingUid = Binder.getCallingUid();
11745        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11746        if (intentFilter.countActions() == 0) {
11747            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11748            return;
11749        }
11750        synchronized (mPackages) {
11751            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11752                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11753            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11754            mSettings.writePackageRestrictionsLPr(sourceUserId);
11755        }
11756    }
11757
11758    @Override
11759    public void addCrossProfileIntentsForPackage(String packageName,
11760            int sourceUserId, int targetUserId) {
11761        mContext.enforceCallingOrSelfPermission(
11762                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11763        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11764        mSettings.writePackageRestrictionsLPr(sourceUserId);
11765    }
11766
11767    @Override
11768    public void removeCrossProfileIntentsForPackage(String packageName,
11769            int sourceUserId, int targetUserId) {
11770        mContext.enforceCallingOrSelfPermission(
11771                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11772        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11773        mSettings.writePackageRestrictionsLPr(sourceUserId);
11774    }
11775
11776    @Override
11777    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11778            int ownerUserId) {
11779        mContext.enforceCallingOrSelfPermission(
11780                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11781        int callingUid = Binder.getCallingUid();
11782        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11783        int callingUserId = UserHandle.getUserId(callingUid);
11784        synchronized (mPackages) {
11785            CrossProfileIntentResolver resolver =
11786                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11787            HashSet<CrossProfileIntentFilter> set =
11788                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11789            for (CrossProfileIntentFilter filter : set) {
11790                if (filter.getOwnerPackage().equals(ownerPackage)
11791                        && filter.getOwnerUserId() == callingUserId) {
11792                    resolver.removeFilter(filter);
11793                }
11794            }
11795            mSettings.writePackageRestrictionsLPr(sourceUserId);
11796        }
11797    }
11798
11799    // Enforcing that callingUid is owning pkg on userId
11800    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11801        // The system owns everything.
11802        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11803            return;
11804        }
11805        int callingUserId = UserHandle.getUserId(callingUid);
11806        if (callingUserId != userId) {
11807            throw new SecurityException("calling uid " + callingUid
11808                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11809                    + callingUserId);
11810        }
11811        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11812        if (pi == null) {
11813            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11814                    + callingUserId);
11815        }
11816        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11817            throw new SecurityException("Calling uid " + callingUid
11818                    + " does not own package " + pkg);
11819        }
11820    }
11821
11822    @Override
11823    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11824        Intent intent = new Intent(Intent.ACTION_MAIN);
11825        intent.addCategory(Intent.CATEGORY_HOME);
11826
11827        final int callingUserId = UserHandle.getCallingUserId();
11828        List<ResolveInfo> list = queryIntentActivities(intent, null,
11829                PackageManager.GET_META_DATA, callingUserId);
11830        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11831                true, false, false, callingUserId);
11832
11833        allHomeCandidates.clear();
11834        if (list != null) {
11835            for (ResolveInfo ri : list) {
11836                allHomeCandidates.add(ri);
11837            }
11838        }
11839        return (preferred == null || preferred.activityInfo == null)
11840                ? null
11841                : new ComponentName(preferred.activityInfo.packageName,
11842                        preferred.activityInfo.name);
11843    }
11844
11845    /**
11846     * Check if calling UID is the current home app. This handles both the case
11847     * where the user has selected a specific home app, and where there is only
11848     * one home app.
11849     */
11850    public boolean checkCallerIsHomeApp() {
11851        final Intent intent = new Intent(Intent.ACTION_MAIN);
11852        intent.addCategory(Intent.CATEGORY_HOME);
11853
11854        final int callingUid = Binder.getCallingUid();
11855        final int callingUserId = UserHandle.getCallingUserId();
11856        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11857        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11858                false, false, callingUserId);
11859
11860        if (preferredHome != null) {
11861            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11862                return true;
11863            }
11864        } else {
11865            for (ResolveInfo info : allHomes) {
11866                if (callingUid == info.activityInfo.applicationInfo.uid) {
11867                    return true;
11868                }
11869            }
11870        }
11871
11872        return false;
11873    }
11874
11875    /**
11876     * Enforce that calling UID is the current home app. This handles both the
11877     * case where the user has selected a specific home app, and where there is
11878     * only one home app.
11879     */
11880    public void enforceCallerIsHomeApp() {
11881        if (!checkCallerIsHomeApp()) {
11882            throw new SecurityException("Caller is not currently selected home app");
11883        }
11884    }
11885
11886    @Override
11887    public void setApplicationEnabledSetting(String appPackageName,
11888            int newState, int flags, int userId, String callingPackage) {
11889        if (!sUserManager.exists(userId)) return;
11890        if (callingPackage == null) {
11891            callingPackage = Integer.toString(Binder.getCallingUid());
11892        }
11893        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11894    }
11895
11896    @Override
11897    public void setComponentEnabledSetting(ComponentName componentName,
11898            int newState, int flags, int userId) {
11899        if (!sUserManager.exists(userId)) return;
11900        setEnabledSetting(componentName.getPackageName(),
11901                componentName.getClassName(), newState, flags, userId, null);
11902    }
11903
11904    private void setEnabledSetting(final String packageName, String className, int newState,
11905            final int flags, int userId, String callingPackage) {
11906        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11907              || newState == COMPONENT_ENABLED_STATE_ENABLED
11908              || newState == COMPONENT_ENABLED_STATE_DISABLED
11909              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11910              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11911            throw new IllegalArgumentException("Invalid new component state: "
11912                    + newState);
11913        }
11914        PackageSetting pkgSetting;
11915        final int uid = Binder.getCallingUid();
11916        final int permission = mContext.checkCallingOrSelfPermission(
11917                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11918        enforceCrossUserPermission(uid, userId, false, "set enabled");
11919        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11920        boolean sendNow = false;
11921        boolean isApp = (className == null);
11922        String componentName = isApp ? packageName : className;
11923        int packageUid = -1;
11924        ArrayList<String> components;
11925
11926        // writer
11927        synchronized (mPackages) {
11928            pkgSetting = mSettings.mPackages.get(packageName);
11929            if (pkgSetting == null) {
11930                if (className == null) {
11931                    throw new IllegalArgumentException(
11932                            "Unknown package: " + packageName);
11933                }
11934                throw new IllegalArgumentException(
11935                        "Unknown component: " + packageName
11936                        + "/" + className);
11937            }
11938            // Allow root and verify that userId is not being specified by a different user
11939            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11940                throw new SecurityException(
11941                        "Permission Denial: attempt to change component state from pid="
11942                        + Binder.getCallingPid()
11943                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11944            }
11945            if (className == null) {
11946                // We're dealing with an application/package level state change
11947                if (pkgSetting.getEnabled(userId) == newState) {
11948                    // Nothing to do
11949                    return;
11950                }
11951                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11952                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11953                    // Don't care about who enables an app.
11954                    callingPackage = null;
11955                }
11956                pkgSetting.setEnabled(newState, userId, callingPackage);
11957                // pkgSetting.pkg.mSetEnabled = newState;
11958            } else {
11959                // We're dealing with a component level state change
11960                // First, verify that this is a valid class name.
11961                PackageParser.Package pkg = pkgSetting.pkg;
11962                if (pkg == null || !pkg.hasComponentClassName(className)) {
11963                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11964                        throw new IllegalArgumentException("Component class " + className
11965                                + " does not exist in " + packageName);
11966                    } else {
11967                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11968                                + className + " does not exist in " + packageName);
11969                    }
11970                }
11971                switch (newState) {
11972                case COMPONENT_ENABLED_STATE_ENABLED:
11973                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11974                        return;
11975                    }
11976                    break;
11977                case COMPONENT_ENABLED_STATE_DISABLED:
11978                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11979                        return;
11980                    }
11981                    break;
11982                case COMPONENT_ENABLED_STATE_DEFAULT:
11983                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11984                        return;
11985                    }
11986                    break;
11987                default:
11988                    Slog.e(TAG, "Invalid new component state: " + newState);
11989                    return;
11990                }
11991            }
11992            mSettings.writePackageRestrictionsLPr(userId);
11993            components = mPendingBroadcasts.get(userId, packageName);
11994            final boolean newPackage = components == null;
11995            if (newPackage) {
11996                components = new ArrayList<String>();
11997            }
11998            if (!components.contains(componentName)) {
11999                components.add(componentName);
12000            }
12001            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12002                sendNow = true;
12003                // Purge entry from pending broadcast list if another one exists already
12004                // since we are sending one right away.
12005                mPendingBroadcasts.remove(userId, packageName);
12006            } else {
12007                if (newPackage) {
12008                    mPendingBroadcasts.put(userId, packageName, components);
12009                }
12010                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12011                    // Schedule a message
12012                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12013                }
12014            }
12015        }
12016
12017        long callingId = Binder.clearCallingIdentity();
12018        try {
12019            if (sendNow) {
12020                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12021                sendPackageChangedBroadcast(packageName,
12022                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12023            }
12024        } finally {
12025            Binder.restoreCallingIdentity(callingId);
12026        }
12027    }
12028
12029    private void sendPackageChangedBroadcast(String packageName,
12030            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12031        if (DEBUG_INSTALL)
12032            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12033                    + componentNames);
12034        Bundle extras = new Bundle(4);
12035        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12036        String nameList[] = new String[componentNames.size()];
12037        componentNames.toArray(nameList);
12038        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12039        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12040        extras.putInt(Intent.EXTRA_UID, packageUid);
12041        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12042                new int[] {UserHandle.getUserId(packageUid)});
12043    }
12044
12045    @Override
12046    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12047        if (!sUserManager.exists(userId)) return;
12048        final int uid = Binder.getCallingUid();
12049        final int permission = mContext.checkCallingOrSelfPermission(
12050                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12051        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12052        enforceCrossUserPermission(uid, userId, true, "stop package");
12053        // writer
12054        synchronized (mPackages) {
12055            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12056                    uid, userId)) {
12057                scheduleWritePackageRestrictionsLocked(userId);
12058            }
12059        }
12060    }
12061
12062    @Override
12063    public String getInstallerPackageName(String packageName) {
12064        // reader
12065        synchronized (mPackages) {
12066            return mSettings.getInstallerPackageNameLPr(packageName);
12067        }
12068    }
12069
12070    @Override
12071    public int getApplicationEnabledSetting(String packageName, int userId) {
12072        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12073        int uid = Binder.getCallingUid();
12074        enforceCrossUserPermission(uid, userId, false, "get enabled");
12075        // reader
12076        synchronized (mPackages) {
12077            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12078        }
12079    }
12080
12081    @Override
12082    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12083        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12084        int uid = Binder.getCallingUid();
12085        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12086        // reader
12087        synchronized (mPackages) {
12088            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12089        }
12090    }
12091
12092    @Override
12093    public void enterSafeMode() {
12094        enforceSystemOrRoot("Only the system can request entering safe mode");
12095
12096        if (!mSystemReady) {
12097            mSafeMode = true;
12098        }
12099    }
12100
12101    @Override
12102    public void systemReady() {
12103        mSystemReady = true;
12104
12105        // Read the compatibilty setting when the system is ready.
12106        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12107                mContext.getContentResolver(),
12108                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12109        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12110        if (DEBUG_SETTINGS) {
12111            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12112        }
12113
12114        synchronized (mPackages) {
12115            // Verify that all of the preferred activity components actually
12116            // exist.  It is possible for applications to be updated and at
12117            // that point remove a previously declared activity component that
12118            // had been set as a preferred activity.  We try to clean this up
12119            // the next time we encounter that preferred activity, but it is
12120            // possible for the user flow to never be able to return to that
12121            // situation so here we do a sanity check to make sure we haven't
12122            // left any junk around.
12123            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12124            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12125                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12126                removed.clear();
12127                for (PreferredActivity pa : pir.filterSet()) {
12128                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12129                        removed.add(pa);
12130                    }
12131                }
12132                if (removed.size() > 0) {
12133                    for (int r=0; r<removed.size(); r++) {
12134                        PreferredActivity pa = removed.get(r);
12135                        Slog.w(TAG, "Removing dangling preferred activity: "
12136                                + pa.mPref.mComponent);
12137                        pir.removeFilter(pa);
12138                    }
12139                    mSettings.writePackageRestrictionsLPr(
12140                            mSettings.mPreferredActivities.keyAt(i));
12141                }
12142            }
12143        }
12144        sUserManager.systemReady();
12145    }
12146
12147    @Override
12148    public boolean isSafeMode() {
12149        return mSafeMode;
12150    }
12151
12152    @Override
12153    public boolean hasSystemUidErrors() {
12154        return mHasSystemUidErrors;
12155    }
12156
12157    static String arrayToString(int[] array) {
12158        StringBuffer buf = new StringBuffer(128);
12159        buf.append('[');
12160        if (array != null) {
12161            for (int i=0; i<array.length; i++) {
12162                if (i > 0) buf.append(", ");
12163                buf.append(array[i]);
12164            }
12165        }
12166        buf.append(']');
12167        return buf.toString();
12168    }
12169
12170    static class DumpState {
12171        public static final int DUMP_LIBS = 1 << 0;
12172        public static final int DUMP_FEATURES = 1 << 1;
12173        public static final int DUMP_RESOLVERS = 1 << 2;
12174        public static final int DUMP_PERMISSIONS = 1 << 3;
12175        public static final int DUMP_PACKAGES = 1 << 4;
12176        public static final int DUMP_SHARED_USERS = 1 << 5;
12177        public static final int DUMP_MESSAGES = 1 << 6;
12178        public static final int DUMP_PROVIDERS = 1 << 7;
12179        public static final int DUMP_VERIFIERS = 1 << 8;
12180        public static final int DUMP_PREFERRED = 1 << 9;
12181        public static final int DUMP_PREFERRED_XML = 1 << 10;
12182        public static final int DUMP_KEYSETS = 1 << 11;
12183        public static final int DUMP_VERSION = 1 << 12;
12184        public static final int DUMP_INSTALLS = 1 << 13;
12185
12186        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12187
12188        private int mTypes;
12189
12190        private int mOptions;
12191
12192        private boolean mTitlePrinted;
12193
12194        private SharedUserSetting mSharedUser;
12195
12196        public boolean isDumping(int type) {
12197            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12198                return true;
12199            }
12200
12201            return (mTypes & type) != 0;
12202        }
12203
12204        public void setDump(int type) {
12205            mTypes |= type;
12206        }
12207
12208        public boolean isOptionEnabled(int option) {
12209            return (mOptions & option) != 0;
12210        }
12211
12212        public void setOptionEnabled(int option) {
12213            mOptions |= option;
12214        }
12215
12216        public boolean onTitlePrinted() {
12217            final boolean printed = mTitlePrinted;
12218            mTitlePrinted = true;
12219            return printed;
12220        }
12221
12222        public boolean getTitlePrinted() {
12223            return mTitlePrinted;
12224        }
12225
12226        public void setTitlePrinted(boolean enabled) {
12227            mTitlePrinted = enabled;
12228        }
12229
12230        public SharedUserSetting getSharedUser() {
12231            return mSharedUser;
12232        }
12233
12234        public void setSharedUser(SharedUserSetting user) {
12235            mSharedUser = user;
12236        }
12237    }
12238
12239    @Override
12240    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12241        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12242                != PackageManager.PERMISSION_GRANTED) {
12243            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12244                    + Binder.getCallingPid()
12245                    + ", uid=" + Binder.getCallingUid()
12246                    + " without permission "
12247                    + android.Manifest.permission.DUMP);
12248            return;
12249        }
12250
12251        DumpState dumpState = new DumpState();
12252        boolean fullPreferred = false;
12253        boolean checkin = false;
12254
12255        String packageName = null;
12256
12257        int opti = 0;
12258        while (opti < args.length) {
12259            String opt = args[opti];
12260            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12261                break;
12262            }
12263            opti++;
12264            if ("-a".equals(opt)) {
12265                // Right now we only know how to print all.
12266            } else if ("-h".equals(opt)) {
12267                pw.println("Package manager dump options:");
12268                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12269                pw.println("    --checkin: dump for a checkin");
12270                pw.println("    -f: print details of intent filters");
12271                pw.println("    -h: print this help");
12272                pw.println("  cmd may be one of:");
12273                pw.println("    l[ibraries]: list known shared libraries");
12274                pw.println("    f[ibraries]: list device features");
12275                pw.println("    k[eysets]: print known keysets");
12276                pw.println("    r[esolvers]: dump intent resolvers");
12277                pw.println("    perm[issions]: dump permissions");
12278                pw.println("    pref[erred]: print preferred package settings");
12279                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12280                pw.println("    prov[iders]: dump content providers");
12281                pw.println("    p[ackages]: dump installed packages");
12282                pw.println("    s[hared-users]: dump shared user IDs");
12283                pw.println("    m[essages]: print collected runtime messages");
12284                pw.println("    v[erifiers]: print package verifier info");
12285                pw.println("    version: print database version info");
12286                pw.println("    write: write current settings now");
12287                pw.println("    <package.name>: info about given package");
12288                pw.println("    installs: details about install sessions");
12289                return;
12290            } else if ("--checkin".equals(opt)) {
12291                checkin = true;
12292            } else if ("-f".equals(opt)) {
12293                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12294            } else {
12295                pw.println("Unknown argument: " + opt + "; use -h for help");
12296            }
12297        }
12298
12299        // Is the caller requesting to dump a particular piece of data?
12300        if (opti < args.length) {
12301            String cmd = args[opti];
12302            opti++;
12303            // Is this a package name?
12304            if ("android".equals(cmd) || cmd.contains(".")) {
12305                packageName = cmd;
12306                // When dumping a single package, we always dump all of its
12307                // filter information since the amount of data will be reasonable.
12308                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12309            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12310                dumpState.setDump(DumpState.DUMP_LIBS);
12311            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12312                dumpState.setDump(DumpState.DUMP_FEATURES);
12313            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12314                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12315            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12316                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12317            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12318                dumpState.setDump(DumpState.DUMP_PREFERRED);
12319            } else if ("preferred-xml".equals(cmd)) {
12320                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12321                if (opti < args.length && "--full".equals(args[opti])) {
12322                    fullPreferred = true;
12323                    opti++;
12324                }
12325            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12326                dumpState.setDump(DumpState.DUMP_PACKAGES);
12327            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12328                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12329            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12330                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12331            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12332                dumpState.setDump(DumpState.DUMP_MESSAGES);
12333            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12334                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12335            } else if ("version".equals(cmd)) {
12336                dumpState.setDump(DumpState.DUMP_VERSION);
12337            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12338                dumpState.setDump(DumpState.DUMP_KEYSETS);
12339            } else if ("write".equals(cmd)) {
12340                synchronized (mPackages) {
12341                    mSettings.writeLPr();
12342                    pw.println("Settings written.");
12343                    return;
12344                }
12345            } else if ("installs".equals(cmd)) {
12346                dumpState.setDump(DumpState.DUMP_INSTALLS);
12347            }
12348        }
12349
12350        if (checkin) {
12351            pw.println("vers,1");
12352        }
12353
12354        // reader
12355        synchronized (mPackages) {
12356            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12357                if (!checkin) {
12358                    if (dumpState.onTitlePrinted())
12359                        pw.println();
12360                    pw.println("Database versions:");
12361                    pw.print("  SDK Version:");
12362                    pw.print(" internal=");
12363                    pw.print(mSettings.mInternalSdkPlatform);
12364                    pw.print(" external=");
12365                    pw.println(mSettings.mExternalSdkPlatform);
12366                    pw.print("  DB Version:");
12367                    pw.print(" internal=");
12368                    pw.print(mSettings.mInternalDatabaseVersion);
12369                    pw.print(" external=");
12370                    pw.println(mSettings.mExternalDatabaseVersion);
12371                }
12372            }
12373
12374            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12375                if (!checkin) {
12376                    if (dumpState.onTitlePrinted())
12377                        pw.println();
12378                    pw.println("Verifiers:");
12379                    pw.print("  Required: ");
12380                    pw.print(mRequiredVerifierPackage);
12381                    pw.print(" (uid=");
12382                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12383                    pw.println(")");
12384                } else if (mRequiredVerifierPackage != null) {
12385                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12386                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12387                }
12388            }
12389
12390            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12391                boolean printedHeader = false;
12392                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12393                while (it.hasNext()) {
12394                    String name = it.next();
12395                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12396                    if (!checkin) {
12397                        if (!printedHeader) {
12398                            if (dumpState.onTitlePrinted())
12399                                pw.println();
12400                            pw.println("Libraries:");
12401                            printedHeader = true;
12402                        }
12403                        pw.print("  ");
12404                    } else {
12405                        pw.print("lib,");
12406                    }
12407                    pw.print(name);
12408                    if (!checkin) {
12409                        pw.print(" -> ");
12410                    }
12411                    if (ent.path != null) {
12412                        if (!checkin) {
12413                            pw.print("(jar) ");
12414                            pw.print(ent.path);
12415                        } else {
12416                            pw.print(",jar,");
12417                            pw.print(ent.path);
12418                        }
12419                    } else {
12420                        if (!checkin) {
12421                            pw.print("(apk) ");
12422                            pw.print(ent.apk);
12423                        } else {
12424                            pw.print(",apk,");
12425                            pw.print(ent.apk);
12426                        }
12427                    }
12428                    pw.println();
12429                }
12430            }
12431
12432            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12433                if (dumpState.onTitlePrinted())
12434                    pw.println();
12435                if (!checkin) {
12436                    pw.println("Features:");
12437                }
12438                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12439                while (it.hasNext()) {
12440                    String name = it.next();
12441                    if (!checkin) {
12442                        pw.print("  ");
12443                    } else {
12444                        pw.print("feat,");
12445                    }
12446                    pw.println(name);
12447                }
12448            }
12449
12450            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12451                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12452                        : "Activity Resolver Table:", "  ", packageName,
12453                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12454                    dumpState.setTitlePrinted(true);
12455                }
12456                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12457                        : "Receiver Resolver Table:", "  ", packageName,
12458                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12459                    dumpState.setTitlePrinted(true);
12460                }
12461                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12462                        : "Service Resolver Table:", "  ", packageName,
12463                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12464                    dumpState.setTitlePrinted(true);
12465                }
12466                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12467                        : "Provider Resolver Table:", "  ", packageName,
12468                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12469                    dumpState.setTitlePrinted(true);
12470                }
12471            }
12472
12473            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12474                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12475                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12476                    int user = mSettings.mPreferredActivities.keyAt(i);
12477                    if (pir.dump(pw,
12478                            dumpState.getTitlePrinted()
12479                                ? "\nPreferred Activities User " + user + ":"
12480                                : "Preferred Activities User " + user + ":", "  ",
12481                            packageName, true)) {
12482                        dumpState.setTitlePrinted(true);
12483                    }
12484                }
12485            }
12486
12487            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12488                pw.flush();
12489                FileOutputStream fout = new FileOutputStream(fd);
12490                BufferedOutputStream str = new BufferedOutputStream(fout);
12491                XmlSerializer serializer = new FastXmlSerializer();
12492                try {
12493                    serializer.setOutput(str, "utf-8");
12494                    serializer.startDocument(null, true);
12495                    serializer.setFeature(
12496                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12497                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12498                    serializer.endDocument();
12499                    serializer.flush();
12500                } catch (IllegalArgumentException e) {
12501                    pw.println("Failed writing: " + e);
12502                } catch (IllegalStateException e) {
12503                    pw.println("Failed writing: " + e);
12504                } catch (IOException e) {
12505                    pw.println("Failed writing: " + e);
12506                }
12507            }
12508
12509            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12510                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12511                if (packageName == null) {
12512                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12513                        if (iperm == 0) {
12514                            if (dumpState.onTitlePrinted())
12515                                pw.println();
12516                            pw.println("AppOp Permissions:");
12517                        }
12518                        pw.print("  AppOp Permission ");
12519                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12520                        pw.println(":");
12521                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12522                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12523                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12524                        }
12525                    }
12526                }
12527            }
12528
12529            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12530                boolean printedSomething = false;
12531                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12532                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12533                        continue;
12534                    }
12535                    if (!printedSomething) {
12536                        if (dumpState.onTitlePrinted())
12537                            pw.println();
12538                        pw.println("Registered ContentProviders:");
12539                        printedSomething = true;
12540                    }
12541                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12542                    pw.print("    "); pw.println(p.toString());
12543                }
12544                printedSomething = false;
12545                for (Map.Entry<String, PackageParser.Provider> entry :
12546                        mProvidersByAuthority.entrySet()) {
12547                    PackageParser.Provider p = entry.getValue();
12548                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12549                        continue;
12550                    }
12551                    if (!printedSomething) {
12552                        if (dumpState.onTitlePrinted())
12553                            pw.println();
12554                        pw.println("ContentProvider Authorities:");
12555                        printedSomething = true;
12556                    }
12557                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12558                    pw.print("    "); pw.println(p.toString());
12559                    if (p.info != null && p.info.applicationInfo != null) {
12560                        final String appInfo = p.info.applicationInfo.toString();
12561                        pw.print("      applicationInfo="); pw.println(appInfo);
12562                    }
12563                }
12564            }
12565
12566            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12567                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12568            }
12569
12570            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12571                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12572            }
12573
12574            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12575                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12576            }
12577
12578            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12579                if (dumpState.onTitlePrinted()) pw.println();
12580                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12581            }
12582
12583            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12584                if (dumpState.onTitlePrinted()) pw.println();
12585                mSettings.dumpReadMessagesLPr(pw, dumpState);
12586
12587                pw.println();
12588                pw.println("Package warning messages:");
12589                final File fname = getSettingsProblemFile();
12590                FileInputStream in = null;
12591                try {
12592                    in = new FileInputStream(fname);
12593                    final int avail = in.available();
12594                    final byte[] data = new byte[avail];
12595                    in.read(data);
12596                    pw.print(new String(data));
12597                } catch (FileNotFoundException e) {
12598                } catch (IOException e) {
12599                } finally {
12600                    if (in != null) {
12601                        try {
12602                            in.close();
12603                        } catch (IOException e) {
12604                        }
12605                    }
12606                }
12607            }
12608        }
12609    }
12610
12611    // ------- apps on sdcard specific code -------
12612    static final boolean DEBUG_SD_INSTALL = false;
12613
12614    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12615
12616    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12617
12618    private boolean mMediaMounted = false;
12619
12620    static String getEncryptKey() {
12621        try {
12622            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12623                    SD_ENCRYPTION_KEYSTORE_NAME);
12624            if (sdEncKey == null) {
12625                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12626                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12627                if (sdEncKey == null) {
12628                    Slog.e(TAG, "Failed to create encryption keys");
12629                    return null;
12630                }
12631            }
12632            return sdEncKey;
12633        } catch (NoSuchAlgorithmException nsae) {
12634            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12635            return null;
12636        } catch (IOException ioe) {
12637            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12638            return null;
12639        }
12640    }
12641
12642    /*
12643     * Update media status on PackageManager.
12644     */
12645    @Override
12646    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12647        int callingUid = Binder.getCallingUid();
12648        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12649            throw new SecurityException("Media status can only be updated by the system");
12650        }
12651        // reader; this apparently protects mMediaMounted, but should probably
12652        // be a different lock in that case.
12653        synchronized (mPackages) {
12654            Log.i(TAG, "Updating external media status from "
12655                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12656                    + (mediaStatus ? "mounted" : "unmounted"));
12657            if (DEBUG_SD_INSTALL)
12658                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12659                        + ", mMediaMounted=" + mMediaMounted);
12660            if (mediaStatus == mMediaMounted) {
12661                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12662                        : 0, -1);
12663                mHandler.sendMessage(msg);
12664                return;
12665            }
12666            mMediaMounted = mediaStatus;
12667        }
12668        // Queue up an async operation since the package installation may take a
12669        // little while.
12670        mHandler.post(new Runnable() {
12671            public void run() {
12672                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12673            }
12674        });
12675    }
12676
12677    /**
12678     * Called by MountService when the initial ASECs to scan are available.
12679     * Should block until all the ASEC containers are finished being scanned.
12680     */
12681    public void scanAvailableAsecs() {
12682        updateExternalMediaStatusInner(true, false, false);
12683        if (mShouldRestoreconData) {
12684            SELinuxMMAC.setRestoreconDone();
12685            mShouldRestoreconData = false;
12686        }
12687    }
12688
12689    /*
12690     * Collect information of applications on external media, map them against
12691     * existing containers and update information based on current mount status.
12692     * Please note that we always have to report status if reportStatus has been
12693     * set to true especially when unloading packages.
12694     */
12695    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12696            boolean externalStorage) {
12697        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12698        int[] uidArr = EmptyArray.INT;
12699
12700        final String[] list = PackageHelper.getSecureContainerList();
12701        if (ArrayUtils.isEmpty(list)) {
12702            Log.i(TAG, "No secure containers found");
12703        } else {
12704            // Process list of secure containers and categorize them
12705            // as active or stale based on their package internal state.
12706
12707            // reader
12708            synchronized (mPackages) {
12709                for (String cid : list) {
12710                    // Leave stages untouched for now; installer service owns them
12711                    if (PackageInstallerService.isStageName(cid)) continue;
12712
12713                    if (DEBUG_SD_INSTALL)
12714                        Log.i(TAG, "Processing container " + cid);
12715                    String pkgName = getAsecPackageName(cid);
12716                    if (pkgName == null) {
12717                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12718                        continue;
12719                    }
12720                    if (DEBUG_SD_INSTALL)
12721                        Log.i(TAG, "Looking for pkg : " + pkgName);
12722
12723                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12724                    if (ps == null) {
12725                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12726                        continue;
12727                    }
12728
12729                    /*
12730                     * Skip packages that are not external if we're unmounting
12731                     * external storage.
12732                     */
12733                    if (externalStorage && !isMounted && !isExternal(ps)) {
12734                        continue;
12735                    }
12736
12737                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12738                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12739                    // The package status is changed only if the code path
12740                    // matches between settings and the container id.
12741                    if (ps.codePathString != null
12742                            && ps.codePathString.startsWith(args.getCodePath())) {
12743                        if (DEBUG_SD_INSTALL) {
12744                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12745                                    + " at code path: " + ps.codePathString);
12746                        }
12747
12748                        // We do have a valid package installed on sdcard
12749                        processCids.put(args, ps.codePathString);
12750                        final int uid = ps.appId;
12751                        if (uid != -1) {
12752                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12753                        }
12754                    } else {
12755                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12756                                + ps.codePathString);
12757                    }
12758                }
12759            }
12760
12761            Arrays.sort(uidArr);
12762        }
12763
12764        // Process packages with valid entries.
12765        if (isMounted) {
12766            if (DEBUG_SD_INSTALL)
12767                Log.i(TAG, "Loading packages");
12768            loadMediaPackages(processCids, uidArr);
12769            startCleaningPackages();
12770            mInstallerService.onSecureContainersAvailable();
12771        } else {
12772            if (DEBUG_SD_INSTALL)
12773                Log.i(TAG, "Unloading packages");
12774            unloadMediaPackages(processCids, uidArr, reportStatus);
12775        }
12776    }
12777
12778    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12779            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12780        int size = pkgList.size();
12781        if (size > 0) {
12782            // Send broadcasts here
12783            Bundle extras = new Bundle();
12784            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12785                    .toArray(new String[size]));
12786            if (uidArr != null) {
12787                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12788            }
12789            if (replacing) {
12790                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12791            }
12792            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12793                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12794            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12795        }
12796    }
12797
12798   /*
12799     * Look at potentially valid container ids from processCids If package
12800     * information doesn't match the one on record or package scanning fails,
12801     * the cid is added to list of removeCids. We currently don't delete stale
12802     * containers.
12803     */
12804    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12805        ArrayList<String> pkgList = new ArrayList<String>();
12806        Set<AsecInstallArgs> keys = processCids.keySet();
12807
12808        for (AsecInstallArgs args : keys) {
12809            String codePath = processCids.get(args);
12810            if (DEBUG_SD_INSTALL)
12811                Log.i(TAG, "Loading container : " + args.cid);
12812            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12813            try {
12814                // Make sure there are no container errors first.
12815                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12816                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12817                            + " when installing from sdcard");
12818                    continue;
12819                }
12820                // Check code path here.
12821                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12822                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12823                            + " does not match one in settings " + codePath);
12824                    continue;
12825                }
12826                // Parse package
12827                int parseFlags = mDefParseFlags;
12828                if (args.isExternal()) {
12829                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12830                }
12831                if (args.isFwdLocked()) {
12832                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12833                }
12834
12835                synchronized (mInstallLock) {
12836                    PackageParser.Package pkg = null;
12837                    try {
12838                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12839                    } catch (PackageManagerException e) {
12840                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12841                    }
12842                    // Scan the package
12843                    if (pkg != null) {
12844                        /*
12845                         * TODO why is the lock being held? doPostInstall is
12846                         * called in other places without the lock. This needs
12847                         * to be straightened out.
12848                         */
12849                        // writer
12850                        synchronized (mPackages) {
12851                            retCode = PackageManager.INSTALL_SUCCEEDED;
12852                            pkgList.add(pkg.packageName);
12853                            // Post process args
12854                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12855                                    pkg.applicationInfo.uid);
12856                        }
12857                    } else {
12858                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12859                    }
12860                }
12861
12862            } finally {
12863                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12864                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12865                }
12866            }
12867        }
12868        // writer
12869        synchronized (mPackages) {
12870            // If the platform SDK has changed since the last time we booted,
12871            // we need to re-grant app permission to catch any new ones that
12872            // appear. This is really a hack, and means that apps can in some
12873            // cases get permissions that the user didn't initially explicitly
12874            // allow... it would be nice to have some better way to handle
12875            // this situation.
12876            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12877            if (regrantPermissions)
12878                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12879                        + mSdkVersion + "; regranting permissions for external storage");
12880            mSettings.mExternalSdkPlatform = mSdkVersion;
12881
12882            // Make sure group IDs have been assigned, and any permission
12883            // changes in other apps are accounted for
12884            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12885                    | (regrantPermissions
12886                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12887                            : 0));
12888
12889            mSettings.updateExternalDatabaseVersion();
12890
12891            // can downgrade to reader
12892            // Persist settings
12893            mSettings.writeLPr();
12894        }
12895        // Send a broadcast to let everyone know we are done processing
12896        if (pkgList.size() > 0) {
12897            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12898        }
12899    }
12900
12901   /*
12902     * Utility method to unload a list of specified containers
12903     */
12904    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12905        // Just unmount all valid containers.
12906        for (AsecInstallArgs arg : cidArgs) {
12907            synchronized (mInstallLock) {
12908                arg.doPostDeleteLI(false);
12909           }
12910       }
12911   }
12912
12913    /*
12914     * Unload packages mounted on external media. This involves deleting package
12915     * data from internal structures, sending broadcasts about diabled packages,
12916     * gc'ing to free up references, unmounting all secure containers
12917     * corresponding to packages on external media, and posting a
12918     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12919     * that we always have to post this message if status has been requested no
12920     * matter what.
12921     */
12922    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12923            final boolean reportStatus) {
12924        if (DEBUG_SD_INSTALL)
12925            Log.i(TAG, "unloading media packages");
12926        ArrayList<String> pkgList = new ArrayList<String>();
12927        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12928        final Set<AsecInstallArgs> keys = processCids.keySet();
12929        for (AsecInstallArgs args : keys) {
12930            String pkgName = args.getPackageName();
12931            if (DEBUG_SD_INSTALL)
12932                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12933            // Delete package internally
12934            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12935            synchronized (mInstallLock) {
12936                boolean res = deletePackageLI(pkgName, null, false, null, null,
12937                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12938                if (res) {
12939                    pkgList.add(pkgName);
12940                } else {
12941                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12942                    failedList.add(args);
12943                }
12944            }
12945        }
12946
12947        // reader
12948        synchronized (mPackages) {
12949            // We didn't update the settings after removing each package;
12950            // write them now for all packages.
12951            mSettings.writeLPr();
12952        }
12953
12954        // We have to absolutely send UPDATED_MEDIA_STATUS only
12955        // after confirming that all the receivers processed the ordered
12956        // broadcast when packages get disabled, force a gc to clean things up.
12957        // and unload all the containers.
12958        if (pkgList.size() > 0) {
12959            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12960                    new IIntentReceiver.Stub() {
12961                public void performReceive(Intent intent, int resultCode, String data,
12962                        Bundle extras, boolean ordered, boolean sticky,
12963                        int sendingUser) throws RemoteException {
12964                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12965                            reportStatus ? 1 : 0, 1, keys);
12966                    mHandler.sendMessage(msg);
12967                }
12968            });
12969        } else {
12970            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12971                    keys);
12972            mHandler.sendMessage(msg);
12973        }
12974    }
12975
12976    /** Binder call */
12977    @Override
12978    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12979            final int flags) {
12980        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12981        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12982        int returnCode = PackageManager.MOVE_SUCCEEDED;
12983        int currFlags = 0;
12984        int newFlags = 0;
12985        // reader
12986        synchronized (mPackages) {
12987            PackageParser.Package pkg = mPackages.get(packageName);
12988            if (pkg == null) {
12989                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12990            } else {
12991                // Disable moving fwd locked apps and system packages
12992                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12993                    Slog.w(TAG, "Cannot move system application");
12994                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12995                } else if (pkg.mOperationPending) {
12996                    Slog.w(TAG, "Attempt to move package which has pending operations");
12997                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12998                } else {
12999                    // Find install location first
13000                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13001                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13002                        Slog.w(TAG, "Ambigous flags specified for move location.");
13003                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13004                    } else {
13005                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
13006                                : PackageManager.INSTALL_INTERNAL;
13007                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
13008                                : PackageManager.INSTALL_INTERNAL;
13009
13010                        if (newFlags == currFlags) {
13011                            Slog.w(TAG, "No move required. Trying to move to same location");
13012                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13013                        } else {
13014                            if (isForwardLocked(pkg)) {
13015                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13016                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13017                            }
13018                        }
13019                    }
13020                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13021                        pkg.mOperationPending = true;
13022                    }
13023                }
13024            }
13025
13026            /*
13027             * TODO this next block probably shouldn't be inside the lock. We
13028             * can't guarantee these won't change after this is fired off
13029             * anyway.
13030             */
13031            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13032                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user),
13033                        returnCode);
13034            } else {
13035                Message msg = mHandler.obtainMessage(INIT_COPY);
13036                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13037                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13038                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13039                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13040                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets);
13041                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13042                        instructionSets, pkg.applicationInfo.uid, user);
13043                msg.obj = mp;
13044                mHandler.sendMessage(msg);
13045            }
13046        }
13047    }
13048
13049    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13050        // Queue up an async operation since the package deletion may take a
13051        // little while.
13052        mHandler.post(new Runnable() {
13053            public void run() {
13054                // TODO fix this; this does nothing.
13055                mHandler.removeCallbacks(this);
13056                int returnCode = currentStatus;
13057                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13058                    int uidArr[] = null;
13059                    ArrayList<String> pkgList = null;
13060                    synchronized (mPackages) {
13061                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13062                        if (pkg == null) {
13063                            Slog.w(TAG, " Package " + mp.packageName
13064                                    + " doesn't exist. Aborting move");
13065                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13066                        } else if (!mp.srcArgs.getCodePath().equals(
13067                                pkg.applicationInfo.getCodePath())) {
13068                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13069                                    + mp.srcArgs.getCodePath() + " to "
13070                                    + pkg.applicationInfo.getCodePath()
13071                                    + " Aborting move and returning error");
13072                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13073                        } else {
13074                            uidArr = new int[] {
13075                                pkg.applicationInfo.uid
13076                            };
13077                            pkgList = new ArrayList<String>();
13078                            pkgList.add(mp.packageName);
13079                        }
13080                    }
13081                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13082                        // Send resources unavailable broadcast
13083                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13084                        // Update package code and resource paths
13085                        synchronized (mInstallLock) {
13086                            synchronized (mPackages) {
13087                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13088                                // Recheck for package again.
13089                                if (pkg == null) {
13090                                    Slog.w(TAG, " Package " + mp.packageName
13091                                            + " doesn't exist. Aborting move");
13092                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13093                                } else if (!mp.srcArgs.getCodePath().equals(
13094                                        pkg.applicationInfo.getCodePath())) {
13095                                    Slog.w(TAG, "Package " + mp.packageName
13096                                            + " code path changed from " + mp.srcArgs.getCodePath()
13097                                            + " to " + pkg.applicationInfo.getCodePath()
13098                                            + " Aborting move and returning error");
13099                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13100                                } else {
13101                                    final String oldCodePath = pkg.codePath;
13102                                    final String newCodePath = mp.targetArgs.getCodePath();
13103                                    final String newResPath = mp.targetArgs.getResourcePath();
13104                                    // TODO: This assumes the new style of installation.
13105                                    // should we look at legacyNativeLibraryPath ?
13106                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13107                                    final File newNativeDir = new File(newNativeRoot);
13108
13109                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13110                                        // TODO(multiArch): Fix this so that it looks at the existing
13111                                        // recorded CPU abis from the package. There's no need for a separate
13112                                        // round of ABI scanning here.
13113                                        NativeLibraryHelper.Handle handle = null;
13114                                        try {
13115                                            handle = NativeLibraryHelper.Handle.create(
13116                                                    new File(newCodePath));
13117                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13118                                                    handle, Build.SUPPORTED_ABIS);
13119                                            if (abi >= 0) {
13120                                                NativeLibraryHelper.copyNativeBinaries(handle,
13121                                                        newNativeDir, Build.SUPPORTED_ABIS[abi]);
13122                                            }
13123                                        } catch (IOException ioe) {
13124                                            Slog.w(TAG, "Unable to extract native libs for package :"
13125                                                    + mp.packageName, ioe);
13126                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13127                                        } finally {
13128                                            IoUtils.closeQuietly(handle);
13129                                        }
13130                                    }
13131
13132                                    final int[] users = sUserManager.getUserIds();
13133                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13134                                        for (int user : users) {
13135                                            // TODO(multiArch): Fix this so that it links to the
13136                                            // correct directory. We're currently pointing to root. but we
13137                                            // must point to the arch specific subdirectory (if applicable).
13138                                            //
13139                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13140                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13141                                                    newNativeRoot, user) < 0) {
13142                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13143                                            }
13144                                        }
13145                                    }
13146
13147                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13148                                        pkg.codePath = newCodePath;
13149                                        pkg.baseCodePath = newCodePath;
13150                                        // Move dex files around
13151                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13152                                            // Moving of dex files failed. Set
13153                                            // error code and abort move.
13154                                            pkg.codePath = oldCodePath;
13155                                            pkg.baseCodePath = oldCodePath;
13156                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13157                                        }
13158                                    }
13159
13160                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13161                                        pkg.applicationInfo.setCodePath(newCodePath);
13162                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13163                                        pkg.applicationInfo.setSplitCodePaths(null);
13164                                        pkg.applicationInfo.setResourcePath(newResPath);
13165                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13166                                        pkg.applicationInfo.setSplitResourcePaths(null);
13167
13168                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13169                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13170                                        ps.codePathString = ps.codePath.getPath();
13171                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13172                                        ps.resourcePathString = ps.resourcePath.getPath();
13173
13174                                        // Note that we don't have to recalculate the primary and secondary
13175                                        // CPU ABIs because they must already have been calculated during the
13176                                        // initial install of the app.
13177                                        ps.legacyNativeLibraryPathString = null;
13178
13179                                        // Set the application info flag
13180                                        // correctly.
13181                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13182                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13183                                        } else {
13184                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13185                                        }
13186                                        ps.setFlags(pkg.applicationInfo.flags);
13187                                        mAppDirs.remove(oldCodePath);
13188                                        mAppDirs.put(newCodePath, pkg);
13189                                        // Persist settings
13190                                        mSettings.writeLPr();
13191                                    }
13192                                }
13193                            }
13194                        }
13195                        // Send resources available broadcast
13196                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13197                    }
13198                }
13199                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13200                    // Clean up failed installation
13201                    if (mp.targetArgs != null) {
13202                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13203                                -1);
13204                    }
13205                } else {
13206                    // Force a gc to clear things up.
13207                    Runtime.getRuntime().gc();
13208                    // Delete older code
13209                    synchronized (mInstallLock) {
13210                        mp.srcArgs.doPostDeleteLI(true);
13211                    }
13212                }
13213
13214                // Allow more operations on this file if we didn't fail because
13215                // an operation was already pending for this package.
13216                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13217                    synchronized (mPackages) {
13218                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13219                        if (pkg != null) {
13220                            pkg.mOperationPending = false;
13221                       }
13222                   }
13223                }
13224
13225                IPackageMoveObserver observer = mp.observer;
13226                if (observer != null) {
13227                    try {
13228                        observer.packageMoved(mp.packageName, returnCode);
13229                    } catch (RemoteException e) {
13230                        Log.i(TAG, "Observer no longer exists.");
13231                    }
13232                }
13233            }
13234        });
13235    }
13236
13237    @Override
13238    public boolean setInstallLocation(int loc) {
13239        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13240                null);
13241        if (getInstallLocation() == loc) {
13242            return true;
13243        }
13244        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13245                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13246            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13247                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13248            return true;
13249        }
13250        return false;
13251   }
13252
13253    @Override
13254    public int getInstallLocation() {
13255        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13256                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13257                PackageHelper.APP_INSTALL_AUTO);
13258    }
13259
13260    /** Called by UserManagerService */
13261    void cleanUpUserLILPw(int userHandle) {
13262        mDirtyUsers.remove(userHandle);
13263        mSettings.removeUserLPw(userHandle);
13264        mPendingBroadcasts.remove(userHandle);
13265        if (mInstaller != null) {
13266            // Technically, we shouldn't be doing this with the package lock
13267            // held.  However, this is very rare, and there is already so much
13268            // other disk I/O going on, that we'll let it slide for now.
13269            mInstaller.removeUserDataDirs(userHandle);
13270        }
13271        mUserNeedsBadging.delete(userHandle);
13272    }
13273
13274    /** Called by UserManagerService */
13275    void createNewUserLILPw(int userHandle, File path) {
13276        if (mInstaller != null) {
13277            mInstaller.createUserConfig(userHandle);
13278            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13279        }
13280    }
13281
13282    @Override
13283    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13284        mContext.enforceCallingOrSelfPermission(
13285                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13286                "Only package verification agents can read the verifier device identity");
13287
13288        synchronized (mPackages) {
13289            return mSettings.getVerifierDeviceIdentityLPw();
13290        }
13291    }
13292
13293    @Override
13294    public void setPermissionEnforced(String permission, boolean enforced) {
13295        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13296        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13297            synchronized (mPackages) {
13298                if (mSettings.mReadExternalStorageEnforced == null
13299                        || mSettings.mReadExternalStorageEnforced != enforced) {
13300                    mSettings.mReadExternalStorageEnforced = enforced;
13301                    mSettings.writeLPr();
13302                }
13303            }
13304            // kill any non-foreground processes so we restart them and
13305            // grant/revoke the GID.
13306            final IActivityManager am = ActivityManagerNative.getDefault();
13307            if (am != null) {
13308                final long token = Binder.clearCallingIdentity();
13309                try {
13310                    am.killProcessesBelowForeground("setPermissionEnforcement");
13311                } catch (RemoteException e) {
13312                } finally {
13313                    Binder.restoreCallingIdentity(token);
13314                }
13315            }
13316        } else {
13317            throw new IllegalArgumentException("No selective enforcement for " + permission);
13318        }
13319    }
13320
13321    @Override
13322    @Deprecated
13323    public boolean isPermissionEnforced(String permission) {
13324        return true;
13325    }
13326
13327    @Override
13328    public boolean isStorageLow() {
13329        final long token = Binder.clearCallingIdentity();
13330        try {
13331            final DeviceStorageMonitorInternal
13332                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13333            if (dsm != null) {
13334                return dsm.isMemoryLow();
13335            } else {
13336                return false;
13337            }
13338        } finally {
13339            Binder.restoreCallingIdentity(token);
13340        }
13341    }
13342
13343    @Override
13344    public IPackageInstaller getPackageInstaller() {
13345        return mInstallerService;
13346    }
13347
13348    private boolean userNeedsBadging(int userId) {
13349        int index = mUserNeedsBadging.indexOfKey(userId);
13350        if (index < 0) {
13351            final UserInfo userInfo;
13352            final long token = Binder.clearCallingIdentity();
13353            try {
13354                userInfo = sUserManager.getUserInfo(userId);
13355            } finally {
13356                Binder.restoreCallingIdentity(token);
13357            }
13358            final boolean b;
13359            if (userInfo != null && userInfo.isManagedProfile()) {
13360                b = true;
13361            } else {
13362                b = false;
13363            }
13364            mUserNeedsBadging.put(userId, b);
13365            return b;
13366        }
13367        return mUserNeedsBadging.valueAt(index);
13368    }
13369
13370    @Override
13371    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13372        if (packageName == null || alias == null) {
13373            return null;
13374        }
13375        synchronized(mPackages) {
13376            final PackageParser.Package pkg = mPackages.get(packageName);
13377            if (pkg == null) {
13378                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13379                throw new IllegalArgumentException("Unknown package: " + packageName);
13380            }
13381            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13382                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13383                throw new SecurityException("May not access KeySets defined by"
13384                        + " aliases in other applications.");
13385            }
13386            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13387            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13388        }
13389    }
13390
13391    @Override
13392    public KeySetHandle getSigningKeySet(String packageName) {
13393        if (packageName == null) {
13394            return null;
13395        }
13396        synchronized(mPackages) {
13397            final PackageParser.Package pkg = mPackages.get(packageName);
13398            if (pkg == null) {
13399                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13400                throw new IllegalArgumentException("Unknown package: " + packageName);
13401            }
13402            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13403                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13404                throw new SecurityException("May not access signing KeySet of other apps.");
13405            }
13406            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13407            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13408        }
13409    }
13410
13411    @Override
13412    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13413        if (packageName == null || ks == null) {
13414            return false;
13415        }
13416        synchronized(mPackages) {
13417            final PackageParser.Package pkg = mPackages.get(packageName);
13418            if (pkg == null) {
13419                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13420                throw new IllegalArgumentException("Unknown package: " + packageName);
13421            }
13422            if (ks instanceof KeySetHandle) {
13423                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13424                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13425            }
13426            return false;
13427        }
13428    }
13429
13430    @Override
13431    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13432        if (packageName == null || ks == null) {
13433            return false;
13434        }
13435        synchronized(mPackages) {
13436            final PackageParser.Package pkg = mPackages.get(packageName);
13437            if (pkg == null) {
13438                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13439                throw new IllegalArgumentException("Unknown package: " + packageName);
13440            }
13441            if (ks instanceof KeySetHandle) {
13442                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13443                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13444            }
13445            return false;
13446        }
13447    }
13448}
13449