PackageManagerService.java revision 4a88bf99851a3db3b629df23b919f2660c492f18
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 android.system.OsConstants.S_IRGRP;
52import static android.system.OsConstants.S_IROTH;
53import static android.system.OsConstants.S_IRWXU;
54import static android.system.OsConstants.S_IXGRP;
55import static android.system.OsConstants.S_IXOTH;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.util.ArrayUtils.appendInt;
59import static com.android.internal.util.ArrayUtils.removeInt;
60
61import android.util.ArrayMap;
62
63import com.android.internal.R;
64import com.android.internal.app.IMediaContainerService;
65import com.android.internal.app.ResolverActivity;
66import com.android.internal.content.NativeLibraryHelper;
67import com.android.internal.content.PackageHelper;
68import com.android.internal.os.IParcelFileDescriptorFactory;
69import com.android.internal.util.ArrayUtils;
70import com.android.internal.util.FastPrintWriter;
71import com.android.internal.util.FastXmlSerializer;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.internal.util.Preconditions;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.IActivityManager;
88import android.app.admin.IDevicePolicyManager;
89import android.app.backup.IBackupManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.ManifestDigest;
112import android.content.pm.PackageCleanItem;
113import android.content.pm.PackageInfo;
114import android.content.pm.PackageInfoLite;
115import android.content.pm.PackageInstaller;
116import android.content.pm.PackageManager;
117import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageParser;
122import android.content.pm.PackageStats;
123import android.content.pm.PackageUserState;
124import android.content.pm.ParceledListSlice;
125import android.content.pm.PermissionGroupInfo;
126import android.content.pm.PermissionInfo;
127import android.content.pm.ProviderInfo;
128import android.content.pm.ResolveInfo;
129import android.content.pm.ServiceInfo;
130import android.content.pm.Signature;
131import android.content.pm.UserInfo;
132import android.content.pm.VerificationParams;
133import android.content.pm.VerifierDeviceIdentity;
134import android.content.pm.VerifierInfo;
135import android.content.res.Resources;
136import android.hardware.display.DisplayManager;
137import android.net.Uri;
138import android.os.Binder;
139import android.os.Build;
140import android.os.Bundle;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FilenameFilter;
185import java.io.IOException;
186import java.io.InputStream;
187import java.io.PrintWriter;
188import java.nio.charset.StandardCharsets;
189import java.security.NoSuchAlgorithmException;
190import java.security.PublicKey;
191import java.security.cert.CertificateEncodingException;
192import java.security.cert.CertificateException;
193import java.text.SimpleDateFormat;
194import java.util.ArrayList;
195import java.util.Arrays;
196import java.util.Collection;
197import java.util.Collections;
198import java.util.Comparator;
199import java.util.Date;
200import java.util.HashMap;
201import java.util.HashSet;
202import java.util.Iterator;
203import java.util.List;
204import java.util.Map;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
252    // Suffix used during package installation when copying/moving
253    // package apks to install directory.
254    private static final String INSTALL_PACKAGE_SUFFIX = "-";
255
256    // Special value for {@code PackageParser.Package#cpuAbiOverride} to indicate
257    // that the cpuAbiOverride must be clear.
258    private static final String CLEAR_ABI_OVERRIDE = "-";
259
260    static final int SCAN_MONITOR = 1<<0;
261    static final int SCAN_NO_DEX = 1<<1;
262    static final int SCAN_FORCE_DEX = 1<<2;
263    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
264    static final int SCAN_NEW_INSTALL = 1<<4;
265    static final int SCAN_NO_PATHS = 1<<5;
266    static final int SCAN_UPDATE_TIME = 1<<6;
267    static final int SCAN_DEFER_DEX = 1<<7;
268    static final int SCAN_BOOTING = 1<<8;
269    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
270    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
271
272    static final int REMOVE_CHATTY = 1<<16;
273
274    /**
275     * Timeout (in milliseconds) after which the watchdog should declare that
276     * our handler thread is wedged.  The usual default for such things is one
277     * minute but we sometimes do very lengthy I/O operations on this thread,
278     * such as installing multi-gigabyte applications, so ours needs to be longer.
279     */
280    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
281
282    /**
283     * Whether verification is enabled by default.
284     */
285    private static final boolean DEFAULT_VERIFY_ENABLE = true;
286
287    /**
288     * The default maximum time to wait for the verification agent to return in
289     * milliseconds.
290     */
291    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
292
293    /**
294     * The default response for package verification timeout.
295     *
296     * This can be either PackageManager.VERIFICATION_ALLOW or
297     * PackageManager.VERIFICATION_REJECT.
298     */
299    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
300
301    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
302
303    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
304            DEFAULT_CONTAINER_PACKAGE,
305            "com.android.defcontainer.DefaultContainerService");
306
307    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
308
309    private static final String LIB_DIR_NAME = "lib";
310    private static final String LIB64_DIR_NAME = "lib64";
311
312    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
313
314    static final String mTempContainerPrefix = "smdl2tmp";
315
316    private static String sPreferredInstructionSet;
317
318    final ServiceThread mHandlerThread;
319
320    private static final String IDMAP_PREFIX = "/data/resource-cache/";
321    private static final String IDMAP_SUFFIX = "@idmap";
322
323    final PackageHandler mHandler;
324
325    final int mSdkVersion = Build.VERSION.SDK_INT;
326
327    final Context mContext;
328    final boolean mFactoryTest;
329    final boolean mOnlyCore;
330    final DisplayMetrics mMetrics;
331    final int mDefParseFlags;
332    final String[] mSeparateProcesses;
333
334    // This is where all application persistent data goes.
335    final File mAppDataDir;
336
337    // This is where all application persistent data goes for secondary users.
338    final File mUserAppDataDir;
339
340    /** The location for ASEC container files on internal storage. */
341    final String mAsecInternalPath;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    /** Directory where installed third-party apps stored */
348    final File mAppInstallDir;
349
350    /**
351     * Directory to which applications installed internally have their
352     * 32 bit native libraries copied.
353     */
354    private File mAppLib32InstallDir;
355
356    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
357    // apps.
358    final File mDrmAppPrivateInstallDir;
359
360    // ----------------------------------------------------------------
361
362    // Lock for state used when installing and doing other long running
363    // operations.  Methods that must be called with this lock held have
364    // the suffix "LI".
365    final Object mInstallLock = new Object();
366
367    // These are the directories in the 3rd party applications installed dir
368    // that we have currently loaded packages from.  Keys are the application's
369    // installed zip file (absolute codePath), and values are Package.
370    final HashMap<String, PackageParser.Package> mAppDirs =
371            new HashMap<String, PackageParser.Package>();
372
373    // ----------------------------------------------------------------
374
375    // Keys are String (package name), values are Package.  This also serves
376    // as the lock for the global state.  Methods that must be called with
377    // this lock held have the prefix "LP".
378    final HashMap<String, PackageParser.Package> mPackages =
379            new HashMap<String, PackageParser.Package>();
380
381    // Tracks available target package names -> overlay package paths.
382    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
383        new HashMap<String, HashMap<String, PackageParser.Package>>();
384
385    final Settings mSettings;
386    boolean mRestoredSettings;
387
388    // System configuration read by SystemConfig.
389    final int[] mGlobalGids;
390    final SparseArray<HashSet<String>> mSystemPermissions;
391    final HashMap<String, FeatureInfo> mAvailableFeatures;
392
393    // If mac_permissions.xml was found for seinfo labeling.
394    boolean mFoundPolicyFile;
395
396    // If a recursive restorecon of /data/data/<pkg> is needed.
397    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
398
399    public static final class SharedLibraryEntry {
400        public final String path;
401        public final String apk;
402
403        SharedLibraryEntry(String _path, String _apk) {
404            path = _path;
405            apk = _apk;
406        }
407    }
408
409    // Currently known shared libraries.
410    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
411            new HashMap<String, SharedLibraryEntry>();
412
413    // All available activities, for your resolving pleasure.
414    final ActivityIntentResolver mActivities =
415            new ActivityIntentResolver();
416
417    // All available receivers, for your resolving pleasure.
418    final ActivityIntentResolver mReceivers =
419            new ActivityIntentResolver();
420
421    // All available services, for your resolving pleasure.
422    final ServiceIntentResolver mServices = new ServiceIntentResolver();
423
424    // All available providers, for your resolving pleasure.
425    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
426
427    // Mapping from provider base names (first directory in content URI codePath)
428    // to the provider information.
429    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
430            new HashMap<String, PackageParser.Provider>();
431
432    // Mapping from instrumentation class names to info about them.
433    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
434            new HashMap<ComponentName, PackageParser.Instrumentation>();
435
436    // Mapping from permission names to info about them.
437    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
438            new HashMap<String, PackageParser.PermissionGroup>();
439
440    // Packages whose data we have transfered into another package, thus
441    // should no longer exist.
442    final HashSet<String> mTransferedPackages = new HashSet<String>();
443
444    // Broadcast actions that are only available to the system.
445    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
446
447    /** List of packages waiting for verification. */
448    final SparseArray<PackageVerificationState> mPendingVerification
449            = new SparseArray<PackageVerificationState>();
450
451    /** Set of packages associated with each app op permission. */
452    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
453
454    final PackageInstallerService mInstallerService;
455
456    HashSet<PackageParser.Package> mDeferredDexOpt = null;
457
458    // Cache of users who need badging.
459    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
460
461    /** Token for keys in mPendingVerification. */
462    private int mPendingVerificationToken = 0;
463
464    boolean mSystemReady;
465    boolean mSafeMode;
466    boolean mHasSystemUidErrors;
467
468    ApplicationInfo mAndroidApplication;
469    final ActivityInfo mResolveActivity = new ActivityInfo();
470    final ResolveInfo mResolveInfo = new ResolveInfo();
471    ComponentName mResolveComponentName;
472    PackageParser.Package mPlatformPackage;
473    ComponentName mCustomResolverComponentName;
474
475    boolean mResolverReplaced = false;
476
477    // Set of pending broadcasts for aggregating enable/disable of components.
478    static class PendingPackageBroadcasts {
479        // for each user id, a map of <package name -> components within that package>
480        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
481
482        public PendingPackageBroadcasts() {
483            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
484        }
485
486        public ArrayList<String> get(int userId, String packageName) {
487            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
488            return packages.get(packageName);
489        }
490
491        public void put(int userId, String packageName, ArrayList<String> components) {
492            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
493            packages.put(packageName, components);
494        }
495
496        public void remove(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
498            if (packages != null) {
499                packages.remove(packageName);
500            }
501        }
502
503        public void remove(int userId) {
504            mUidMap.remove(userId);
505        }
506
507        public int userIdCount() {
508            return mUidMap.size();
509        }
510
511        public int userIdAt(int n) {
512            return mUidMap.keyAt(n);
513        }
514
515        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
516            return mUidMap.get(userId);
517        }
518
519        public int size() {
520            // total number of pending broadcast entries across all userIds
521            int num = 0;
522            for (int i = 0; i< mUidMap.size(); i++) {
523                num += mUidMap.valueAt(i).size();
524            }
525            return num;
526        }
527
528        public void clear() {
529            mUidMap.clear();
530        }
531
532        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
533            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
534            if (map == null) {
535                map = new HashMap<String, ArrayList<String>>();
536                mUidMap.put(userId, map);
537            }
538            return map;
539        }
540    }
541    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
542
543    // Service Connection to remote media container service to copy
544    // package uri's from external media onto secure containers
545    // or internal storage.
546    private IMediaContainerService mContainerService = null;
547
548    static final int SEND_PENDING_BROADCAST = 1;
549    static final int MCS_BOUND = 3;
550    static final int END_COPY = 4;
551    static final int INIT_COPY = 5;
552    static final int MCS_UNBIND = 6;
553    static final int START_CLEANING_PACKAGE = 7;
554    static final int FIND_INSTALL_LOC = 8;
555    static final int POST_INSTALL = 9;
556    static final int MCS_RECONNECT = 10;
557    static final int MCS_GIVE_UP = 11;
558    static final int UPDATED_MEDIA_STATUS = 12;
559    static final int WRITE_SETTINGS = 13;
560    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
561    static final int PACKAGE_VERIFIED = 15;
562    static final int CHECK_PENDING_VERIFICATION = 16;
563
564    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
565
566    // Delay time in millisecs
567    static final int BROADCAST_DELAY = 10 * 1000;
568
569    static UserManagerService sUserManager;
570
571    // Stores a list of users whose package restrictions file needs to be updated
572    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
573
574    final private DefaultContainerConnection mDefContainerConn =
575            new DefaultContainerConnection();
576    class DefaultContainerConnection implements ServiceConnection {
577        public void onServiceConnected(ComponentName name, IBinder service) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
579            IMediaContainerService imcs =
580                IMediaContainerService.Stub.asInterface(service);
581            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
582        }
583
584        public void onServiceDisconnected(ComponentName name) {
585            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
586        }
587    };
588
589    // Recordkeeping of restore-after-install operations that are currently in flight
590    // between the Package Manager and the Backup Manager
591    class PostInstallData {
592        public InstallArgs args;
593        public PackageInstalledInfo res;
594
595        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
596            args = _a;
597            res = _r;
598        }
599    };
600    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
601    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
602
603    private final String mRequiredVerifierPackage;
604
605    private final PackageUsage mPackageUsage = new PackageUsage();
606
607    private class PackageUsage {
608        private static final int WRITE_INTERVAL
609            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
610
611        private final Object mFileLock = new Object();
612        private final AtomicLong mLastWritten = new AtomicLong(0);
613        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
614
615        private boolean mIsHistoricalPackageUsageAvailable = true;
616
617        boolean isHistoricalPackageUsageAvailable() {
618            return mIsHistoricalPackageUsageAvailable;
619        }
620
621        void write(boolean force) {
622            if (force) {
623                writeInternal();
624                return;
625            }
626            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
627                && !DEBUG_DEXOPT) {
628                return;
629            }
630            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
631                new Thread("PackageUsage_DiskWriter") {
632                    @Override
633                    public void run() {
634                        try {
635                            writeInternal();
636                        } finally {
637                            mBackgroundWriteRunning.set(false);
638                        }
639                    }
640                }.start();
641            }
642        }
643
644        private void writeInternal() {
645            synchronized (mPackages) {
646                synchronized (mFileLock) {
647                    AtomicFile file = getFile();
648                    FileOutputStream f = null;
649                    try {
650                        f = file.startWrite();
651                        BufferedOutputStream out = new BufferedOutputStream(f);
652                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
653                        StringBuilder sb = new StringBuilder();
654                        for (PackageParser.Package pkg : mPackages.values()) {
655                            if (pkg.mLastPackageUsageTimeInMills == 0) {
656                                continue;
657                            }
658                            sb.setLength(0);
659                            sb.append(pkg.packageName);
660                            sb.append(' ');
661                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
662                            sb.append('\n');
663                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
664                        }
665                        out.flush();
666                        file.finishWrite(f);
667                    } catch (IOException e) {
668                        if (f != null) {
669                            file.failWrite(f);
670                        }
671                        Log.e(TAG, "Failed to write package usage times", e);
672                    }
673                }
674            }
675            mLastWritten.set(SystemClock.elapsedRealtime());
676        }
677
678        void readLP() {
679            synchronized (mFileLock) {
680                AtomicFile file = getFile();
681                BufferedInputStream in = null;
682                try {
683                    in = new BufferedInputStream(file.openRead());
684                    StringBuffer sb = new StringBuffer();
685                    while (true) {
686                        String packageName = readToken(in, sb, ' ');
687                        if (packageName == null) {
688                            break;
689                        }
690                        String timeInMillisString = readToken(in, sb, '\n');
691                        if (timeInMillisString == null) {
692                            throw new IOException("Failed to find last usage time for package "
693                                                  + packageName);
694                        }
695                        PackageParser.Package pkg = mPackages.get(packageName);
696                        if (pkg == null) {
697                            continue;
698                        }
699                        long timeInMillis;
700                        try {
701                            timeInMillis = Long.parseLong(timeInMillisString.toString());
702                        } catch (NumberFormatException e) {
703                            throw new IOException("Failed to parse " + timeInMillisString
704                                                  + " as a long.", e);
705                        }
706                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
707                    }
708                } catch (FileNotFoundException expected) {
709                    mIsHistoricalPackageUsageAvailable = false;
710                } catch (IOException e) {
711                    Log.w(TAG, "Failed to read package usage times", e);
712                } finally {
713                    IoUtils.closeQuietly(in);
714                }
715            }
716            mLastWritten.set(SystemClock.elapsedRealtime());
717        }
718
719        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
720                throws IOException {
721            sb.setLength(0);
722            while (true) {
723                int ch = in.read();
724                if (ch == -1) {
725                    if (sb.length() == 0) {
726                        return null;
727                    }
728                    throw new IOException("Unexpected EOF");
729                }
730                if (ch == endOfToken) {
731                    return sb.toString();
732                }
733                sb.append((char)ch);
734            }
735        }
736
737        private AtomicFile getFile() {
738            File dataDir = Environment.getDataDirectory();
739            File systemDir = new File(dataDir, "system");
740            File fname = new File(systemDir, "package-usage.list");
741            return new AtomicFile(fname);
742        }
743    }
744
745    class PackageHandler extends Handler {
746        private boolean mBound = false;
747        final ArrayList<HandlerParams> mPendingInstalls =
748            new ArrayList<HandlerParams>();
749
750        private boolean connectToService() {
751            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
752                    " DefaultContainerService");
753            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
754            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
755            if (mContext.bindServiceAsUser(service, mDefContainerConn,
756                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
757                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758                mBound = true;
759                return true;
760            }
761            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
762            return false;
763        }
764
765        private void disconnectService() {
766            mContainerService = null;
767            mBound = false;
768            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
769            mContext.unbindService(mDefContainerConn);
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771        }
772
773        PackageHandler(Looper looper) {
774            super(looper);
775        }
776
777        public void handleMessage(Message msg) {
778            try {
779                doHandleMessage(msg);
780            } finally {
781                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782            }
783        }
784
785        void doHandleMessage(Message msg) {
786            switch (msg.what) {
787                case INIT_COPY: {
788                    HandlerParams params = (HandlerParams) msg.obj;
789                    int idx = mPendingInstalls.size();
790                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
791                    // If a bind was already initiated we dont really
792                    // need to do anything. The pending install
793                    // will be processed later on.
794                    if (!mBound) {
795                        // If this is the only one pending we might
796                        // have to bind to the service again.
797                        if (!connectToService()) {
798                            Slog.e(TAG, "Failed to bind to media container service");
799                            params.serviceError();
800                            return;
801                        } else {
802                            // Once we bind to the service, the first
803                            // pending request will be processed.
804                            mPendingInstalls.add(idx, params);
805                        }
806                    } else {
807                        mPendingInstalls.add(idx, params);
808                        // Already bound to the service. Just make
809                        // sure we trigger off processing the first request.
810                        if (idx == 0) {
811                            mHandler.sendEmptyMessage(MCS_BOUND);
812                        }
813                    }
814                    break;
815                }
816                case MCS_BOUND: {
817                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
818                    if (msg.obj != null) {
819                        mContainerService = (IMediaContainerService) msg.obj;
820                    }
821                    if (mContainerService == null) {
822                        // Something seriously wrong. Bail out
823                        Slog.e(TAG, "Cannot bind to media container service");
824                        for (HandlerParams params : mPendingInstalls) {
825                            // Indicate service bind error
826                            params.serviceError();
827                        }
828                        mPendingInstalls.clear();
829                    } else if (mPendingInstalls.size() > 0) {
830                        HandlerParams params = mPendingInstalls.get(0);
831                        if (params != null) {
832                            if (params.startCopy()) {
833                                // We are done...  look for more work or to
834                                // go idle.
835                                if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                        "Checking for more work or unbind...");
837                                // Delete pending install
838                                if (mPendingInstalls.size() > 0) {
839                                    mPendingInstalls.remove(0);
840                                }
841                                if (mPendingInstalls.size() == 0) {
842                                    if (mBound) {
843                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
844                                                "Posting delayed MCS_UNBIND");
845                                        removeMessages(MCS_UNBIND);
846                                        Message ubmsg = obtainMessage(MCS_UNBIND);
847                                        // Unbind after a little delay, to avoid
848                                        // continual thrashing.
849                                        sendMessageDelayed(ubmsg, 10000);
850                                    }
851                                } else {
852                                    // There are more pending requests in queue.
853                                    // Just post MCS_BOUND message to trigger processing
854                                    // of next pending install.
855                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
856                                            "Posting MCS_BOUND for next work");
857                                    mHandler.sendEmptyMessage(MCS_BOUND);
858                                }
859                            }
860                        }
861                    } else {
862                        // Should never happen ideally.
863                        Slog.w(TAG, "Empty queue");
864                    }
865                    break;
866                }
867                case MCS_RECONNECT: {
868                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
869                    if (mPendingInstalls.size() > 0) {
870                        if (mBound) {
871                            disconnectService();
872                        }
873                        if (!connectToService()) {
874                            Slog.e(TAG, "Failed to bind to media container service");
875                            for (HandlerParams params : mPendingInstalls) {
876                                // Indicate service bind error
877                                params.serviceError();
878                            }
879                            mPendingInstalls.clear();
880                        }
881                    }
882                    break;
883                }
884                case MCS_UNBIND: {
885                    // If there is no actual work left, then time to unbind.
886                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
887
888                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
889                        if (mBound) {
890                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
891
892                            disconnectService();
893                        }
894                    } else if (mPendingInstalls.size() > 0) {
895                        // There are more pending requests in queue.
896                        // Just post MCS_BOUND message to trigger processing
897                        // of next pending install.
898                        mHandler.sendEmptyMessage(MCS_BOUND);
899                    }
900
901                    break;
902                }
903                case MCS_GIVE_UP: {
904                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
905                    mPendingInstalls.remove(0);
906                    break;
907                }
908                case SEND_PENDING_BROADCAST: {
909                    String packages[];
910                    ArrayList<String> components[];
911                    int size = 0;
912                    int uids[];
913                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
914                    synchronized (mPackages) {
915                        if (mPendingBroadcasts == null) {
916                            return;
917                        }
918                        size = mPendingBroadcasts.size();
919                        if (size <= 0) {
920                            // Nothing to be done. Just return
921                            return;
922                        }
923                        packages = new String[size];
924                        components = new ArrayList[size];
925                        uids = new int[size];
926                        int i = 0;  // filling out the above arrays
927
928                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
929                            int packageUserId = mPendingBroadcasts.userIdAt(n);
930                            Iterator<Map.Entry<String, ArrayList<String>>> it
931                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
932                                            .entrySet().iterator();
933                            while (it.hasNext() && i < size) {
934                                Map.Entry<String, ArrayList<String>> ent = it.next();
935                                packages[i] = ent.getKey();
936                                components[i] = ent.getValue();
937                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
938                                uids[i] = (ps != null)
939                                        ? UserHandle.getUid(packageUserId, ps.appId)
940                                        : -1;
941                                i++;
942                            }
943                        }
944                        size = i;
945                        mPendingBroadcasts.clear();
946                    }
947                    // Send broadcasts
948                    for (int i = 0; i < size; i++) {
949                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
950                    }
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
952                    break;
953                }
954                case START_CLEANING_PACKAGE: {
955                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
956                    final String packageName = (String)msg.obj;
957                    final int userId = msg.arg1;
958                    final boolean andCode = msg.arg2 != 0;
959                    synchronized (mPackages) {
960                        if (userId == UserHandle.USER_ALL) {
961                            int[] users = sUserManager.getUserIds();
962                            for (int user : users) {
963                                mSettings.addPackageToCleanLPw(
964                                        new PackageCleanItem(user, packageName, andCode));
965                            }
966                        } else {
967                            mSettings.addPackageToCleanLPw(
968                                    new PackageCleanItem(userId, packageName, andCode));
969                        }
970                    }
971                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
972                    startCleaningPackages();
973                } break;
974                case POST_INSTALL: {
975                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
976                    PostInstallData data = mRunningInstalls.get(msg.arg1);
977                    mRunningInstalls.delete(msg.arg1);
978                    boolean deleteOld = false;
979
980                    if (data != null) {
981                        InstallArgs args = data.args;
982                        PackageInstalledInfo res = data.res;
983
984                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
985                            res.removedInfo.sendBroadcast(false, true, false);
986                            Bundle extras = new Bundle(1);
987                            extras.putInt(Intent.EXTRA_UID, res.uid);
988                            // Determine the set of users who are adding this
989                            // package for the first time vs. those who are seeing
990                            // an update.
991                            int[] firstUsers;
992                            int[] updateUsers = new int[0];
993                            if (res.origUsers == null || res.origUsers.length == 0) {
994                                firstUsers = res.newUsers;
995                            } else {
996                                firstUsers = new int[0];
997                                for (int i=0; i<res.newUsers.length; i++) {
998                                    int user = res.newUsers[i];
999                                    boolean isNew = true;
1000                                    for (int j=0; j<res.origUsers.length; j++) {
1001                                        if (res.origUsers[j] == user) {
1002                                            isNew = false;
1003                                            break;
1004                                        }
1005                                    }
1006                                    if (isNew) {
1007                                        int[] newFirst = new int[firstUsers.length+1];
1008                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1009                                                firstUsers.length);
1010                                        newFirst[firstUsers.length] = user;
1011                                        firstUsers = newFirst;
1012                                    } else {
1013                                        int[] newUpdate = new int[updateUsers.length+1];
1014                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1015                                                updateUsers.length);
1016                                        newUpdate[updateUsers.length] = user;
1017                                        updateUsers = newUpdate;
1018                                    }
1019                                }
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, firstUsers);
1024                            final boolean update = res.removedInfo.removedPackage != null;
1025                            if (update) {
1026                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1027                            }
1028                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1029                                    res.pkg.applicationInfo.packageName,
1030                                    extras, null, null, updateUsers);
1031                            if (update) {
1032                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1033                                        res.pkg.applicationInfo.packageName,
1034                                        extras, null, null, updateUsers);
1035                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1036                                        null, null,
1037                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1038
1039                                // treat asec-hosted packages like removable media on upgrade
1040                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1041                                    if (DEBUG_INSTALL) {
1042                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1043                                                + " is ASEC-hosted -> AVAILABLE");
1044                                    }
1045                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1046                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1047                                    pkgList.add(res.pkg.applicationInfo.packageName);
1048                                    sendResourcesChangedBroadcast(true, true,
1049                                            pkgList,uidArray, null);
1050                                }
1051                            }
1052                            if (res.removedInfo.args != null) {
1053                                // Remove the replaced package's older resources safely now
1054                                deleteOld = true;
1055                            }
1056
1057                            // Log current value of "unknown sources" setting
1058                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1059                                getUnknownSourcesSettings());
1060                        }
1061                        // Force a gc to clear up things
1062                        Runtime.getRuntime().gc();
1063                        // We delete after a gc for applications  on sdcard.
1064                        if (deleteOld) {
1065                            synchronized (mInstallLock) {
1066                                res.removedInfo.args.doPostDeleteLI(true);
1067                            }
1068                        }
1069                        if (args.observer != null) {
1070                            try {
1071                                Bundle extras = extrasForInstallResult(res);
1072                                args.observer.onPackageInstalled(res.name, res.returnCode,
1073                                        res.returnMsg, extras);
1074                            } catch (RemoteException e) {
1075                                Slog.i(TAG, "Observer no longer exists.");
1076                            }
1077                        }
1078                    } else {
1079                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1080                    }
1081                } break;
1082                case UPDATED_MEDIA_STATUS: {
1083                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1084                    boolean reportStatus = msg.arg1 == 1;
1085                    boolean doGc = msg.arg2 == 1;
1086                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1087                    if (doGc) {
1088                        // Force a gc to clear up stale containers.
1089                        Runtime.getRuntime().gc();
1090                    }
1091                    if (msg.obj != null) {
1092                        @SuppressWarnings("unchecked")
1093                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1094                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1095                        // Unload containers
1096                        unloadAllContainers(args);
1097                    }
1098                    if (reportStatus) {
1099                        try {
1100                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1101                            PackageHelper.getMountService().finishMediaUpdate();
1102                        } catch (RemoteException e) {
1103                            Log.e(TAG, "MountService not running?");
1104                        }
1105                    }
1106                } break;
1107                case WRITE_SETTINGS: {
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109                    synchronized (mPackages) {
1110                        removeMessages(WRITE_SETTINGS);
1111                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1112                        mSettings.writeLPr();
1113                        mDirtyUsers.clear();
1114                    }
1115                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116                } break;
1117                case WRITE_PACKAGE_RESTRICTIONS: {
1118                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1119                    synchronized (mPackages) {
1120                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1121                        for (int userId : mDirtyUsers) {
1122                            mSettings.writePackageRestrictionsLPr(userId);
1123                        }
1124                        mDirtyUsers.clear();
1125                    }
1126                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127                } break;
1128                case CHECK_PENDING_VERIFICATION: {
1129                    final int verificationId = msg.arg1;
1130                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1131
1132                    if ((state != null) && !state.timeoutExtended()) {
1133                        final InstallArgs args = state.getInstallArgs();
1134                        final Uri originUri = Uri.fromFile(args.originFile);
1135
1136                        Slog.i(TAG, "Verification timed out for " + originUri);
1137                        mPendingVerification.remove(verificationId);
1138
1139                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1140
1141                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1142                            Slog.i(TAG, "Continuing with installation of " + originUri);
1143                            state.setVerifierResponse(Binder.getCallingUid(),
1144                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1145                            broadcastPackageVerified(verificationId, originUri,
1146                                    PackageManager.VERIFICATION_ALLOW,
1147                                    state.getInstallArgs().getUser());
1148                            try {
1149                                ret = args.copyApk(mContainerService, true);
1150                            } catch (RemoteException e) {
1151                                Slog.e(TAG, "Could not contact the ContainerService");
1152                            }
1153                        } else {
1154                            broadcastPackageVerified(verificationId, originUri,
1155                                    PackageManager.VERIFICATION_REJECT,
1156                                    state.getInstallArgs().getUser());
1157                        }
1158
1159                        processPendingInstall(args, ret);
1160                        mHandler.sendEmptyMessage(MCS_UNBIND);
1161                    }
1162                    break;
1163                }
1164                case PACKAGE_VERIFIED: {
1165                    final int verificationId = msg.arg1;
1166
1167                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1168                    if (state == null) {
1169                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1170                        break;
1171                    }
1172
1173                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1174
1175                    state.setVerifierResponse(response.callerUid, response.code);
1176
1177                    if (state.isVerificationComplete()) {
1178                        mPendingVerification.remove(verificationId);
1179
1180                        final InstallArgs args = state.getInstallArgs();
1181                        final Uri originUri = Uri.fromFile(args.originFile);
1182
1183                        int ret;
1184                        if (state.isInstallAllowed()) {
1185                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1186                            broadcastPackageVerified(verificationId, originUri,
1187                                    response.code, state.getInstallArgs().getUser());
1188                            try {
1189                                ret = args.copyApk(mContainerService, true);
1190                            } catch (RemoteException e) {
1191                                Slog.e(TAG, "Could not contact the ContainerService");
1192                            }
1193                        } else {
1194                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1195                        }
1196
1197                        processPendingInstall(args, ret);
1198
1199                        mHandler.sendEmptyMessage(MCS_UNBIND);
1200                    }
1201
1202                    break;
1203                }
1204            }
1205        }
1206    }
1207
1208    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1209        Bundle extras = null;
1210        switch (res.returnCode) {
1211            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1212                extras = new Bundle();
1213                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1214                        res.origPermission);
1215                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1216                        res.origPackage);
1217                break;
1218            }
1219        }
1220        return extras;
1221    }
1222
1223    void scheduleWriteSettingsLocked() {
1224        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1225            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1226        }
1227    }
1228
1229    void scheduleWritePackageRestrictionsLocked(int userId) {
1230        if (!sUserManager.exists(userId)) return;
1231        mDirtyUsers.add(userId);
1232        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1233            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1234        }
1235    }
1236
1237    public static final PackageManagerService main(Context context, Installer installer,
1238            boolean factoryTest, boolean onlyCore) {
1239        PackageManagerService m = new PackageManagerService(context, installer,
1240                factoryTest, onlyCore);
1241        ServiceManager.addService("package", m);
1242        return m;
1243    }
1244
1245    static String[] splitString(String str, char sep) {
1246        int count = 1;
1247        int i = 0;
1248        while ((i=str.indexOf(sep, i)) >= 0) {
1249            count++;
1250            i++;
1251        }
1252
1253        String[] res = new String[count];
1254        i=0;
1255        count = 0;
1256        int lastI=0;
1257        while ((i=str.indexOf(sep, i)) >= 0) {
1258            res[count] = str.substring(lastI, i);
1259            count++;
1260            i++;
1261            lastI = i;
1262        }
1263        res[count] = str.substring(lastI, str.length());
1264        return res;
1265    }
1266
1267    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1268        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1269                Context.DISPLAY_SERVICE);
1270        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1271    }
1272
1273    public PackageManagerService(Context context, Installer installer,
1274            boolean factoryTest, boolean onlyCore) {
1275        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1276                SystemClock.uptimeMillis());
1277
1278        if (mSdkVersion <= 0) {
1279            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1280        }
1281
1282        mContext = context;
1283        mFactoryTest = factoryTest;
1284        mOnlyCore = onlyCore;
1285        mMetrics = new DisplayMetrics();
1286        mSettings = new Settings(context);
1287        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299
1300        String separateProcesses = SystemProperties.get("debug.separate_processes");
1301        if (separateProcesses != null && separateProcesses.length() > 0) {
1302            if ("*".equals(separateProcesses)) {
1303                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1304                mSeparateProcesses = null;
1305                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1306            } else {
1307                mDefParseFlags = 0;
1308                mSeparateProcesses = separateProcesses.split(",");
1309                Slog.w(TAG, "Running with debug.separate_processes: "
1310                        + separateProcesses);
1311            }
1312        } else {
1313            mDefParseFlags = 0;
1314            mSeparateProcesses = null;
1315        }
1316
1317        mInstaller = installer;
1318
1319        getDefaultDisplayMetrics(context, mMetrics);
1320
1321        SystemConfig systemConfig = SystemConfig.getInstance();
1322        mGlobalGids = systemConfig.getGlobalGids();
1323        mSystemPermissions = systemConfig.getSystemPermissions();
1324        mAvailableFeatures = systemConfig.getAvailableFeatures();
1325
1326        synchronized (mInstallLock) {
1327        // writer
1328        synchronized (mPackages) {
1329            mHandlerThread = new ServiceThread(TAG,
1330                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1331            mHandlerThread.start();
1332            mHandler = new PackageHandler(mHandlerThread.getLooper());
1333            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1334
1335            File dataDir = Environment.getDataDirectory();
1336            mAppDataDir = new File(dataDir, "data");
1337            mAppInstallDir = new File(dataDir, "app");
1338            mAppLib32InstallDir = new File(dataDir, "app-lib");
1339            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1340            mUserAppDataDir = new File(dataDir, "user");
1341            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1342
1343            sUserManager = new UserManagerService(context, this,
1344                    mInstallLock, mPackages);
1345
1346            // Propagate permission configuration in to package manager.
1347            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1348                    = systemConfig.getPermissions();
1349            for (int i=0; i<permConfig.size(); i++) {
1350                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1351                BasePermission bp = mSettings.mPermissions.get(perm.name);
1352                if (bp == null) {
1353                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1354                    mSettings.mPermissions.put(perm.name, bp);
1355                }
1356                if (perm.gids != null) {
1357                    bp.gids = appendInts(bp.gids, perm.gids);
1358                }
1359            }
1360
1361            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1362            for (int i=0; i<libConfig.size(); i++) {
1363                mSharedLibraries.put(libConfig.keyAt(i),
1364                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1365            }
1366
1367            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1368
1369            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1370                    mSdkVersion, mOnlyCore);
1371
1372            String customResolverActivity = Resources.getSystem().getString(
1373                    R.string.config_customResolverActivity);
1374            if (TextUtils.isEmpty(customResolverActivity)) {
1375                customResolverActivity = null;
1376            } else {
1377                mCustomResolverComponentName = ComponentName.unflattenFromString(
1378                        customResolverActivity);
1379            }
1380
1381            long startTime = SystemClock.uptimeMillis();
1382
1383            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1384                    startTime);
1385
1386            // Set flag to monitor and not change apk file paths when
1387            // scanning install directories.
1388            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1389
1390            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1391
1392            /**
1393             * Add everything in the in the boot class path to the
1394             * list of process files because dexopt will have been run
1395             * if necessary during zygote startup.
1396             */
1397            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1398            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1399
1400            if (bootClassPath != null) {
1401                String[] bootClassPathElements = splitString(bootClassPath, ':');
1402                for (String element : bootClassPathElements) {
1403                    alreadyDexOpted.add(element);
1404                }
1405            } else {
1406                Slog.w(TAG, "No BOOTCLASSPATH found!");
1407            }
1408
1409            if (systemServerClassPath != null) {
1410                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1411                for (String element : systemServerClassPathElements) {
1412                    alreadyDexOpted.add(element);
1413                }
1414            } else {
1415                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1416            }
1417
1418            boolean didDexOptLibraryOrTool = false;
1419
1420            final List<String> allInstructionSets = getAllInstructionSets();
1421            final String[] dexCodeInstructionSets =
1422                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1423
1424            /**
1425             * Ensure all external libraries have had dexopt run on them.
1426             */
1427            if (mSharedLibraries.size() > 0) {
1428                // NOTE: For now, we're compiling these system "shared libraries"
1429                // (and framework jars) into all available architectures. It's possible
1430                // to compile them only when we come across an app that uses them (there's
1431                // already logic for that in scanPackageLI) but that adds some complexity.
1432                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1433                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1434                        final String lib = libEntry.path;
1435                        if (lib == null) {
1436                            continue;
1437                        }
1438
1439                        try {
1440                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1441                                                                                 dexCodeInstructionSet,
1442                                                                                 false);
1443                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1444                                alreadyDexOpted.add(lib);
1445
1446                                // The list of "shared libraries" we have at this point is
1447                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1448                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1449                                } else {
1450                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1451                                }
1452                                didDexOptLibraryOrTool = true;
1453                            }
1454                        } catch (FileNotFoundException e) {
1455                            Slog.w(TAG, "Library not found: " + lib);
1456                        } catch (IOException e) {
1457                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1458                                    + e.getMessage());
1459                        }
1460                    }
1461                }
1462            }
1463
1464            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1465
1466            // Gross hack for now: we know this file doesn't contain any
1467            // code, so don't dexopt it to avoid the resulting log spew.
1468            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1469
1470            // Gross hack for now: we know this file is only part of
1471            // the boot class path for art, so don't dexopt it to
1472            // avoid the resulting log spew.
1473            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1474
1475            /**
1476             * And there are a number of commands implemented in Java, which
1477             * we currently need to do the dexopt on so that they can be
1478             * run from a non-root shell.
1479             */
1480            String[] frameworkFiles = frameworkDir.list();
1481            if (frameworkFiles != null) {
1482                // TODO: We could compile these only for the most preferred ABI. We should
1483                // first double check that the dex files for these commands are not referenced
1484                // by other system apps.
1485                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1486                    for (int i=0; i<frameworkFiles.length; i++) {
1487                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1488                        String path = libPath.getPath();
1489                        // Skip the file if we already did it.
1490                        if (alreadyDexOpted.contains(path)) {
1491                            continue;
1492                        }
1493                        // Skip the file if it is not a type we want to dexopt.
1494                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1495                            continue;
1496                        }
1497                        try {
1498                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1499                                                                                 dexCodeInstructionSet,
1500                                                                                 false);
1501                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1502                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1503                                didDexOptLibraryOrTool = true;
1504                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1505                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1506                                didDexOptLibraryOrTool = true;
1507                            }
1508                        } catch (FileNotFoundException e) {
1509                            Slog.w(TAG, "Jar not found: " + path);
1510                        } catch (IOException e) {
1511                            Slog.w(TAG, "Exception reading jar: " + path, e);
1512                        }
1513                    }
1514                }
1515            }
1516
1517            if (didDexOptLibraryOrTool) {
1518                // If we dexopted a library or tool, then something on the system has
1519                // changed. Consider this significant, and wipe away all other
1520                // existing dexopt files to ensure we don't leave any dangling around.
1521                //
1522                // TODO: This should be revisited because it isn't as good an indicator
1523                // as it used to be. It used to include the boot classpath but at some point
1524                // DexFile.isDexOptNeeded started returning false for the boot
1525                // class path files in all cases. It is very possible in a
1526                // small maintenance release update that the library and tool
1527                // jars may be unchanged but APK could be removed resulting in
1528                // unused dalvik-cache files.
1529                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1530                    mInstaller.pruneDexCache(dexCodeInstructionSet);
1531                }
1532
1533                // Additionally, delete all dex files from the root directory
1534                // since there shouldn't be any there anyway, unless we're upgrading
1535                // from an older OS version or a build that contained the "old" style
1536                // flat scheme.
1537                mInstaller.pruneDexCache(".");
1538            }
1539
1540            // Collect vendor overlay packages.
1541            // (Do this before scanning any apps.)
1542            // For security and version matching reason, only consider
1543            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1544            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1545            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1547
1548            // Find base frameworks (resource packages without code).
1549            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1550                    | PackageParser.PARSE_IS_SYSTEM_DIR
1551                    | PackageParser.PARSE_IS_PRIVILEGED,
1552                    scanMode | SCAN_NO_DEX, 0);
1553
1554            // Collected privileged system packages.
1555            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1556            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1557                    | PackageParser.PARSE_IS_SYSTEM_DIR
1558                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1559
1560            // Collect ordinary system packages.
1561            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1562            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1563                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1564
1565            // Collect all vendor packages.
1566            File vendorAppDir = new File("/vendor/app");
1567            try {
1568                vendorAppDir = vendorAppDir.getCanonicalFile();
1569            } catch (IOException e) {
1570                // failed to look up canonical path, continue with original one
1571            }
1572            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1574
1575            // Collect all OEM packages.
1576            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1577            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1578                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1579
1580            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1581            mInstaller.moveFiles();
1582
1583            // Prune any system packages that no longer exist.
1584            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1585            if (!mOnlyCore) {
1586                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1587                while (psit.hasNext()) {
1588                    PackageSetting ps = psit.next();
1589
1590                    /*
1591                     * If this is not a system app, it can't be a
1592                     * disable system app.
1593                     */
1594                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1595                        continue;
1596                    }
1597
1598                    /*
1599                     * If the package is scanned, it's not erased.
1600                     */
1601                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1602                    if (scannedPkg != null) {
1603                        /*
1604                         * If the system app is both scanned and in the
1605                         * disabled packages list, then it must have been
1606                         * added via OTA. Remove it from the currently
1607                         * scanned package so the previously user-installed
1608                         * application can be scanned.
1609                         */
1610                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1611                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1612                                    + "; removing system app");
1613                            removePackageLI(ps, true);
1614                        }
1615
1616                        continue;
1617                    }
1618
1619                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1620                        psit.remove();
1621                        String msg = "System package " + ps.name
1622                                + " no longer exists; wiping its data";
1623                        reportSettingsProblem(Log.WARN, msg);
1624                        removeDataDirsLI(ps.name);
1625                    } else {
1626                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1627                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1628                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1629                        }
1630                    }
1631                }
1632            }
1633
1634            //look for any incomplete package installations
1635            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1636            //clean up list
1637            for(int i = 0; i < deletePkgsList.size(); i++) {
1638                //clean up here
1639                cleanupInstallFailedPackage(deletePkgsList.get(i));
1640            }
1641            //delete tmp files
1642            deleteTempPackageFiles();
1643
1644            // Remove any shared userIDs that have no associated packages
1645            mSettings.pruneSharedUsersLPw();
1646
1647            if (!mOnlyCore) {
1648                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1649                        SystemClock.uptimeMillis());
1650                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1651
1652                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1653                        scanMode, 0);
1654
1655                /**
1656                 * Remove disable package settings for any updated system
1657                 * apps that were removed via an OTA. If they're not a
1658                 * previously-updated app, remove them completely.
1659                 * Otherwise, just revoke their system-level permissions.
1660                 */
1661                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1662                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1663                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1664
1665                    String msg;
1666                    if (deletedPkg == null) {
1667                        msg = "Updated system package " + deletedAppName
1668                                + " no longer exists; wiping its data";
1669                        removeDataDirsLI(deletedAppName);
1670                    } else {
1671                        msg = "Updated system app + " + deletedAppName
1672                                + " no longer present; removing system privileges for "
1673                                + deletedAppName;
1674
1675                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1676
1677                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1678                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1679                    }
1680                    reportSettingsProblem(Log.WARN, msg);
1681                }
1682            }
1683
1684            // Now that we know all of the shared libraries, update all clients to have
1685            // the correct library paths.
1686            updateAllSharedLibrariesLPw();
1687
1688            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1689                // NOTE: We ignore potential failures here during a system scan (like
1690                // the rest of the commands above) because there's precious little we
1691                // can do about it. A settings error is reported, though.
1692                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1693                        false /* force dexopt */, false /* defer dexopt */);
1694            }
1695
1696            // Now that we know all the packages we are keeping,
1697            // read and update their last usage times.
1698            mPackageUsage.readLP();
1699
1700            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1701                    SystemClock.uptimeMillis());
1702            Slog.i(TAG, "Time to scan packages: "
1703                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1704                    + " seconds");
1705
1706            // If the platform SDK has changed since the last time we booted,
1707            // we need to re-grant app permission to catch any new ones that
1708            // appear.  This is really a hack, and means that apps can in some
1709            // cases get permissions that the user didn't initially explicitly
1710            // allow...  it would be nice to have some better way to handle
1711            // this situation.
1712            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1713                    != mSdkVersion;
1714            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1715                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1716                    + "; regranting permissions for internal storage");
1717            mSettings.mInternalSdkPlatform = mSdkVersion;
1718
1719            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1720                    | (regrantPermissions
1721                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1722                            : 0));
1723
1724            // If this is the first boot, and it is a normal boot, then
1725            // we need to initialize the default preferred apps.
1726            if (!mRestoredSettings && !onlyCore) {
1727                mSettings.readDefaultPreferredAppsLPw(this, 0);
1728            }
1729
1730            // If this is first boot after an OTA, and a normal boot, then
1731            // we need to clear code cache directories.
1732            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1733                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1734                for (String pkgName : mSettings.mPackages.keySet()) {
1735                    deleteCodeCacheDirsLI(pkgName);
1736                }
1737                mSettings.mFingerprint = Build.FINGERPRINT;
1738            }
1739
1740            // All the changes are done during package scanning.
1741            mSettings.updateInternalDatabaseVersion();
1742
1743            // can downgrade to reader
1744            mSettings.writeLPr();
1745
1746            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1747                    SystemClock.uptimeMillis());
1748
1749
1750            mRequiredVerifierPackage = getRequiredVerifierLPr();
1751        } // synchronized (mPackages)
1752        } // synchronized (mInstallLock)
1753
1754        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1755
1756        // Now after opening every single application zip, make sure they
1757        // are all flushed.  Not really needed, but keeps things nice and
1758        // tidy.
1759        Runtime.getRuntime().gc();
1760    }
1761
1762    @Override
1763    public boolean isFirstBoot() {
1764        return !mRestoredSettings;
1765    }
1766
1767    @Override
1768    public boolean isOnlyCoreApps() {
1769        return mOnlyCore;
1770    }
1771
1772    private String getRequiredVerifierLPr() {
1773        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1774        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1775                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1776
1777        String requiredVerifier = null;
1778
1779        final int N = receivers.size();
1780        for (int i = 0; i < N; i++) {
1781            final ResolveInfo info = receivers.get(i);
1782
1783            if (info.activityInfo == null) {
1784                continue;
1785            }
1786
1787            final String packageName = info.activityInfo.packageName;
1788
1789            final PackageSetting ps = mSettings.mPackages.get(packageName);
1790            if (ps == null) {
1791                continue;
1792            }
1793
1794            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1795            if (!gp.grantedPermissions
1796                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1797                continue;
1798            }
1799
1800            if (requiredVerifier != null) {
1801                throw new RuntimeException("There can be only one required verifier");
1802            }
1803
1804            requiredVerifier = packageName;
1805        }
1806
1807        return requiredVerifier;
1808    }
1809
1810    @Override
1811    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1812            throws RemoteException {
1813        try {
1814            return super.onTransact(code, data, reply, flags);
1815        } catch (RuntimeException e) {
1816            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1817                Slog.wtf(TAG, "Package Manager Crash", e);
1818            }
1819            throw e;
1820        }
1821    }
1822
1823    void cleanupInstallFailedPackage(PackageSetting ps) {
1824        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1825        removeDataDirsLI(ps.name);
1826
1827        // TODO: try cleaning up codePath directory contents first, since it
1828        // might be a cluster
1829
1830        if (ps.codePath != null) {
1831            if (!ps.codePath.delete()) {
1832                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1833            }
1834        }
1835        if (ps.resourcePath != null) {
1836            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1837                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1838            }
1839        }
1840        mSettings.removePackageLPw(ps.name);
1841    }
1842
1843    static int[] appendInts(int[] cur, int[] add) {
1844        if (add == null) return cur;
1845        if (cur == null) return add;
1846        final int N = add.length;
1847        for (int i=0; i<N; i++) {
1848            cur = appendInt(cur, add[i]);
1849        }
1850        return cur;
1851    }
1852
1853    static int[] removeInts(int[] cur, int[] rem) {
1854        if (rem == null) return cur;
1855        if (cur == null) return cur;
1856        final int N = rem.length;
1857        for (int i=0; i<N; i++) {
1858            cur = removeInt(cur, rem[i]);
1859        }
1860        return cur;
1861    }
1862
1863    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1864        if (!sUserManager.exists(userId)) return null;
1865        final PackageSetting ps = (PackageSetting) p.mExtras;
1866        if (ps == null) {
1867            return null;
1868        }
1869        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1870        final PackageUserState state = ps.readUserState(userId);
1871        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1872                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1873                state, userId);
1874    }
1875
1876    @Override
1877    public boolean isPackageAvailable(String packageName, int userId) {
1878        if (!sUserManager.exists(userId)) return false;
1879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1880        synchronized (mPackages) {
1881            PackageParser.Package p = mPackages.get(packageName);
1882            if (p != null) {
1883                final PackageSetting ps = (PackageSetting) p.mExtras;
1884                if (ps != null) {
1885                    final PackageUserState state = ps.readUserState(userId);
1886                    if (state != null) {
1887                        return PackageParser.isAvailable(state);
1888                    }
1889                }
1890            }
1891        }
1892        return false;
1893    }
1894
1895    @Override
1896    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1897        if (!sUserManager.exists(userId)) return null;
1898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1899        // reader
1900        synchronized (mPackages) {
1901            PackageParser.Package p = mPackages.get(packageName);
1902            if (DEBUG_PACKAGE_INFO)
1903                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1904            if (p != null) {
1905                return generatePackageInfo(p, flags, userId);
1906            }
1907            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1908                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1909            }
1910        }
1911        return null;
1912    }
1913
1914    @Override
1915    public String[] currentToCanonicalPackageNames(String[] names) {
1916        String[] out = new String[names.length];
1917        // reader
1918        synchronized (mPackages) {
1919            for (int i=names.length-1; i>=0; i--) {
1920                PackageSetting ps = mSettings.mPackages.get(names[i]);
1921                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1922            }
1923        }
1924        return out;
1925    }
1926
1927    @Override
1928    public String[] canonicalToCurrentPackageNames(String[] names) {
1929        String[] out = new String[names.length];
1930        // reader
1931        synchronized (mPackages) {
1932            for (int i=names.length-1; i>=0; i--) {
1933                String cur = mSettings.mRenamedPackages.get(names[i]);
1934                out[i] = cur != null ? cur : names[i];
1935            }
1936        }
1937        return out;
1938    }
1939
1940    @Override
1941    public int getPackageUid(String packageName, int userId) {
1942        if (!sUserManager.exists(userId)) return -1;
1943        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1944        // reader
1945        synchronized (mPackages) {
1946            PackageParser.Package p = mPackages.get(packageName);
1947            if(p != null) {
1948                return UserHandle.getUid(userId, p.applicationInfo.uid);
1949            }
1950            PackageSetting ps = mSettings.mPackages.get(packageName);
1951            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1952                return -1;
1953            }
1954            p = ps.pkg;
1955            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1956        }
1957    }
1958
1959    @Override
1960    public int[] getPackageGids(String packageName) {
1961        // reader
1962        synchronized (mPackages) {
1963            PackageParser.Package p = mPackages.get(packageName);
1964            if (DEBUG_PACKAGE_INFO)
1965                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1966            if (p != null) {
1967                final PackageSetting ps = (PackageSetting)p.mExtras;
1968                return ps.getGids();
1969            }
1970        }
1971        // stupid thing to indicate an error.
1972        return new int[0];
1973    }
1974
1975    static final PermissionInfo generatePermissionInfo(
1976            BasePermission bp, int flags) {
1977        if (bp.perm != null) {
1978            return PackageParser.generatePermissionInfo(bp.perm, flags);
1979        }
1980        PermissionInfo pi = new PermissionInfo();
1981        pi.name = bp.name;
1982        pi.packageName = bp.sourcePackage;
1983        pi.nonLocalizedLabel = bp.name;
1984        pi.protectionLevel = bp.protectionLevel;
1985        return pi;
1986    }
1987
1988    @Override
1989    public PermissionInfo getPermissionInfo(String name, int flags) {
1990        // reader
1991        synchronized (mPackages) {
1992            final BasePermission p = mSettings.mPermissions.get(name);
1993            if (p != null) {
1994                return generatePermissionInfo(p, flags);
1995            }
1996            return null;
1997        }
1998    }
1999
2000    @Override
2001    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2002        // reader
2003        synchronized (mPackages) {
2004            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2005            for (BasePermission p : mSettings.mPermissions.values()) {
2006                if (group == null) {
2007                    if (p.perm == null || p.perm.info.group == null) {
2008                        out.add(generatePermissionInfo(p, flags));
2009                    }
2010                } else {
2011                    if (p.perm != null && group.equals(p.perm.info.group)) {
2012                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2013                    }
2014                }
2015            }
2016
2017            if (out.size() > 0) {
2018                return out;
2019            }
2020            return mPermissionGroups.containsKey(group) ? out : null;
2021        }
2022    }
2023
2024    @Override
2025    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2026        // reader
2027        synchronized (mPackages) {
2028            return PackageParser.generatePermissionGroupInfo(
2029                    mPermissionGroups.get(name), flags);
2030        }
2031    }
2032
2033    @Override
2034    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2035        // reader
2036        synchronized (mPackages) {
2037            final int N = mPermissionGroups.size();
2038            ArrayList<PermissionGroupInfo> out
2039                    = new ArrayList<PermissionGroupInfo>(N);
2040            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2041                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2042            }
2043            return out;
2044        }
2045    }
2046
2047    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2048            int userId) {
2049        if (!sUserManager.exists(userId)) return null;
2050        PackageSetting ps = mSettings.mPackages.get(packageName);
2051        if (ps != null) {
2052            if (ps.pkg == null) {
2053                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2054                        flags, userId);
2055                if (pInfo != null) {
2056                    return pInfo.applicationInfo;
2057                }
2058                return null;
2059            }
2060            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2061                    ps.readUserState(userId), userId);
2062        }
2063        return null;
2064    }
2065
2066    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2067            int userId) {
2068        if (!sUserManager.exists(userId)) return null;
2069        PackageSetting ps = mSettings.mPackages.get(packageName);
2070        if (ps != null) {
2071            PackageParser.Package pkg = ps.pkg;
2072            if (pkg == null) {
2073                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2074                    return null;
2075                }
2076                // Only data remains, so we aren't worried about code paths
2077                pkg = new PackageParser.Package(packageName);
2078                pkg.applicationInfo.packageName = packageName;
2079                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2080                pkg.applicationInfo.dataDir =
2081                        getDataPathForPackage(packageName, 0).getPath();
2082                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2083                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2084            }
2085            return generatePackageInfo(pkg, flags, userId);
2086        }
2087        return null;
2088    }
2089
2090    @Override
2091    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2092        if (!sUserManager.exists(userId)) return null;
2093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2094        // writer
2095        synchronized (mPackages) {
2096            PackageParser.Package p = mPackages.get(packageName);
2097            if (DEBUG_PACKAGE_INFO) Log.v(
2098                    TAG, "getApplicationInfo " + packageName
2099                    + ": " + p);
2100            if (p != null) {
2101                PackageSetting ps = mSettings.mPackages.get(packageName);
2102                if (ps == null) return null;
2103                // Note: isEnabledLP() does not apply here - always return info
2104                return PackageParser.generateApplicationInfo(
2105                        p, flags, ps.readUserState(userId), userId);
2106            }
2107            if ("android".equals(packageName)||"system".equals(packageName)) {
2108                return mAndroidApplication;
2109            }
2110            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2111                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2112            }
2113        }
2114        return null;
2115    }
2116
2117
2118    @Override
2119    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2120        mContext.enforceCallingOrSelfPermission(
2121                android.Manifest.permission.CLEAR_APP_CACHE, null);
2122        // Queue up an async operation since clearing cache may take a little while.
2123        mHandler.post(new Runnable() {
2124            public void run() {
2125                mHandler.removeCallbacks(this);
2126                int retCode = -1;
2127                synchronized (mInstallLock) {
2128                    retCode = mInstaller.freeCache(freeStorageSize);
2129                    if (retCode < 0) {
2130                        Slog.w(TAG, "Couldn't clear application caches");
2131                    }
2132                }
2133                if (observer != null) {
2134                    try {
2135                        observer.onRemoveCompleted(null, (retCode >= 0));
2136                    } catch (RemoteException e) {
2137                        Slog.w(TAG, "RemoveException when invoking call back");
2138                    }
2139                }
2140            }
2141        });
2142    }
2143
2144    @Override
2145    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2146        mContext.enforceCallingOrSelfPermission(
2147                android.Manifest.permission.CLEAR_APP_CACHE, null);
2148        // Queue up an async operation since clearing cache may take a little while.
2149        mHandler.post(new Runnable() {
2150            public void run() {
2151                mHandler.removeCallbacks(this);
2152                int retCode = -1;
2153                synchronized (mInstallLock) {
2154                    retCode = mInstaller.freeCache(freeStorageSize);
2155                    if (retCode < 0) {
2156                        Slog.w(TAG, "Couldn't clear application caches");
2157                    }
2158                }
2159                if(pi != null) {
2160                    try {
2161                        // Callback via pending intent
2162                        int code = (retCode >= 0) ? 1 : 0;
2163                        pi.sendIntent(null, code, null,
2164                                null, null);
2165                    } catch (SendIntentException e1) {
2166                        Slog.i(TAG, "Failed to send pending intent");
2167                    }
2168                }
2169            }
2170        });
2171    }
2172
2173    void freeStorage(long freeStorageSize) throws IOException {
2174        synchronized (mInstallLock) {
2175            if (mInstaller.freeCache(freeStorageSize) < 0) {
2176                throw new IOException("Failed to free enough space");
2177            }
2178        }
2179    }
2180
2181    @Override
2182    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2183        if (!sUserManager.exists(userId)) return null;
2184        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2185        synchronized (mPackages) {
2186            PackageParser.Activity a = mActivities.mActivities.get(component);
2187
2188            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2189            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2190                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2191                if (ps == null) return null;
2192                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2193                        userId);
2194            }
2195            if (mResolveComponentName.equals(component)) {
2196                return mResolveActivity;
2197            }
2198        }
2199        return null;
2200    }
2201
2202    @Override
2203    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2204            String resolvedType) {
2205        synchronized (mPackages) {
2206            PackageParser.Activity a = mActivities.mActivities.get(component);
2207            if (a == null) {
2208                return false;
2209            }
2210            for (int i=0; i<a.intents.size(); i++) {
2211                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2212                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2213                    return true;
2214                }
2215            }
2216            return false;
2217        }
2218    }
2219
2220    @Override
2221    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2222        if (!sUserManager.exists(userId)) return null;
2223        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2224        synchronized (mPackages) {
2225            PackageParser.Activity a = mReceivers.mActivities.get(component);
2226            if (DEBUG_PACKAGE_INFO) Log.v(
2227                TAG, "getReceiverInfo " + component + ": " + a);
2228            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2229                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2230                if (ps == null) return null;
2231                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2232                        userId);
2233            }
2234        }
2235        return null;
2236    }
2237
2238    @Override
2239    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2240        if (!sUserManager.exists(userId)) return null;
2241        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2242        synchronized (mPackages) {
2243            PackageParser.Service s = mServices.mServices.get(component);
2244            if (DEBUG_PACKAGE_INFO) Log.v(
2245                TAG, "getServiceInfo " + component + ": " + s);
2246            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2247                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2248                if (ps == null) return null;
2249                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2250                        userId);
2251            }
2252        }
2253        return null;
2254    }
2255
2256    @Override
2257    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2258        if (!sUserManager.exists(userId)) return null;
2259        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2260        synchronized (mPackages) {
2261            PackageParser.Provider p = mProviders.mProviders.get(component);
2262            if (DEBUG_PACKAGE_INFO) Log.v(
2263                TAG, "getProviderInfo " + component + ": " + p);
2264            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2265                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2266                if (ps == null) return null;
2267                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2268                        userId);
2269            }
2270        }
2271        return null;
2272    }
2273
2274    @Override
2275    public String[] getSystemSharedLibraryNames() {
2276        Set<String> libSet;
2277        synchronized (mPackages) {
2278            libSet = mSharedLibraries.keySet();
2279            int size = libSet.size();
2280            if (size > 0) {
2281                String[] libs = new String[size];
2282                libSet.toArray(libs);
2283                return libs;
2284            }
2285        }
2286        return null;
2287    }
2288
2289    @Override
2290    public FeatureInfo[] getSystemAvailableFeatures() {
2291        Collection<FeatureInfo> featSet;
2292        synchronized (mPackages) {
2293            featSet = mAvailableFeatures.values();
2294            int size = featSet.size();
2295            if (size > 0) {
2296                FeatureInfo[] features = new FeatureInfo[size+1];
2297                featSet.toArray(features);
2298                FeatureInfo fi = new FeatureInfo();
2299                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2300                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2301                features[size] = fi;
2302                return features;
2303            }
2304        }
2305        return null;
2306    }
2307
2308    @Override
2309    public boolean hasSystemFeature(String name) {
2310        synchronized (mPackages) {
2311            return mAvailableFeatures.containsKey(name);
2312        }
2313    }
2314
2315    private void checkValidCaller(int uid, int userId) {
2316        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2317            return;
2318
2319        throw new SecurityException("Caller uid=" + uid
2320                + " is not privileged to communicate with user=" + userId);
2321    }
2322
2323    @Override
2324    public int checkPermission(String permName, String pkgName) {
2325        synchronized (mPackages) {
2326            PackageParser.Package p = mPackages.get(pkgName);
2327            if (p != null && p.mExtras != null) {
2328                PackageSetting ps = (PackageSetting)p.mExtras;
2329                if (ps.sharedUser != null) {
2330                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2331                        return PackageManager.PERMISSION_GRANTED;
2332                    }
2333                } else if (ps.grantedPermissions.contains(permName)) {
2334                    return PackageManager.PERMISSION_GRANTED;
2335                }
2336            }
2337        }
2338        return PackageManager.PERMISSION_DENIED;
2339    }
2340
2341    @Override
2342    public int checkUidPermission(String permName, int uid) {
2343        synchronized (mPackages) {
2344            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2345            if (obj != null) {
2346                GrantedPermissions gp = (GrantedPermissions)obj;
2347                if (gp.grantedPermissions.contains(permName)) {
2348                    return PackageManager.PERMISSION_GRANTED;
2349                }
2350            } else {
2351                HashSet<String> perms = mSystemPermissions.get(uid);
2352                if (perms != null && perms.contains(permName)) {
2353                    return PackageManager.PERMISSION_GRANTED;
2354                }
2355            }
2356        }
2357        return PackageManager.PERMISSION_DENIED;
2358    }
2359
2360    /**
2361     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2362     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2363     * @param message the message to log on security exception
2364     */
2365    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2366            String message) {
2367        if (userId < 0) {
2368            throw new IllegalArgumentException("Invalid userId " + userId);
2369        }
2370        if (userId == UserHandle.getUserId(callingUid)) return;
2371        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2372            if (requireFullPermission) {
2373                mContext.enforceCallingOrSelfPermission(
2374                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2375            } else {
2376                try {
2377                    mContext.enforceCallingOrSelfPermission(
2378                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2379                } catch (SecurityException se) {
2380                    mContext.enforceCallingOrSelfPermission(
2381                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2382                }
2383            }
2384        }
2385    }
2386
2387    private BasePermission findPermissionTreeLP(String permName) {
2388        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2389            if (permName.startsWith(bp.name) &&
2390                    permName.length() > bp.name.length() &&
2391                    permName.charAt(bp.name.length()) == '.') {
2392                return bp;
2393            }
2394        }
2395        return null;
2396    }
2397
2398    private BasePermission checkPermissionTreeLP(String permName) {
2399        if (permName != null) {
2400            BasePermission bp = findPermissionTreeLP(permName);
2401            if (bp != null) {
2402                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2403                    return bp;
2404                }
2405                throw new SecurityException("Calling uid "
2406                        + Binder.getCallingUid()
2407                        + " is not allowed to add to permission tree "
2408                        + bp.name + " owned by uid " + bp.uid);
2409            }
2410        }
2411        throw new SecurityException("No permission tree found for " + permName);
2412    }
2413
2414    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2415        if (s1 == null) {
2416            return s2 == null;
2417        }
2418        if (s2 == null) {
2419            return false;
2420        }
2421        if (s1.getClass() != s2.getClass()) {
2422            return false;
2423        }
2424        return s1.equals(s2);
2425    }
2426
2427    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2428        if (pi1.icon != pi2.icon) return false;
2429        if (pi1.logo != pi2.logo) return false;
2430        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2431        if (!compareStrings(pi1.name, pi2.name)) return false;
2432        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2433        // We'll take care of setting this one.
2434        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2435        // These are not currently stored in settings.
2436        //if (!compareStrings(pi1.group, pi2.group)) return false;
2437        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2438        //if (pi1.labelRes != pi2.labelRes) return false;
2439        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2440        return true;
2441    }
2442
2443    int permissionInfoFootprint(PermissionInfo info) {
2444        int size = info.name.length();
2445        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2446        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2447        return size;
2448    }
2449
2450    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2451        int size = 0;
2452        for (BasePermission perm : mSettings.mPermissions.values()) {
2453            if (perm.uid == tree.uid) {
2454                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2455            }
2456        }
2457        return size;
2458    }
2459
2460    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2461        // We calculate the max size of permissions defined by this uid and throw
2462        // if that plus the size of 'info' would exceed our stated maximum.
2463        if (tree.uid != Process.SYSTEM_UID) {
2464            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2465            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2466                throw new SecurityException("Permission tree size cap exceeded");
2467            }
2468        }
2469    }
2470
2471    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2472        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2473            throw new SecurityException("Label must be specified in permission");
2474        }
2475        BasePermission tree = checkPermissionTreeLP(info.name);
2476        BasePermission bp = mSettings.mPermissions.get(info.name);
2477        boolean added = bp == null;
2478        boolean changed = true;
2479        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2480        if (added) {
2481            enforcePermissionCapLocked(info, tree);
2482            bp = new BasePermission(info.name, tree.sourcePackage,
2483                    BasePermission.TYPE_DYNAMIC);
2484        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2485            throw new SecurityException(
2486                    "Not allowed to modify non-dynamic permission "
2487                    + info.name);
2488        } else {
2489            if (bp.protectionLevel == fixedLevel
2490                    && bp.perm.owner.equals(tree.perm.owner)
2491                    && bp.uid == tree.uid
2492                    && comparePermissionInfos(bp.perm.info, info)) {
2493                changed = false;
2494            }
2495        }
2496        bp.protectionLevel = fixedLevel;
2497        info = new PermissionInfo(info);
2498        info.protectionLevel = fixedLevel;
2499        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2500        bp.perm.info.packageName = tree.perm.info.packageName;
2501        bp.uid = tree.uid;
2502        if (added) {
2503            mSettings.mPermissions.put(info.name, bp);
2504        }
2505        if (changed) {
2506            if (!async) {
2507                mSettings.writeLPr();
2508            } else {
2509                scheduleWriteSettingsLocked();
2510            }
2511        }
2512        return added;
2513    }
2514
2515    @Override
2516    public boolean addPermission(PermissionInfo info) {
2517        synchronized (mPackages) {
2518            return addPermissionLocked(info, false);
2519        }
2520    }
2521
2522    @Override
2523    public boolean addPermissionAsync(PermissionInfo info) {
2524        synchronized (mPackages) {
2525            return addPermissionLocked(info, true);
2526        }
2527    }
2528
2529    @Override
2530    public void removePermission(String name) {
2531        synchronized (mPackages) {
2532            checkPermissionTreeLP(name);
2533            BasePermission bp = mSettings.mPermissions.get(name);
2534            if (bp != null) {
2535                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2536                    throw new SecurityException(
2537                            "Not allowed to modify non-dynamic permission "
2538                            + name);
2539                }
2540                mSettings.mPermissions.remove(name);
2541                mSettings.writeLPr();
2542            }
2543        }
2544    }
2545
2546    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2547        int index = pkg.requestedPermissions.indexOf(bp.name);
2548        if (index == -1) {
2549            throw new SecurityException("Package " + pkg.packageName
2550                    + " has not requested permission " + bp.name);
2551        }
2552        boolean isNormal =
2553                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2554                        == PermissionInfo.PROTECTION_NORMAL);
2555        boolean isDangerous =
2556                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2557                        == PermissionInfo.PROTECTION_DANGEROUS);
2558        boolean isDevelopment =
2559                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2560
2561        if (!isNormal && !isDangerous && !isDevelopment) {
2562            throw new SecurityException("Permission " + bp.name
2563                    + " is not a changeable permission type");
2564        }
2565
2566        if (isNormal || isDangerous) {
2567            if (pkg.requestedPermissionsRequired.get(index)) {
2568                throw new SecurityException("Can't change " + bp.name
2569                        + ". It is required by the application");
2570            }
2571        }
2572    }
2573
2574    @Override
2575    public void grantPermission(String packageName, String permissionName) {
2576        mContext.enforceCallingOrSelfPermission(
2577                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2578        synchronized (mPackages) {
2579            final PackageParser.Package pkg = mPackages.get(packageName);
2580            if (pkg == null) {
2581                throw new IllegalArgumentException("Unknown package: " + packageName);
2582            }
2583            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2584            if (bp == null) {
2585                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2586            }
2587
2588            checkGrantRevokePermissions(pkg, bp);
2589
2590            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2591            if (ps == null) {
2592                return;
2593            }
2594            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2595            if (gp.grantedPermissions.add(permissionName)) {
2596                if (ps.haveGids) {
2597                    gp.gids = appendInts(gp.gids, bp.gids);
2598                }
2599                mSettings.writeLPr();
2600            }
2601        }
2602    }
2603
2604    @Override
2605    public void revokePermission(String packageName, String permissionName) {
2606        int changedAppId = -1;
2607
2608        synchronized (mPackages) {
2609            final PackageParser.Package pkg = mPackages.get(packageName);
2610            if (pkg == null) {
2611                throw new IllegalArgumentException("Unknown package: " + packageName);
2612            }
2613            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2614                mContext.enforceCallingOrSelfPermission(
2615                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2616            }
2617            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2618            if (bp == null) {
2619                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2620            }
2621
2622            checkGrantRevokePermissions(pkg, bp);
2623
2624            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2625            if (ps == null) {
2626                return;
2627            }
2628            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2629            if (gp.grantedPermissions.remove(permissionName)) {
2630                gp.grantedPermissions.remove(permissionName);
2631                if (ps.haveGids) {
2632                    gp.gids = removeInts(gp.gids, bp.gids);
2633                }
2634                mSettings.writeLPr();
2635                changedAppId = ps.appId;
2636            }
2637        }
2638
2639        if (changedAppId >= 0) {
2640            // We changed the perm on someone, kill its processes.
2641            IActivityManager am = ActivityManagerNative.getDefault();
2642            if (am != null) {
2643                final int callingUserId = UserHandle.getCallingUserId();
2644                final long ident = Binder.clearCallingIdentity();
2645                try {
2646                    //XXX we should only revoke for the calling user's app permissions,
2647                    // but for now we impact all users.
2648                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2649                    //        "revoke " + permissionName);
2650                    int[] users = sUserManager.getUserIds();
2651                    for (int user : users) {
2652                        am.killUid(UserHandle.getUid(user, changedAppId),
2653                                "revoke " + permissionName);
2654                    }
2655                } catch (RemoteException e) {
2656                } finally {
2657                    Binder.restoreCallingIdentity(ident);
2658                }
2659            }
2660        }
2661    }
2662
2663    @Override
2664    public boolean isProtectedBroadcast(String actionName) {
2665        synchronized (mPackages) {
2666            return mProtectedBroadcasts.contains(actionName);
2667        }
2668    }
2669
2670    @Override
2671    public int checkSignatures(String pkg1, String pkg2) {
2672        synchronized (mPackages) {
2673            final PackageParser.Package p1 = mPackages.get(pkg1);
2674            final PackageParser.Package p2 = mPackages.get(pkg2);
2675            if (p1 == null || p1.mExtras == null
2676                    || p2 == null || p2.mExtras == null) {
2677                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2678            }
2679            return compareSignatures(p1.mSignatures, p2.mSignatures);
2680        }
2681    }
2682
2683    @Override
2684    public int checkUidSignatures(int uid1, int uid2) {
2685        // Map to base uids.
2686        uid1 = UserHandle.getAppId(uid1);
2687        uid2 = UserHandle.getAppId(uid2);
2688        // reader
2689        synchronized (mPackages) {
2690            Signature[] s1;
2691            Signature[] s2;
2692            Object obj = mSettings.getUserIdLPr(uid1);
2693            if (obj != null) {
2694                if (obj instanceof SharedUserSetting) {
2695                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2696                } else if (obj instanceof PackageSetting) {
2697                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2698                } else {
2699                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2700                }
2701            } else {
2702                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2703            }
2704            obj = mSettings.getUserIdLPr(uid2);
2705            if (obj != null) {
2706                if (obj instanceof SharedUserSetting) {
2707                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2708                } else if (obj instanceof PackageSetting) {
2709                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2710                } else {
2711                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2712                }
2713            } else {
2714                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715            }
2716            return compareSignatures(s1, s2);
2717        }
2718    }
2719
2720    /**
2721     * Compares two sets of signatures. Returns:
2722     * <br />
2723     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2724     * <br />
2725     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2726     * <br />
2727     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2728     * <br />
2729     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2730     * <br />
2731     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2732     */
2733    static int compareSignatures(Signature[] s1, Signature[] s2) {
2734        if (s1 == null) {
2735            return s2 == null
2736                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2737                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2738        }
2739
2740        if (s2 == null) {
2741            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2742        }
2743
2744        if (s1.length != s2.length) {
2745            return PackageManager.SIGNATURE_NO_MATCH;
2746        }
2747
2748        // Since both signature sets are of size 1, we can compare without HashSets.
2749        if (s1.length == 1) {
2750            return s1[0].equals(s2[0]) ?
2751                    PackageManager.SIGNATURE_MATCH :
2752                    PackageManager.SIGNATURE_NO_MATCH;
2753        }
2754
2755        HashSet<Signature> set1 = new HashSet<Signature>();
2756        for (Signature sig : s1) {
2757            set1.add(sig);
2758        }
2759        HashSet<Signature> set2 = new HashSet<Signature>();
2760        for (Signature sig : s2) {
2761            set2.add(sig);
2762        }
2763        // Make sure s2 contains all signatures in s1.
2764        if (set1.equals(set2)) {
2765            return PackageManager.SIGNATURE_MATCH;
2766        }
2767        return PackageManager.SIGNATURE_NO_MATCH;
2768    }
2769
2770    /**
2771     * If the database version for this type of package (internal storage or
2772     * external storage) is less than the version where package signatures
2773     * were updated, return true.
2774     */
2775    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2776        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2777                DatabaseVersion.SIGNATURE_END_ENTITY))
2778                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2779                        DatabaseVersion.SIGNATURE_END_ENTITY));
2780    }
2781
2782    /**
2783     * Used for backward compatibility to make sure any packages with
2784     * certificate chains get upgraded to the new style. {@code existingSigs}
2785     * will be in the old format (since they were stored on disk from before the
2786     * system upgrade) and {@code scannedSigs} will be in the newer format.
2787     */
2788    private int compareSignaturesCompat(PackageSignatures existingSigs,
2789            PackageParser.Package scannedPkg) {
2790        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2791            return PackageManager.SIGNATURE_NO_MATCH;
2792        }
2793
2794        HashSet<Signature> existingSet = new HashSet<Signature>();
2795        for (Signature sig : existingSigs.mSignatures) {
2796            existingSet.add(sig);
2797        }
2798        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2799        for (Signature sig : scannedPkg.mSignatures) {
2800            try {
2801                Signature[] chainSignatures = sig.getChainSignatures();
2802                for (Signature chainSig : chainSignatures) {
2803                    scannedCompatSet.add(chainSig);
2804                }
2805            } catch (CertificateEncodingException e) {
2806                scannedCompatSet.add(sig);
2807            }
2808        }
2809        /*
2810         * Make sure the expanded scanned set contains all signatures in the
2811         * existing one.
2812         */
2813        if (scannedCompatSet.equals(existingSet)) {
2814            // Migrate the old signatures to the new scheme.
2815            existingSigs.assignSignatures(scannedPkg.mSignatures);
2816            // The new KeySets will be re-added later in the scanning process.
2817            synchronized (mPackages) {
2818                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2819            }
2820            return PackageManager.SIGNATURE_MATCH;
2821        }
2822        return PackageManager.SIGNATURE_NO_MATCH;
2823    }
2824
2825    @Override
2826    public String[] getPackagesForUid(int uid) {
2827        uid = UserHandle.getAppId(uid);
2828        // reader
2829        synchronized (mPackages) {
2830            Object obj = mSettings.getUserIdLPr(uid);
2831            if (obj instanceof SharedUserSetting) {
2832                final SharedUserSetting sus = (SharedUserSetting) obj;
2833                final int N = sus.packages.size();
2834                final String[] res = new String[N];
2835                final Iterator<PackageSetting> it = sus.packages.iterator();
2836                int i = 0;
2837                while (it.hasNext()) {
2838                    res[i++] = it.next().name;
2839                }
2840                return res;
2841            } else if (obj instanceof PackageSetting) {
2842                final PackageSetting ps = (PackageSetting) obj;
2843                return new String[] { ps.name };
2844            }
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public String getNameForUid(int uid) {
2851        // reader
2852        synchronized (mPackages) {
2853            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2854            if (obj instanceof SharedUserSetting) {
2855                final SharedUserSetting sus = (SharedUserSetting) obj;
2856                return sus.name + ":" + sus.userId;
2857            } else if (obj instanceof PackageSetting) {
2858                final PackageSetting ps = (PackageSetting) obj;
2859                return ps.name;
2860            }
2861        }
2862        return null;
2863    }
2864
2865    @Override
2866    public int getUidForSharedUser(String sharedUserName) {
2867        if(sharedUserName == null) {
2868            return -1;
2869        }
2870        // reader
2871        synchronized (mPackages) {
2872            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2873            if (suid == null) {
2874                return -1;
2875            }
2876            return suid.userId;
2877        }
2878    }
2879
2880    @Override
2881    public int getFlagsForUid(int uid) {
2882        synchronized (mPackages) {
2883            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2884            if (obj instanceof SharedUserSetting) {
2885                final SharedUserSetting sus = (SharedUserSetting) obj;
2886                return sus.pkgFlags;
2887            } else if (obj instanceof PackageSetting) {
2888                final PackageSetting ps = (PackageSetting) obj;
2889                return ps.pkgFlags;
2890            }
2891        }
2892        return 0;
2893    }
2894
2895    @Override
2896    public String[] getAppOpPermissionPackages(String permissionName) {
2897        synchronized (mPackages) {
2898            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2899            if (pkgs == null) {
2900                return null;
2901            }
2902            return pkgs.toArray(new String[pkgs.size()]);
2903        }
2904    }
2905
2906    @Override
2907    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2908            int flags, int userId) {
2909        if (!sUserManager.exists(userId)) return null;
2910        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2911        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2912        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2913    }
2914
2915    @Override
2916    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2917            IntentFilter filter, int match, ComponentName activity) {
2918        final int userId = UserHandle.getCallingUserId();
2919        if (DEBUG_PREFERRED) {
2920            Log.v(TAG, "setLastChosenActivity intent=" + intent
2921                + " resolvedType=" + resolvedType
2922                + " flags=" + flags
2923                + " filter=" + filter
2924                + " match=" + match
2925                + " activity=" + activity);
2926            filter.dump(new PrintStreamPrinter(System.out), "    ");
2927        }
2928        intent.setComponent(null);
2929        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2930        // Find any earlier preferred or last chosen entries and nuke them
2931        findPreferredActivity(intent, resolvedType,
2932                flags, query, 0, false, true, false, userId);
2933        // Add the new activity as the last chosen for this filter
2934        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2935                "Setting last chosen");
2936    }
2937
2938    @Override
2939    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2940        final int userId = UserHandle.getCallingUserId();
2941        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2942        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2943        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2944                false, false, false, userId);
2945    }
2946
2947    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2948            int flags, List<ResolveInfo> query, int userId) {
2949        if (query != null) {
2950            final int N = query.size();
2951            if (N == 1) {
2952                return query.get(0);
2953            } else if (N > 1) {
2954                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2955                // If there is more than one activity with the same priority,
2956                // then let the user decide between them.
2957                ResolveInfo r0 = query.get(0);
2958                ResolveInfo r1 = query.get(1);
2959                if (DEBUG_INTENT_MATCHING || debug) {
2960                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2961                            + r1.activityInfo.name + "=" + r1.priority);
2962                }
2963                // If the first activity has a higher priority, or a different
2964                // default, then it is always desireable to pick it.
2965                if (r0.priority != r1.priority
2966                        || r0.preferredOrder != r1.preferredOrder
2967                        || r0.isDefault != r1.isDefault) {
2968                    return query.get(0);
2969                }
2970                // If we have saved a preference for a preferred activity for
2971                // this Intent, use that.
2972                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2973                        flags, query, r0.priority, true, false, debug, userId);
2974                if (ri != null) {
2975                    return ri;
2976                }
2977                if (userId != 0) {
2978                    ri = new ResolveInfo(mResolveInfo);
2979                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2980                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2981                            ri.activityInfo.applicationInfo);
2982                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2983                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2984                    return ri;
2985                }
2986                return mResolveInfo;
2987            }
2988        }
2989        return null;
2990    }
2991
2992    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2993            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2994        final int N = query.size();
2995        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2996                .get(userId);
2997        // Get the list of persistent preferred activities that handle the intent
2998        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2999        List<PersistentPreferredActivity> pprefs = ppir != null
3000                ? ppir.queryIntent(intent, resolvedType,
3001                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3002                : null;
3003        if (pprefs != null && pprefs.size() > 0) {
3004            final int M = pprefs.size();
3005            for (int i=0; i<M; i++) {
3006                final PersistentPreferredActivity ppa = pprefs.get(i);
3007                if (DEBUG_PREFERRED || debug) {
3008                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3009                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3010                            + "\n  component=" + ppa.mComponent);
3011                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3012                }
3013                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3014                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3015                if (DEBUG_PREFERRED || debug) {
3016                    Slog.v(TAG, "Found persistent preferred activity:");
3017                    if (ai != null) {
3018                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3019                    } else {
3020                        Slog.v(TAG, "  null");
3021                    }
3022                }
3023                if (ai == null) {
3024                    // This previously registered persistent preferred activity
3025                    // component is no longer known. Ignore it and do NOT remove it.
3026                    continue;
3027                }
3028                for (int j=0; j<N; j++) {
3029                    final ResolveInfo ri = query.get(j);
3030                    if (!ri.activityInfo.applicationInfo.packageName
3031                            .equals(ai.applicationInfo.packageName)) {
3032                        continue;
3033                    }
3034                    if (!ri.activityInfo.name.equals(ai.name)) {
3035                        continue;
3036                    }
3037                    //  Found a persistent preference that can handle the intent.
3038                    if (DEBUG_PREFERRED || debug) {
3039                        Slog.v(TAG, "Returning persistent preferred activity: " +
3040                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3041                    }
3042                    return ri;
3043                }
3044            }
3045        }
3046        return null;
3047    }
3048
3049    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3050            List<ResolveInfo> query, int priority, boolean always,
3051            boolean removeMatches, boolean debug, int userId) {
3052        if (!sUserManager.exists(userId)) return null;
3053        // writer
3054        synchronized (mPackages) {
3055            if (intent.getSelector() != null) {
3056                intent = intent.getSelector();
3057            }
3058            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3059
3060            // Try to find a matching persistent preferred activity.
3061            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3062                    debug, userId);
3063
3064            // If a persistent preferred activity matched, use it.
3065            if (pri != null) {
3066                return pri;
3067            }
3068
3069            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3070            // Get the list of preferred activities that handle the intent
3071            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3072            List<PreferredActivity> prefs = pir != null
3073                    ? pir.queryIntent(intent, resolvedType,
3074                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3075                    : null;
3076            if (prefs != null && prefs.size() > 0) {
3077                // First figure out how good the original match set is.
3078                // We will only allow preferred activities that came
3079                // from the same match quality.
3080                int match = 0;
3081
3082                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3083
3084                final int N = query.size();
3085                for (int j=0; j<N; j++) {
3086                    final ResolveInfo ri = query.get(j);
3087                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3088                            + ": 0x" + Integer.toHexString(match));
3089                    if (ri.match > match) {
3090                        match = ri.match;
3091                    }
3092                }
3093
3094                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3095                        + Integer.toHexString(match));
3096
3097                match &= IntentFilter.MATCH_CATEGORY_MASK;
3098                final int M = prefs.size();
3099                for (int i=0; i<M; i++) {
3100                    final PreferredActivity pa = prefs.get(i);
3101                    if (DEBUG_PREFERRED || debug) {
3102                        Slog.v(TAG, "Checking PreferredActivity ds="
3103                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3104                                + "\n  component=" + pa.mPref.mComponent);
3105                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3106                    }
3107                    if (pa.mPref.mMatch != match) {
3108                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3109                                + Integer.toHexString(pa.mPref.mMatch));
3110                        continue;
3111                    }
3112                    // If it's not an "always" type preferred activity and that's what we're
3113                    // looking for, skip it.
3114                    if (always && !pa.mPref.mAlways) {
3115                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3116                        continue;
3117                    }
3118                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3119                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3120                    if (DEBUG_PREFERRED || debug) {
3121                        Slog.v(TAG, "Found preferred activity:");
3122                        if (ai != null) {
3123                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3124                        } else {
3125                            Slog.v(TAG, "  null");
3126                        }
3127                    }
3128                    if (ai == null) {
3129                        // This previously registered preferred activity
3130                        // component is no longer known.  Most likely an update
3131                        // to the app was installed and in the new version this
3132                        // component no longer exists.  Clean it up by removing
3133                        // it from the preferred activities list, and skip it.
3134                        Slog.w(TAG, "Removing dangling preferred activity: "
3135                                + pa.mPref.mComponent);
3136                        pir.removeFilter(pa);
3137                        continue;
3138                    }
3139                    for (int j=0; j<N; j++) {
3140                        final ResolveInfo ri = query.get(j);
3141                        if (!ri.activityInfo.applicationInfo.packageName
3142                                .equals(ai.applicationInfo.packageName)) {
3143                            continue;
3144                        }
3145                        if (!ri.activityInfo.name.equals(ai.name)) {
3146                            continue;
3147                        }
3148
3149                        if (removeMatches) {
3150                            pir.removeFilter(pa);
3151                            if (DEBUG_PREFERRED) {
3152                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3153                            }
3154                            break;
3155                        }
3156
3157                        // Okay we found a previously set preferred or last chosen app.
3158                        // If the result set is different from when this
3159                        // was created, we need to clear it and re-ask the
3160                        // user their preference, if we're looking for an "always" type entry.
3161                        if (always && !pa.mPref.sameSet(query, priority)) {
3162                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3163                                    + intent + " type " + resolvedType);
3164                            if (DEBUG_PREFERRED) {
3165                                Slog.v(TAG, "Removing preferred activity since set changed "
3166                                        + pa.mPref.mComponent);
3167                            }
3168                            pir.removeFilter(pa);
3169                            // Re-add the filter as a "last chosen" entry (!always)
3170                            PreferredActivity lastChosen = new PreferredActivity(
3171                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3172                            pir.addFilter(lastChosen);
3173                            mSettings.writePackageRestrictionsLPr(userId);
3174                            return null;
3175                        }
3176
3177                        // Yay! Either the set matched or we're looking for the last chosen
3178                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3179                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3180                        mSettings.writePackageRestrictionsLPr(userId);
3181                        return ri;
3182                    }
3183                }
3184            }
3185            mSettings.writePackageRestrictionsLPr(userId);
3186        }
3187        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3188        return null;
3189    }
3190
3191    /*
3192     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3193     */
3194    @Override
3195    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3196            int targetUserId) {
3197        mContext.enforceCallingOrSelfPermission(
3198                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3199        List<CrossProfileIntentFilter> matches =
3200                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3201        if (matches != null) {
3202            int size = matches.size();
3203            for (int i = 0; i < size; i++) {
3204                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3205            }
3206        }
3207        ArrayList<String> packageNames = null;
3208        SparseArray<ArrayList<String>> fromSource =
3209                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3210        if (fromSource != null) {
3211            packageNames = fromSource.get(targetUserId);
3212            if (packageNames != null) {
3213                // We need the package name, so we try to resolve with the loosest flags possible
3214                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3215                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3216                int count = resolveInfos.size();
3217                for (int i = 0; i < count; i++) {
3218                    ResolveInfo resolveInfo = resolveInfos.get(i);
3219                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3220                        return true;
3221                    }
3222                }
3223            }
3224        }
3225        return false;
3226    }
3227
3228    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3229            String resolvedType, int userId) {
3230        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3231        if (resolver != null) {
3232            return resolver.queryIntent(intent, resolvedType, false, userId);
3233        }
3234        return null;
3235    }
3236
3237    @Override
3238    public List<ResolveInfo> queryIntentActivities(Intent intent,
3239            String resolvedType, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return Collections.emptyList();
3241        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3242        ComponentName comp = intent.getComponent();
3243        if (comp == null) {
3244            if (intent.getSelector() != null) {
3245                intent = intent.getSelector();
3246                comp = intent.getComponent();
3247            }
3248        }
3249
3250        if (comp != null) {
3251            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3252            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3253            if (ai != null) {
3254                final ResolveInfo ri = new ResolveInfo();
3255                ri.activityInfo = ai;
3256                list.add(ri);
3257            }
3258            return list;
3259        }
3260
3261        // reader
3262        synchronized (mPackages) {
3263            final String pkgName = intent.getPackage();
3264            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3265            if (pkgName == null) {
3266                ResolveInfo resolveInfo = null;
3267                if (queryCrossProfile) {
3268                    // Check if the intent needs to be forwarded to another user for this package
3269                    ArrayList<ResolveInfo> crossProfileResult =
3270                            queryIntentActivitiesCrossProfilePackage(
3271                                    intent, resolvedType, flags, userId);
3272                    if (!crossProfileResult.isEmpty()) {
3273                        // Skip the current profile
3274                        return crossProfileResult;
3275                    }
3276                    List<CrossProfileIntentFilter> matchingFilters =
3277                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3278                    // Check for results that need to skip the current profile.
3279                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3280                            resolvedType, flags, userId);
3281                    if (resolveInfo != null) {
3282                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3283                        result.add(resolveInfo);
3284                        return result;
3285                    }
3286                    // Check for cross profile results.
3287                    resolveInfo = queryCrossProfileIntents(
3288                            matchingFilters, intent, resolvedType, flags, userId);
3289                }
3290                // Check for results in the current profile.
3291                List<ResolveInfo> result = mActivities.queryIntent(
3292                        intent, resolvedType, flags, userId);
3293                if (resolveInfo != null) {
3294                    result.add(resolveInfo);
3295                }
3296                return result;
3297            }
3298            final PackageParser.Package pkg = mPackages.get(pkgName);
3299            if (pkg != null) {
3300                if (queryCrossProfile) {
3301                    ArrayList<ResolveInfo> crossProfileResult =
3302                            queryIntentActivitiesCrossProfilePackage(
3303                                    intent, resolvedType, flags, userId, pkg, pkgName);
3304                    if (!crossProfileResult.isEmpty()) {
3305                        // Skip the current profile
3306                        return crossProfileResult;
3307                    }
3308                }
3309                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3310                        pkg.activities, userId);
3311            }
3312            return new ArrayList<ResolveInfo>();
3313        }
3314    }
3315
3316    private ResolveInfo querySkipCurrentProfileIntents(
3317            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3318            int flags, int sourceUserId) {
3319        if (matchingFilters != null) {
3320            int size = matchingFilters.size();
3321            for (int i = 0; i < size; i ++) {
3322                CrossProfileIntentFilter filter = matchingFilters.get(i);
3323                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3324                    // Checking if there are activities in the target user that can handle the
3325                    // intent.
3326                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3327                            flags, sourceUserId);
3328                    if (resolveInfo != null) {
3329                        return resolveInfo;
3330                    }
3331                }
3332            }
3333        }
3334        return null;
3335    }
3336
3337    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3338            Intent intent, String resolvedType, int flags, int userId) {
3339        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3340        SparseArray<ArrayList<String>> sourceForwardingInfo =
3341                mSettings.mCrossProfilePackageInfo.get(userId);
3342        if (sourceForwardingInfo != null) {
3343            int NI = sourceForwardingInfo.size();
3344            for (int i = 0; i < NI; i++) {
3345                int targetUserId = sourceForwardingInfo.keyAt(i);
3346                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3347                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3348                        intent, resolvedType, flags, targetUserId);
3349                int NJ = resolveInfos.size();
3350                for (int j = 0; j < NJ; j++) {
3351                    ResolveInfo resolveInfo = resolveInfos.get(j);
3352                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3353                        matchingResolveInfos.add(createForwardingResolveInfo(
3354                                resolveInfo.filter, userId, targetUserId));
3355                    }
3356                }
3357            }
3358        }
3359        return matchingResolveInfos;
3360    }
3361
3362    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3363            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3364            String packageName) {
3365        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3366        SparseArray<ArrayList<String>> sourceForwardingInfo =
3367                mSettings.mCrossProfilePackageInfo.get(userId);
3368        if (sourceForwardingInfo != null) {
3369            int NI = sourceForwardingInfo.size();
3370            for (int i = 0; i < NI; i++) {
3371                int targetUserId = sourceForwardingInfo.keyAt(i);
3372                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3373                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3374                            intent, resolvedType, flags, pkg.activities, targetUserId);
3375                    int NJ = resolveInfos.size();
3376                    for (int j = 0; j < NJ; j++) {
3377                        ResolveInfo resolveInfo = resolveInfos.get(j);
3378                        matchingResolveInfos.add(createForwardingResolveInfo(
3379                                resolveInfo.filter, userId, targetUserId));
3380                    }
3381                }
3382            }
3383        }
3384        return matchingResolveInfos;
3385    }
3386
3387    // Return matching ResolveInfo if any for skip current profile intent filters.
3388    private ResolveInfo queryCrossProfileIntents(
3389            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3390            int flags, int sourceUserId) {
3391        if (matchingFilters != null) {
3392            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3393            // match the same intent. For performance reasons, it is better not to
3394            // run queryIntent twice for the same userId
3395            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3396            int size = matchingFilters.size();
3397            for (int i = 0; i < size; i++) {
3398                CrossProfileIntentFilter filter = matchingFilters.get(i);
3399                int targetUserId = filter.getTargetUserId();
3400                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3401                        && !alreadyTriedUserIds.get(targetUserId)) {
3402                    // Checking if there are activities in the target user that can handle the
3403                    // intent.
3404                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3405                            flags, sourceUserId);
3406                    if (resolveInfo != null) return resolveInfo;
3407                    alreadyTriedUserIds.put(targetUserId, true);
3408                }
3409            }
3410        }
3411        return null;
3412    }
3413
3414    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3415            String resolvedType, int flags, int sourceUserId) {
3416        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3417                resolvedType, flags, filter.getTargetUserId());
3418        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3419            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3420        }
3421        return null;
3422    }
3423
3424    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3425            int sourceUserId, int targetUserId) {
3426        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3427        String className;
3428        if (targetUserId == UserHandle.USER_OWNER) {
3429            className = FORWARD_INTENT_TO_USER_OWNER;
3430        } else {
3431            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3432        }
3433        ComponentName forwardingActivityComponentName = new ComponentName(
3434                mAndroidApplication.packageName, className);
3435        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3436                sourceUserId);
3437        if (targetUserId == UserHandle.USER_OWNER) {
3438            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3439            forwardingResolveInfo.noResourceId = true;
3440        }
3441        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3442        forwardingResolveInfo.priority = 0;
3443        forwardingResolveInfo.preferredOrder = 0;
3444        forwardingResolveInfo.match = 0;
3445        forwardingResolveInfo.isDefault = true;
3446        forwardingResolveInfo.filter = filter;
3447        forwardingResolveInfo.targetUserId = targetUserId;
3448        return forwardingResolveInfo;
3449    }
3450
3451    @Override
3452    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3453            Intent[] specifics, String[] specificTypes, Intent intent,
3454            String resolvedType, int flags, int userId) {
3455        if (!sUserManager.exists(userId)) return Collections.emptyList();
3456        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3457                "query intent activity options");
3458        final String resultsAction = intent.getAction();
3459
3460        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3461                | PackageManager.GET_RESOLVED_FILTER, userId);
3462
3463        if (DEBUG_INTENT_MATCHING) {
3464            Log.v(TAG, "Query " + intent + ": " + results);
3465        }
3466
3467        int specificsPos = 0;
3468        int N;
3469
3470        // todo: note that the algorithm used here is O(N^2).  This
3471        // isn't a problem in our current environment, but if we start running
3472        // into situations where we have more than 5 or 10 matches then this
3473        // should probably be changed to something smarter...
3474
3475        // First we go through and resolve each of the specific items
3476        // that were supplied, taking care of removing any corresponding
3477        // duplicate items in the generic resolve list.
3478        if (specifics != null) {
3479            for (int i=0; i<specifics.length; i++) {
3480                final Intent sintent = specifics[i];
3481                if (sintent == null) {
3482                    continue;
3483                }
3484
3485                if (DEBUG_INTENT_MATCHING) {
3486                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3487                }
3488
3489                String action = sintent.getAction();
3490                if (resultsAction != null && resultsAction.equals(action)) {
3491                    // If this action was explicitly requested, then don't
3492                    // remove things that have it.
3493                    action = null;
3494                }
3495
3496                ResolveInfo ri = null;
3497                ActivityInfo ai = null;
3498
3499                ComponentName comp = sintent.getComponent();
3500                if (comp == null) {
3501                    ri = resolveIntent(
3502                        sintent,
3503                        specificTypes != null ? specificTypes[i] : null,
3504                            flags, userId);
3505                    if (ri == null) {
3506                        continue;
3507                    }
3508                    if (ri == mResolveInfo) {
3509                        // ACK!  Must do something better with this.
3510                    }
3511                    ai = ri.activityInfo;
3512                    comp = new ComponentName(ai.applicationInfo.packageName,
3513                            ai.name);
3514                } else {
3515                    ai = getActivityInfo(comp, flags, userId);
3516                    if (ai == null) {
3517                        continue;
3518                    }
3519                }
3520
3521                // Look for any generic query activities that are duplicates
3522                // of this specific one, and remove them from the results.
3523                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3524                N = results.size();
3525                int j;
3526                for (j=specificsPos; j<N; j++) {
3527                    ResolveInfo sri = results.get(j);
3528                    if ((sri.activityInfo.name.equals(comp.getClassName())
3529                            && sri.activityInfo.applicationInfo.packageName.equals(
3530                                    comp.getPackageName()))
3531                        || (action != null && sri.filter.matchAction(action))) {
3532                        results.remove(j);
3533                        if (DEBUG_INTENT_MATCHING) Log.v(
3534                            TAG, "Removing duplicate item from " + j
3535                            + " due to specific " + specificsPos);
3536                        if (ri == null) {
3537                            ri = sri;
3538                        }
3539                        j--;
3540                        N--;
3541                    }
3542                }
3543
3544                // Add this specific item to its proper place.
3545                if (ri == null) {
3546                    ri = new ResolveInfo();
3547                    ri.activityInfo = ai;
3548                }
3549                results.add(specificsPos, ri);
3550                ri.specificIndex = i;
3551                specificsPos++;
3552            }
3553        }
3554
3555        // Now we go through the remaining generic results and remove any
3556        // duplicate actions that are found here.
3557        N = results.size();
3558        for (int i=specificsPos; i<N-1; i++) {
3559            final ResolveInfo rii = results.get(i);
3560            if (rii.filter == null) {
3561                continue;
3562            }
3563
3564            // Iterate over all of the actions of this result's intent
3565            // filter...  typically this should be just one.
3566            final Iterator<String> it = rii.filter.actionsIterator();
3567            if (it == null) {
3568                continue;
3569            }
3570            while (it.hasNext()) {
3571                final String action = it.next();
3572                if (resultsAction != null && resultsAction.equals(action)) {
3573                    // If this action was explicitly requested, then don't
3574                    // remove things that have it.
3575                    continue;
3576                }
3577                for (int j=i+1; j<N; j++) {
3578                    final ResolveInfo rij = results.get(j);
3579                    if (rij.filter != null && rij.filter.hasAction(action)) {
3580                        results.remove(j);
3581                        if (DEBUG_INTENT_MATCHING) Log.v(
3582                            TAG, "Removing duplicate item from " + j
3583                            + " due to action " + action + " at " + i);
3584                        j--;
3585                        N--;
3586                    }
3587                }
3588            }
3589
3590            // If the caller didn't request filter information, drop it now
3591            // so we don't have to marshall/unmarshall it.
3592            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3593                rii.filter = null;
3594            }
3595        }
3596
3597        // Filter out the caller activity if so requested.
3598        if (caller != null) {
3599            N = results.size();
3600            for (int i=0; i<N; i++) {
3601                ActivityInfo ainfo = results.get(i).activityInfo;
3602                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3603                        && caller.getClassName().equals(ainfo.name)) {
3604                    results.remove(i);
3605                    break;
3606                }
3607            }
3608        }
3609
3610        // If the caller didn't request filter information,
3611        // drop them now so we don't have to
3612        // marshall/unmarshall it.
3613        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3614            N = results.size();
3615            for (int i=0; i<N; i++) {
3616                results.get(i).filter = null;
3617            }
3618        }
3619
3620        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3621        return results;
3622    }
3623
3624    @Override
3625    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3626            int userId) {
3627        if (!sUserManager.exists(userId)) return Collections.emptyList();
3628        ComponentName comp = intent.getComponent();
3629        if (comp == null) {
3630            if (intent.getSelector() != null) {
3631                intent = intent.getSelector();
3632                comp = intent.getComponent();
3633            }
3634        }
3635        if (comp != null) {
3636            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3637            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3638            if (ai != null) {
3639                ResolveInfo ri = new ResolveInfo();
3640                ri.activityInfo = ai;
3641                list.add(ri);
3642            }
3643            return list;
3644        }
3645
3646        // reader
3647        synchronized (mPackages) {
3648            String pkgName = intent.getPackage();
3649            if (pkgName == null) {
3650                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3651            }
3652            final PackageParser.Package pkg = mPackages.get(pkgName);
3653            if (pkg != null) {
3654                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3655                        userId);
3656            }
3657            return null;
3658        }
3659    }
3660
3661    @Override
3662    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3663        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3664        if (!sUserManager.exists(userId)) return null;
3665        if (query != null) {
3666            if (query.size() >= 1) {
3667                // If there is more than one service with the same priority,
3668                // just arbitrarily pick the first one.
3669                return query.get(0);
3670            }
3671        }
3672        return null;
3673    }
3674
3675    @Override
3676    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3677            int userId) {
3678        if (!sUserManager.exists(userId)) return Collections.emptyList();
3679        ComponentName comp = intent.getComponent();
3680        if (comp == null) {
3681            if (intent.getSelector() != null) {
3682                intent = intent.getSelector();
3683                comp = intent.getComponent();
3684            }
3685        }
3686        if (comp != null) {
3687            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3688            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3689            if (si != null) {
3690                final ResolveInfo ri = new ResolveInfo();
3691                ri.serviceInfo = si;
3692                list.add(ri);
3693            }
3694            return list;
3695        }
3696
3697        // reader
3698        synchronized (mPackages) {
3699            String pkgName = intent.getPackage();
3700            if (pkgName == null) {
3701                return mServices.queryIntent(intent, resolvedType, flags, userId);
3702            }
3703            final PackageParser.Package pkg = mPackages.get(pkgName);
3704            if (pkg != null) {
3705                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3706                        userId);
3707            }
3708            return null;
3709        }
3710    }
3711
3712    @Override
3713    public List<ResolveInfo> queryIntentContentProviders(
3714            Intent intent, String resolvedType, int flags, int userId) {
3715        if (!sUserManager.exists(userId)) return Collections.emptyList();
3716        ComponentName comp = intent.getComponent();
3717        if (comp == null) {
3718            if (intent.getSelector() != null) {
3719                intent = intent.getSelector();
3720                comp = intent.getComponent();
3721            }
3722        }
3723        if (comp != null) {
3724            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3725            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3726            if (pi != null) {
3727                final ResolveInfo ri = new ResolveInfo();
3728                ri.providerInfo = pi;
3729                list.add(ri);
3730            }
3731            return list;
3732        }
3733
3734        // reader
3735        synchronized (mPackages) {
3736            String pkgName = intent.getPackage();
3737            if (pkgName == null) {
3738                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3739            }
3740            final PackageParser.Package pkg = mPackages.get(pkgName);
3741            if (pkg != null) {
3742                return mProviders.queryIntentForPackage(
3743                        intent, resolvedType, flags, pkg.providers, userId);
3744            }
3745            return null;
3746        }
3747    }
3748
3749    @Override
3750    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3751        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3752
3753        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3754
3755        // writer
3756        synchronized (mPackages) {
3757            ArrayList<PackageInfo> list;
3758            if (listUninstalled) {
3759                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3760                for (PackageSetting ps : mSettings.mPackages.values()) {
3761                    PackageInfo pi;
3762                    if (ps.pkg != null) {
3763                        pi = generatePackageInfo(ps.pkg, flags, userId);
3764                    } else {
3765                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3766                    }
3767                    if (pi != null) {
3768                        list.add(pi);
3769                    }
3770                }
3771            } else {
3772                list = new ArrayList<PackageInfo>(mPackages.size());
3773                for (PackageParser.Package p : mPackages.values()) {
3774                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3775                    if (pi != null) {
3776                        list.add(pi);
3777                    }
3778                }
3779            }
3780
3781            return new ParceledListSlice<PackageInfo>(list);
3782        }
3783    }
3784
3785    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3786            String[] permissions, boolean[] tmp, int flags, int userId) {
3787        int numMatch = 0;
3788        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3789        for (int i=0; i<permissions.length; i++) {
3790            if (gp.grantedPermissions.contains(permissions[i])) {
3791                tmp[i] = true;
3792                numMatch++;
3793            } else {
3794                tmp[i] = false;
3795            }
3796        }
3797        if (numMatch == 0) {
3798            return;
3799        }
3800        PackageInfo pi;
3801        if (ps.pkg != null) {
3802            pi = generatePackageInfo(ps.pkg, flags, userId);
3803        } else {
3804            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3805        }
3806        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3807            if (numMatch == permissions.length) {
3808                pi.requestedPermissions = permissions;
3809            } else {
3810                pi.requestedPermissions = new String[numMatch];
3811                numMatch = 0;
3812                for (int i=0; i<permissions.length; i++) {
3813                    if (tmp[i]) {
3814                        pi.requestedPermissions[numMatch] = permissions[i];
3815                        numMatch++;
3816                    }
3817                }
3818            }
3819        }
3820        list.add(pi);
3821    }
3822
3823    @Override
3824    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3825            String[] permissions, int flags, int userId) {
3826        if (!sUserManager.exists(userId)) return null;
3827        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3828
3829        // writer
3830        synchronized (mPackages) {
3831            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3832            boolean[] tmpBools = new boolean[permissions.length];
3833            if (listUninstalled) {
3834                for (PackageSetting ps : mSettings.mPackages.values()) {
3835                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3836                }
3837            } else {
3838                for (PackageParser.Package pkg : mPackages.values()) {
3839                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3840                    if (ps != null) {
3841                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3842                                userId);
3843                    }
3844                }
3845            }
3846
3847            return new ParceledListSlice<PackageInfo>(list);
3848        }
3849    }
3850
3851    @Override
3852    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3853        if (!sUserManager.exists(userId)) return null;
3854        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3855
3856        // writer
3857        synchronized (mPackages) {
3858            ArrayList<ApplicationInfo> list;
3859            if (listUninstalled) {
3860                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3861                for (PackageSetting ps : mSettings.mPackages.values()) {
3862                    ApplicationInfo ai;
3863                    if (ps.pkg != null) {
3864                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3865                                ps.readUserState(userId), userId);
3866                    } else {
3867                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3868                    }
3869                    if (ai != null) {
3870                        list.add(ai);
3871                    }
3872                }
3873            } else {
3874                list = new ArrayList<ApplicationInfo>(mPackages.size());
3875                for (PackageParser.Package p : mPackages.values()) {
3876                    if (p.mExtras != null) {
3877                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3878                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3879                        if (ai != null) {
3880                            list.add(ai);
3881                        }
3882                    }
3883                }
3884            }
3885
3886            return new ParceledListSlice<ApplicationInfo>(list);
3887        }
3888    }
3889
3890    public List<ApplicationInfo> getPersistentApplications(int flags) {
3891        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3892
3893        // reader
3894        synchronized (mPackages) {
3895            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3896            final int userId = UserHandle.getCallingUserId();
3897            while (i.hasNext()) {
3898                final PackageParser.Package p = i.next();
3899                if (p.applicationInfo != null
3900                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3901                        && (!mSafeMode || isSystemApp(p))) {
3902                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3903                    if (ps != null) {
3904                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3905                                ps.readUserState(userId), userId);
3906                        if (ai != null) {
3907                            finalList.add(ai);
3908                        }
3909                    }
3910                }
3911            }
3912        }
3913
3914        return finalList;
3915    }
3916
3917    @Override
3918    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3919        if (!sUserManager.exists(userId)) return null;
3920        // reader
3921        synchronized (mPackages) {
3922            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3923            PackageSetting ps = provider != null
3924                    ? mSettings.mPackages.get(provider.owner.packageName)
3925                    : null;
3926            return ps != null
3927                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3928                    && (!mSafeMode || (provider.info.applicationInfo.flags
3929                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3930                    ? PackageParser.generateProviderInfo(provider, flags,
3931                            ps.readUserState(userId), userId)
3932                    : null;
3933        }
3934    }
3935
3936    /**
3937     * @deprecated
3938     */
3939    @Deprecated
3940    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3941        // reader
3942        synchronized (mPackages) {
3943            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3944                    .entrySet().iterator();
3945            final int userId = UserHandle.getCallingUserId();
3946            while (i.hasNext()) {
3947                Map.Entry<String, PackageParser.Provider> entry = i.next();
3948                PackageParser.Provider p = entry.getValue();
3949                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3950
3951                if (ps != null && p.syncable
3952                        && (!mSafeMode || (p.info.applicationInfo.flags
3953                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3954                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3955                            ps.readUserState(userId), userId);
3956                    if (info != null) {
3957                        outNames.add(entry.getKey());
3958                        outInfo.add(info);
3959                    }
3960                }
3961            }
3962        }
3963    }
3964
3965    @Override
3966    public List<ProviderInfo> queryContentProviders(String processName,
3967            int uid, int flags) {
3968        ArrayList<ProviderInfo> finalList = null;
3969        // reader
3970        synchronized (mPackages) {
3971            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3972            final int userId = processName != null ?
3973                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3974            while (i.hasNext()) {
3975                final PackageParser.Provider p = i.next();
3976                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3977                if (ps != null && p.info.authority != null
3978                        && (processName == null
3979                                || (p.info.processName.equals(processName)
3980                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3981                        && mSettings.isEnabledLPr(p.info, flags, userId)
3982                        && (!mSafeMode
3983                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3984                    if (finalList == null) {
3985                        finalList = new ArrayList<ProviderInfo>(3);
3986                    }
3987                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3988                            ps.readUserState(userId), userId);
3989                    if (info != null) {
3990                        finalList.add(info);
3991                    }
3992                }
3993            }
3994        }
3995
3996        if (finalList != null) {
3997            Collections.sort(finalList, mProviderInitOrderSorter);
3998        }
3999
4000        return finalList;
4001    }
4002
4003    @Override
4004    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4005            int flags) {
4006        // reader
4007        synchronized (mPackages) {
4008            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4009            return PackageParser.generateInstrumentationInfo(i, flags);
4010        }
4011    }
4012
4013    @Override
4014    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4015            int flags) {
4016        ArrayList<InstrumentationInfo> finalList =
4017            new ArrayList<InstrumentationInfo>();
4018
4019        // reader
4020        synchronized (mPackages) {
4021            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4022            while (i.hasNext()) {
4023                final PackageParser.Instrumentation p = i.next();
4024                if (targetPackage == null
4025                        || targetPackage.equals(p.info.targetPackage)) {
4026                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4027                            flags);
4028                    if (ii != null) {
4029                        finalList.add(ii);
4030                    }
4031                }
4032            }
4033        }
4034
4035        return finalList;
4036    }
4037
4038    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4039        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4040        if (overlays == null) {
4041            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4042            return;
4043        }
4044        for (PackageParser.Package opkg : overlays.values()) {
4045            // Not much to do if idmap fails: we already logged the error
4046            // and we certainly don't want to abort installation of pkg simply
4047            // because an overlay didn't fit properly. For these reasons,
4048            // ignore the return value of createIdmapForPackagePairLI.
4049            createIdmapForPackagePairLI(pkg, opkg);
4050        }
4051    }
4052
4053    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4054            PackageParser.Package opkg) {
4055        if (!opkg.mTrustedOverlay) {
4056            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4057                    opkg.baseCodePath + ": overlay not trusted");
4058            return false;
4059        }
4060        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4061        if (overlaySet == null) {
4062            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4063                    opkg.baseCodePath + " but target package has no known overlays");
4064            return false;
4065        }
4066        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4067        // TODO: generate idmap for split APKs
4068        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4069            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4070                    + opkg.baseCodePath);
4071            return false;
4072        }
4073        PackageParser.Package[] overlayArray =
4074            overlaySet.values().toArray(new PackageParser.Package[0]);
4075        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4076            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4077                return p1.mOverlayPriority - p2.mOverlayPriority;
4078            }
4079        };
4080        Arrays.sort(overlayArray, cmp);
4081
4082        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4083        int i = 0;
4084        for (PackageParser.Package p : overlayArray) {
4085            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4086        }
4087        return true;
4088    }
4089
4090    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4091        final File[] files = dir.listFiles();
4092        if (ArrayUtils.isEmpty(files)) {
4093            Log.d(TAG, "No files in app dir " + dir);
4094            return;
4095        }
4096
4097        if (DEBUG_PACKAGE_SCANNING) {
4098            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4099                    + " flags=0x" + Integer.toHexString(flags));
4100        }
4101
4102        for (File file : files) {
4103            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4104                    && !PackageInstallerService.isStageFile(file);
4105            if (!isPackage) {
4106                // Ignore entries which are not apk's
4107                continue;
4108            }
4109            try {
4110                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4111            } catch (PackageManagerException e) {
4112                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4113
4114                // Don't mess around with apps in system partition.
4115                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4116                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4117                    // Delete the apk
4118                    Slog.w(TAG, "Cleaning up failed install of " + file);
4119                    file.delete();
4120                }
4121            }
4122        }
4123    }
4124
4125    private static File getSettingsProblemFile() {
4126        File dataDir = Environment.getDataDirectory();
4127        File systemDir = new File(dataDir, "system");
4128        File fname = new File(systemDir, "uiderrors.txt");
4129        return fname;
4130    }
4131
4132    static void reportSettingsProblem(int priority, String msg) {
4133        try {
4134            File fname = getSettingsProblemFile();
4135            FileOutputStream out = new FileOutputStream(fname, true);
4136            PrintWriter pw = new FastPrintWriter(out);
4137            SimpleDateFormat formatter = new SimpleDateFormat();
4138            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4139            pw.println(dateString + ": " + msg);
4140            pw.close();
4141            FileUtils.setPermissions(
4142                    fname.toString(),
4143                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4144                    -1, -1);
4145        } catch (java.io.IOException e) {
4146        }
4147        Slog.println(priority, TAG, msg);
4148    }
4149
4150    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4151            PackageParser.Package pkg, File srcFile, int parseFlags)
4152            throws PackageManagerException {
4153        if (ps != null
4154                && ps.codePath.equals(srcFile)
4155                && ps.timeStamp == srcFile.lastModified()
4156                && !isCompatSignatureUpdateNeeded(pkg)) {
4157            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4158            if (ps.signatures.mSignatures != null
4159                    && ps.signatures.mSignatures.length != 0
4160                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4161                // Optimization: reuse the existing cached certificates
4162                // if the package appears to be unchanged.
4163                pkg.mSignatures = ps.signatures.mSignatures;
4164                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4165                synchronized (mPackages) {
4166                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4167                }
4168                return;
4169            }
4170
4171            Slog.w(TAG, "PackageSetting for " + ps.name
4172                    + " is missing signatures.  Collecting certs again to recover them.");
4173        } else {
4174            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4175        }
4176
4177        try {
4178            pp.collectCertificates(pkg, parseFlags);
4179            pp.collectManifestDigest(pkg);
4180        } catch (PackageParserException e) {
4181            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4182                    + pkg.packageName + ": " + e.getMessage());
4183        }
4184    }
4185
4186    /*
4187     *  Scan a package and return the newly parsed package.
4188     *  Returns null in case of errors and the error code is stored in mLastScanError
4189     */
4190    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4191            long currentTime, UserHandle user) throws PackageManagerException {
4192        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4193        parseFlags |= mDefParseFlags;
4194        PackageParser pp = new PackageParser();
4195        pp.setSeparateProcesses(mSeparateProcesses);
4196        pp.setOnlyCoreApps(mOnlyCore);
4197        pp.setDisplayMetrics(mMetrics);
4198
4199        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4200            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4201        }
4202
4203        final PackageParser.Package pkg;
4204        try {
4205            pkg = pp.parsePackage(scanFile, parseFlags);
4206        } catch (PackageParserException e) {
4207            throw new PackageManagerException(e.error,
4208                    "Failed to scan " + scanFile + ": " + e.getMessage());
4209        }
4210
4211        PackageSetting ps = null;
4212        PackageSetting updatedPkg;
4213        // reader
4214        synchronized (mPackages) {
4215            // Look to see if we already know about this package.
4216            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4217            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4218                // This package has been renamed to its original name.  Let's
4219                // use that.
4220                ps = mSettings.peekPackageLPr(oldName);
4221            }
4222            // If there was no original package, see one for the real package name.
4223            if (ps == null) {
4224                ps = mSettings.peekPackageLPr(pkg.packageName);
4225            }
4226            // Check to see if this package could be hiding/updating a system
4227            // package.  Must look for it either under the original or real
4228            // package name depending on our state.
4229            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4230            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4231        }
4232        boolean updatedPkgBetter = false;
4233        // First check if this is a system package that may involve an update
4234        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4235            if (ps != null && !ps.codePath.equals(scanFile)) {
4236                // The path has changed from what was last scanned...  check the
4237                // version of the new path against what we have stored to determine
4238                // what to do.
4239                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4240                if (pkg.mVersionCode < ps.versionCode) {
4241                    // The system package has been updated and the code path does not match
4242                    // Ignore entry. Skip it.
4243                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4244                            + " ignored: updated version " + ps.versionCode
4245                            + " better than this " + pkg.mVersionCode);
4246                    if (!updatedPkg.codePath.equals(scanFile)) {
4247                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4248                                + ps.name + " changing from " + updatedPkg.codePathString
4249                                + " to " + scanFile);
4250                        updatedPkg.codePath = scanFile;
4251                        updatedPkg.codePathString = scanFile.toString();
4252                        // This is the point at which we know that the system-disk APK
4253                        // for this package has moved during a reboot (e.g. due to an OTA),
4254                        // so we need to reevaluate it for privilege policy.
4255                        if (locationIsPrivileged(scanFile)) {
4256                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4257                        }
4258                    }
4259                    updatedPkg.pkg = pkg;
4260                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4261                } else {
4262                    // The current app on the system partition is better than
4263                    // what we have updated to on the data partition; switch
4264                    // back to the system partition version.
4265                    // At this point, its safely assumed that package installation for
4266                    // apps in system partition will go through. If not there won't be a working
4267                    // version of the app
4268                    // writer
4269                    synchronized (mPackages) {
4270                        // Just remove the loaded entries from package lists.
4271                        mPackages.remove(ps.name);
4272                    }
4273                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4274                            + "reverting from " + ps.codePathString
4275                            + ": new version " + pkg.mVersionCode
4276                            + " better than installed " + ps.versionCode);
4277
4278                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4279                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4280                            getAppDexInstructionSets(ps), isMultiArch(ps));
4281                    synchronized (mInstallLock) {
4282                        args.cleanUpResourcesLI();
4283                    }
4284                    synchronized (mPackages) {
4285                        mSettings.enableSystemPackageLPw(ps.name);
4286                    }
4287                    updatedPkgBetter = true;
4288                }
4289            }
4290        }
4291
4292        if (updatedPkg != null) {
4293            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4294            // initially
4295            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4296
4297            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4298            // flag set initially
4299            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4300                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4301            }
4302        }
4303
4304        // Verify certificates against what was last scanned
4305        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4306
4307        /*
4308         * A new system app appeared, but we already had a non-system one of the
4309         * same name installed earlier.
4310         */
4311        boolean shouldHideSystemApp = false;
4312        if (updatedPkg == null && ps != null
4313                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4314            /*
4315             * Check to make sure the signatures match first. If they don't,
4316             * wipe the installed application and its data.
4317             */
4318            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4319                    != PackageManager.SIGNATURE_MATCH) {
4320                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4321                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4322                ps = null;
4323            } else {
4324                /*
4325                 * If the newly-added system app is an older version than the
4326                 * already installed version, hide it. It will be scanned later
4327                 * and re-added like an update.
4328                 */
4329                if (pkg.mVersionCode < ps.versionCode) {
4330                    shouldHideSystemApp = true;
4331                } else {
4332                    /*
4333                     * The newly found system app is a newer version that the
4334                     * one previously installed. Simply remove the
4335                     * already-installed application and replace it with our own
4336                     * while keeping the application data.
4337                     */
4338                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4339                            + ps.codePathString + ": new version " + pkg.mVersionCode
4340                            + " better than installed " + ps.versionCode);
4341                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4342                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4343                            getAppDexInstructionSets(ps), isMultiArch(ps));
4344                    synchronized (mInstallLock) {
4345                        args.cleanUpResourcesLI();
4346                    }
4347                }
4348            }
4349        }
4350
4351        // The apk is forward locked (not public) if its code and resources
4352        // are kept in different files. (except for app in either system or
4353        // vendor path).
4354        // TODO grab this value from PackageSettings
4355        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4356            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4357                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4358            }
4359        }
4360
4361        // TODO: extend to support forward-locked splits
4362        String resourcePath = null;
4363        String baseResourcePath = null;
4364        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4365            if (ps != null && ps.resourcePathString != null) {
4366                resourcePath = ps.resourcePathString;
4367                baseResourcePath = ps.resourcePathString;
4368            } else {
4369                // Should not happen at all. Just log an error.
4370                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4371            }
4372        } else {
4373            resourcePath = pkg.codePath;
4374            baseResourcePath = pkg.baseCodePath;
4375        }
4376
4377        // Set application objects path explicitly.
4378        pkg.applicationInfo.setCodePath(pkg.codePath);
4379        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4380        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4381        pkg.applicationInfo.setResourcePath(resourcePath);
4382        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4383        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4384
4385        // Note that we invoke the following method only if we are about to unpack an application
4386        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4387                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4388
4389        /*
4390         * If the system app should be overridden by a previously installed
4391         * data, hide the system app now and let the /data/app scan pick it up
4392         * again.
4393         */
4394        if (shouldHideSystemApp) {
4395            synchronized (mPackages) {
4396                /*
4397                 * We have to grant systems permissions before we hide, because
4398                 * grantPermissions will assume the package update is trying to
4399                 * expand its permissions.
4400                 */
4401                grantPermissionsLPw(pkg, true);
4402                mSettings.disableSystemPackageLPw(pkg.packageName);
4403            }
4404        }
4405
4406        return scannedPkg;
4407    }
4408
4409    private static String fixProcessName(String defProcessName,
4410            String processName, int uid) {
4411        if (processName == null) {
4412            return defProcessName;
4413        }
4414        return processName;
4415    }
4416
4417    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4418            throws PackageManagerException {
4419        if (pkgSetting.signatures.mSignatures != null) {
4420            // Already existing package. Make sure signatures match
4421            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4422                    == PackageManager.SIGNATURE_MATCH;
4423            if (!match) {
4424                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4425                        == PackageManager.SIGNATURE_MATCH;
4426            }
4427            if (!match) {
4428                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4429                        + pkg.packageName + " signatures do not match the "
4430                        + "previously installed version; ignoring!");
4431            }
4432        }
4433
4434        // Check for shared user signatures
4435        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4436            // Already existing package. Make sure signatures match
4437            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4438                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4439            if (!match) {
4440                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4441                        == PackageManager.SIGNATURE_MATCH;
4442            }
4443            if (!match) {
4444                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4445                        "Package " + pkg.packageName
4446                        + " has no signatures that match those in shared user "
4447                        + pkgSetting.sharedUser.name + "; ignoring!");
4448            }
4449        }
4450    }
4451
4452    /**
4453     * Enforces that only the system UID or root's UID can call a method exposed
4454     * via Binder.
4455     *
4456     * @param message used as message if SecurityException is thrown
4457     * @throws SecurityException if the caller is not system or root
4458     */
4459    private static final void enforceSystemOrRoot(String message) {
4460        final int uid = Binder.getCallingUid();
4461        if (uid != Process.SYSTEM_UID && uid != 0) {
4462            throw new SecurityException(message);
4463        }
4464    }
4465
4466    @Override
4467    public void performBootDexOpt() {
4468        enforceSystemOrRoot("Only the system can request dexopt be performed");
4469
4470        final HashSet<PackageParser.Package> pkgs;
4471        synchronized (mPackages) {
4472            pkgs = mDeferredDexOpt;
4473            mDeferredDexOpt = null;
4474        }
4475
4476        if (pkgs != null) {
4477            // Filter out packages that aren't recently used.
4478            //
4479            // The exception is first boot of a non-eng device, which
4480            // should do a full dexopt.
4481            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4482            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4483                // TODO: add a property to control this?
4484                long dexOptLRUThresholdInMinutes;
4485                if (eng) {
4486                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4487                } else {
4488                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4489                }
4490                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4491
4492                int total = pkgs.size();
4493                int skipped = 0;
4494                long now = System.currentTimeMillis();
4495                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4496                    PackageParser.Package pkg = i.next();
4497                    long then = pkg.mLastPackageUsageTimeInMills;
4498                    if (then + dexOptLRUThresholdInMills < now) {
4499                        if (DEBUG_DEXOPT) {
4500                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4501                                  ((then == 0) ? "never" : new Date(then)));
4502                        }
4503                        i.remove();
4504                        skipped++;
4505                    }
4506                }
4507                if (DEBUG_DEXOPT) {
4508                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4509                }
4510            }
4511
4512            int i = 0;
4513            for (PackageParser.Package pkg : pkgs) {
4514                i++;
4515                if (DEBUG_DEXOPT) {
4516                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4517                          + ": " + pkg.packageName);
4518                }
4519                if (!isFirstBoot()) {
4520                    try {
4521                        ActivityManagerNative.getDefault().showBootMessage(
4522                                mContext.getResources().getString(
4523                                        R.string.android_upgrading_apk,
4524                                        i, pkgs.size()), true);
4525                    } catch (RemoteException e) {
4526                    }
4527                }
4528                PackageParser.Package p = pkg;
4529                synchronized (mInstallLock) {
4530                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4531                            true /* include dependencies */);
4532                }
4533            }
4534        }
4535    }
4536
4537    @Override
4538    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4539        return performDexOpt(packageName, instructionSet, true);
4540    }
4541
4542    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4543        if (info.primaryCpuAbi == null) {
4544            return getPreferredInstructionSet();
4545        }
4546
4547        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4548    }
4549
4550    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4551        PackageParser.Package p;
4552        final String targetInstructionSet;
4553        synchronized (mPackages) {
4554            p = mPackages.get(packageName);
4555            if (p == null) {
4556                return false;
4557            }
4558            if (updateUsage) {
4559                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4560            }
4561            mPackageUsage.write(false);
4562
4563            targetInstructionSet = instructionSet != null ? instructionSet :
4564                    getPrimaryInstructionSet(p.applicationInfo);
4565            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4566                return false;
4567            }
4568        }
4569
4570        synchronized (mInstallLock) {
4571            final String[] instructionSets = new String[] { targetInstructionSet };
4572            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4573                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4574        }
4575    }
4576
4577    public HashSet<String> getPackagesThatNeedDexOpt() {
4578        HashSet<String> pkgs = null;
4579        synchronized (mPackages) {
4580            for (PackageParser.Package p : mPackages.values()) {
4581                if (DEBUG_DEXOPT) {
4582                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4583                }
4584                if (!p.mDexOptPerformed.isEmpty()) {
4585                    continue;
4586                }
4587                if (pkgs == null) {
4588                    pkgs = new HashSet<String>();
4589                }
4590                pkgs.add(p.packageName);
4591            }
4592        }
4593        return pkgs;
4594    }
4595
4596    public void shutdown() {
4597        mPackageUsage.write(true);
4598    }
4599
4600    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4601             boolean forceDex, boolean defer, HashSet<String> done) {
4602        for (int i=0; i<libs.size(); i++) {
4603            PackageParser.Package libPkg;
4604            String libName;
4605            synchronized (mPackages) {
4606                libName = libs.get(i);
4607                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4608                if (lib != null && lib.apk != null) {
4609                    libPkg = mPackages.get(lib.apk);
4610                } else {
4611                    libPkg = null;
4612                }
4613            }
4614            if (libPkg != null && !done.contains(libName)) {
4615                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4616            }
4617        }
4618    }
4619
4620    static final int DEX_OPT_SKIPPED = 0;
4621    static final int DEX_OPT_PERFORMED = 1;
4622    static final int DEX_OPT_DEFERRED = 2;
4623    static final int DEX_OPT_FAILED = -1;
4624
4625    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4626            boolean forceDex, boolean defer, HashSet<String> done) {
4627        final String[] instructionSets = targetInstructionSets != null ?
4628                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4629
4630        if (done != null) {
4631            done.add(pkg.packageName);
4632            if (pkg.usesLibraries != null) {
4633                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4634            }
4635            if (pkg.usesOptionalLibraries != null) {
4636                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4637            }
4638        }
4639
4640        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4641            return DEX_OPT_SKIPPED;
4642        }
4643
4644        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4645        boolean performedDexOpt = false;
4646        // There are three basic cases here:
4647        // 1.) we need to dexopt, either because we are forced or it is needed
4648        // 2.) we are defering a needed dexopt
4649        // 3.) we are skipping an unneeded dexopt
4650        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4651        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4652            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4653                continue;
4654            }
4655
4656            for (String path : paths) {
4657                try {
4658                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4659                    // patckage or the one we find does not match the image checksum (i.e. it was
4660                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4661                    // odex file and it matches the checksum of the image but not its base address,
4662                    // meaning we need to move it.
4663                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4664                            pkg.packageName, dexCodeInstructionSet, defer);
4665                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4666                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4667                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet);
4668                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4669                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4670                                pkg.packageName, dexCodeInstructionSet);
4671
4672                        if (ret < 0) {
4673                            // Don't bother running dexopt again if we failed, it will probably
4674                            // just result in an error again. Also, don't bother dexopting for other
4675                            // paths & ISAs.
4676                            return DEX_OPT_FAILED;
4677                        }
4678
4679                        performedDexOpt = true;
4680                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4681                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4682                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4683                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4684                                pkg.packageName, dexCodeInstructionSet);
4685
4686                        if (ret < 0) {
4687                            // Don't bother running patchoat again if we failed, it will probably
4688                            // just result in an error again. Also, don't bother dexopting for other
4689                            // paths & ISAs.
4690                            return DEX_OPT_FAILED;
4691                        }
4692
4693                        performedDexOpt = true;
4694                    }
4695
4696                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4697                    // paths and instruction sets. We'll deal with them all together when we process
4698                    // our list of deferred dexopts.
4699                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4700                        if (mDeferredDexOpt == null) {
4701                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4702                        }
4703                        mDeferredDexOpt.add(pkg);
4704                        return DEX_OPT_DEFERRED;
4705                    }
4706                } catch (FileNotFoundException e) {
4707                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4708                    return DEX_OPT_FAILED;
4709                } catch (IOException e) {
4710                    Slog.w(TAG, "IOException reading apk: " + path, e);
4711                    return DEX_OPT_FAILED;
4712                } catch (StaleDexCacheError e) {
4713                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4714                    return DEX_OPT_FAILED;
4715                } catch (Exception e) {
4716                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4717                    return DEX_OPT_FAILED;
4718                }
4719            }
4720
4721            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4722            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4723            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4724            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4725            // it.
4726            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4727        }
4728
4729        // If we've gotten here, we're sure that no error occurred and that we haven't
4730        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4731        // we've skipped all of them because they are up to date. In both cases this
4732        // package doesn't need dexopt any longer.
4733        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4734    }
4735
4736    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4737        if (info.primaryCpuAbi != null) {
4738            if (info.secondaryCpuAbi != null) {
4739                return new String[] {
4740                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4741                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4742            } else {
4743                return new String[] {
4744                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4745            }
4746        }
4747
4748        return new String[] { getPreferredInstructionSet() };
4749    }
4750
4751    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4752        if (ps.primaryCpuAbiString != null) {
4753            if (ps.secondaryCpuAbiString != null) {
4754                return new String[] {
4755                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4756                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4757            } else {
4758                return new String[] {
4759                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4760            }
4761        }
4762
4763        return new String[] { getPreferredInstructionSet() };
4764    }
4765
4766    private static String getPreferredInstructionSet() {
4767        if (sPreferredInstructionSet == null) {
4768            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4769        }
4770
4771        return sPreferredInstructionSet;
4772    }
4773
4774    private static List<String> getAllInstructionSets() {
4775        final String[] allAbis = Build.SUPPORTED_ABIS;
4776        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4777
4778        for (String abi : allAbis) {
4779            final String instructionSet = VMRuntime.getInstructionSet(abi);
4780            if (!allInstructionSets.contains(instructionSet)) {
4781                allInstructionSets.add(instructionSet);
4782            }
4783        }
4784
4785        return allInstructionSets;
4786    }
4787
4788    /**
4789     * Returns the instruction set that should be used to compile dex code. In the presence of
4790     * a native bridge this might be different than the one shared libraries use.
4791     */
4792    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4793        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4794        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4795    }
4796
4797    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4798        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4799        for (String instructionSet : instructionSets) {
4800            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4801        }
4802        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4803    }
4804
4805    @Override
4806    public void forceDexOpt(String packageName) {
4807        enforceSystemOrRoot("forceDexOpt");
4808
4809        PackageParser.Package pkg;
4810        synchronized (mPackages) {
4811            pkg = mPackages.get(packageName);
4812            if (pkg == null) {
4813                throw new IllegalArgumentException("Missing package: " + packageName);
4814            }
4815        }
4816
4817        synchronized (mInstallLock) {
4818            final String[] instructionSets = new String[] {
4819                    getPrimaryInstructionSet(pkg.applicationInfo) };
4820            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4821            if (res != DEX_OPT_PERFORMED) {
4822                throw new IllegalStateException("Failed to dexopt: " + res);
4823            }
4824        }
4825    }
4826
4827    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4828                                boolean forceDex, boolean defer, boolean inclDependencies) {
4829        HashSet<String> done;
4830        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4831            done = new HashSet<String>();
4832            done.add(pkg.packageName);
4833        } else {
4834            done = null;
4835        }
4836        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4837    }
4838
4839    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4840        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4841            Slog.w(TAG, "Unable to update from " + oldPkg.name
4842                    + " to " + newPkg.packageName
4843                    + ": old package not in system partition");
4844            return false;
4845        } else if (mPackages.get(oldPkg.name) != null) {
4846            Slog.w(TAG, "Unable to update from " + oldPkg.name
4847                    + " to " + newPkg.packageName
4848                    + ": old package still exists");
4849            return false;
4850        }
4851        return true;
4852    }
4853
4854    File getDataPathForUser(int userId) {
4855        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4856    }
4857
4858    private File getDataPathForPackage(String packageName, int userId) {
4859        /*
4860         * Until we fully support multiple users, return the directory we
4861         * previously would have. The PackageManagerTests will need to be
4862         * revised when this is changed back..
4863         */
4864        if (userId == 0) {
4865            return new File(mAppDataDir, packageName);
4866        } else {
4867            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4868                + File.separator + packageName);
4869        }
4870    }
4871
4872    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4873        int[] users = sUserManager.getUserIds();
4874        int res = mInstaller.install(packageName, uid, uid, seinfo);
4875        if (res < 0) {
4876            return res;
4877        }
4878        for (int user : users) {
4879            if (user != 0) {
4880                res = mInstaller.createUserData(packageName,
4881                        UserHandle.getUid(user, uid), user, seinfo);
4882                if (res < 0) {
4883                    return res;
4884                }
4885            }
4886        }
4887        return res;
4888    }
4889
4890    private int removeDataDirsLI(String packageName) {
4891        int[] users = sUserManager.getUserIds();
4892        int res = 0;
4893        for (int user : users) {
4894            int resInner = mInstaller.remove(packageName, user);
4895            if (resInner < 0) {
4896                res = resInner;
4897            }
4898        }
4899
4900        return res;
4901    }
4902
4903    private int deleteCodeCacheDirsLI(String packageName) {
4904        int[] users = sUserManager.getUserIds();
4905        int res = 0;
4906        for (int user : users) {
4907            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4908            if (resInner < 0) {
4909                res = resInner;
4910            }
4911        }
4912        return res;
4913    }
4914
4915    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4916            PackageParser.Package changingLib) {
4917        if (file.path != null) {
4918            usesLibraryFiles.add(file.path);
4919            return;
4920        }
4921        PackageParser.Package p = mPackages.get(file.apk);
4922        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4923            // If we are doing this while in the middle of updating a library apk,
4924            // then we need to make sure to use that new apk for determining the
4925            // dependencies here.  (We haven't yet finished committing the new apk
4926            // to the package manager state.)
4927            if (p == null || p.packageName.equals(changingLib.packageName)) {
4928                p = changingLib;
4929            }
4930        }
4931        if (p != null) {
4932            usesLibraryFiles.addAll(p.getAllCodePaths());
4933        }
4934    }
4935
4936    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4937            PackageParser.Package changingLib) throws PackageManagerException {
4938        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4939            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4940            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4941            for (int i=0; i<N; i++) {
4942                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4943                if (file == null) {
4944                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4945                            "Package " + pkg.packageName + " requires unavailable shared library "
4946                            + pkg.usesLibraries.get(i) + "; failing!");
4947                }
4948                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4949            }
4950            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4951            for (int i=0; i<N; i++) {
4952                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4953                if (file == null) {
4954                    Slog.w(TAG, "Package " + pkg.packageName
4955                            + " desires unavailable shared library "
4956                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4957                } else {
4958                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4959                }
4960            }
4961            N = usesLibraryFiles.size();
4962            if (N > 0) {
4963                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4964            } else {
4965                pkg.usesLibraryFiles = null;
4966            }
4967        }
4968    }
4969
4970    private static boolean hasString(List<String> list, List<String> which) {
4971        if (list == null) {
4972            return false;
4973        }
4974        for (int i=list.size()-1; i>=0; i--) {
4975            for (int j=which.size()-1; j>=0; j--) {
4976                if (which.get(j).equals(list.get(i))) {
4977                    return true;
4978                }
4979            }
4980        }
4981        return false;
4982    }
4983
4984    private void updateAllSharedLibrariesLPw() {
4985        for (PackageParser.Package pkg : mPackages.values()) {
4986            try {
4987                updateSharedLibrariesLPw(pkg, null);
4988            } catch (PackageManagerException e) {
4989                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4990            }
4991        }
4992    }
4993
4994    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4995            PackageParser.Package changingPkg) {
4996        ArrayList<PackageParser.Package> res = null;
4997        for (PackageParser.Package pkg : mPackages.values()) {
4998            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4999                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5000                if (res == null) {
5001                    res = new ArrayList<PackageParser.Package>();
5002                }
5003                res.add(pkg);
5004                try {
5005                    updateSharedLibrariesLPw(pkg, changingPkg);
5006                } catch (PackageManagerException e) {
5007                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5008                }
5009            }
5010        }
5011        return res;
5012    }
5013
5014    /**
5015     * Derive the value of the {@code cpuAbiOverride} based on the provided
5016     * value and an optional stored value from the package settings.
5017     */
5018    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5019        String cpuAbiOverride = null;
5020
5021        if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5022            cpuAbiOverride = null;
5023        } else if (abiOverride != null) {
5024            cpuAbiOverride = abiOverride;
5025        } else if (settings != null) {
5026            cpuAbiOverride = settings.cpuAbiOverrideString;
5027        }
5028
5029        return cpuAbiOverride;
5030    }
5031
5032    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5033            int scanMode, long currentTime, UserHandle user)
5034            throws PackageManagerException {
5035        final File scanFile = new File(pkg.codePath);
5036        if (pkg.applicationInfo.getCodePath() == null ||
5037                pkg.applicationInfo.getResourcePath() == null) {
5038            // Bail out. The resource and code paths haven't been set.
5039            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5040                    "Code and resource paths haven't been set correctly");
5041        }
5042
5043        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5044            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5045        }
5046
5047        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5048            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5049        }
5050
5051        if (mCustomResolverComponentName != null &&
5052                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5053            setUpCustomResolverActivity(pkg);
5054        }
5055
5056        if (pkg.packageName.equals("android")) {
5057            synchronized (mPackages) {
5058                if (mAndroidApplication != null) {
5059                    Slog.w(TAG, "*************************************************");
5060                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5061                    Slog.w(TAG, " file=" + scanFile);
5062                    Slog.w(TAG, "*************************************************");
5063                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5064                            "Core android package being redefined.  Skipping.");
5065                }
5066
5067                // Set up information for our fall-back user intent resolution activity.
5068                mPlatformPackage = pkg;
5069                pkg.mVersionCode = mSdkVersion;
5070                mAndroidApplication = pkg.applicationInfo;
5071
5072                if (!mResolverReplaced) {
5073                    mResolveActivity.applicationInfo = mAndroidApplication;
5074                    mResolveActivity.name = ResolverActivity.class.getName();
5075                    mResolveActivity.packageName = mAndroidApplication.packageName;
5076                    mResolveActivity.processName = "system:ui";
5077                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5078                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5079                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5080                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5081                    mResolveActivity.exported = true;
5082                    mResolveActivity.enabled = true;
5083                    mResolveInfo.activityInfo = mResolveActivity;
5084                    mResolveInfo.priority = 0;
5085                    mResolveInfo.preferredOrder = 0;
5086                    mResolveInfo.match = 0;
5087                    mResolveComponentName = new ComponentName(
5088                            mAndroidApplication.packageName, mResolveActivity.name);
5089                }
5090            }
5091        }
5092
5093        if (DEBUG_PACKAGE_SCANNING) {
5094            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5095                Log.d(TAG, "Scanning package " + pkg.packageName);
5096        }
5097
5098        if (mPackages.containsKey(pkg.packageName)
5099                || mSharedLibraries.containsKey(pkg.packageName)) {
5100            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5101                    "Application package " + pkg.packageName
5102                    + " already installed.  Skipping duplicate.");
5103        }
5104
5105        // Initialize package source and resource directories
5106        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5107        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5108
5109        SharedUserSetting suid = null;
5110        PackageSetting pkgSetting = null;
5111
5112        if (!isSystemApp(pkg)) {
5113            // Only system apps can use these features.
5114            pkg.mOriginalPackages = null;
5115            pkg.mRealPackage = null;
5116            pkg.mAdoptPermissions = null;
5117        }
5118
5119        // writer
5120        synchronized (mPackages) {
5121            if (pkg.mSharedUserId != null) {
5122                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5123                if (suid == null) {
5124                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5125                            "Creating application package " + pkg.packageName
5126                            + " for shared user failed");
5127                }
5128                if (DEBUG_PACKAGE_SCANNING) {
5129                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5130                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5131                                + "): packages=" + suid.packages);
5132                }
5133            }
5134
5135            // Check if we are renaming from an original package name.
5136            PackageSetting origPackage = null;
5137            String realName = null;
5138            if (pkg.mOriginalPackages != null) {
5139                // This package may need to be renamed to a previously
5140                // installed name.  Let's check on that...
5141                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5142                if (pkg.mOriginalPackages.contains(renamed)) {
5143                    // This package had originally been installed as the
5144                    // original name, and we have already taken care of
5145                    // transitioning to the new one.  Just update the new
5146                    // one to continue using the old name.
5147                    realName = pkg.mRealPackage;
5148                    if (!pkg.packageName.equals(renamed)) {
5149                        // Callers into this function may have already taken
5150                        // care of renaming the package; only do it here if
5151                        // it is not already done.
5152                        pkg.setPackageName(renamed);
5153                    }
5154
5155                } else {
5156                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5157                        if ((origPackage = mSettings.peekPackageLPr(
5158                                pkg.mOriginalPackages.get(i))) != null) {
5159                            // We do have the package already installed under its
5160                            // original name...  should we use it?
5161                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5162                                // New package is not compatible with original.
5163                                origPackage = null;
5164                                continue;
5165                            } else if (origPackage.sharedUser != null) {
5166                                // Make sure uid is compatible between packages.
5167                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5168                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5169                                            + " to " + pkg.packageName + ": old uid "
5170                                            + origPackage.sharedUser.name
5171                                            + " differs from " + pkg.mSharedUserId);
5172                                    origPackage = null;
5173                                    continue;
5174                                }
5175                            } else {
5176                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5177                                        + pkg.packageName + " to old name " + origPackage.name);
5178                            }
5179                            break;
5180                        }
5181                    }
5182                }
5183            }
5184
5185            if (mTransferedPackages.contains(pkg.packageName)) {
5186                Slog.w(TAG, "Package " + pkg.packageName
5187                        + " was transferred to another, but its .apk remains");
5188            }
5189
5190            // Just create the setting, don't add it yet. For already existing packages
5191            // the PkgSetting exists already and doesn't have to be created.
5192            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5193                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5194                    pkg.applicationInfo.primaryCpuAbi,
5195                    pkg.applicationInfo.secondaryCpuAbi,
5196                    pkg.applicationInfo.flags, user, false);
5197            if (pkgSetting == null) {
5198                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5199                        "Creating application package " + pkg.packageName + " failed");
5200            }
5201
5202            if (pkgSetting.origPackage != null) {
5203                // If we are first transitioning from an original package,
5204                // fix up the new package's name now.  We need to do this after
5205                // looking up the package under its new name, so getPackageLP
5206                // can take care of fiddling things correctly.
5207                pkg.setPackageName(origPackage.name);
5208
5209                // File a report about this.
5210                String msg = "New package " + pkgSetting.realName
5211                        + " renamed to replace old package " + pkgSetting.name;
5212                reportSettingsProblem(Log.WARN, msg);
5213
5214                // Make a note of it.
5215                mTransferedPackages.add(origPackage.name);
5216
5217                // No longer need to retain this.
5218                pkgSetting.origPackage = null;
5219            }
5220
5221            if (realName != null) {
5222                // Make a note of it.
5223                mTransferedPackages.add(pkg.packageName);
5224            }
5225
5226            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5227                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5228            }
5229
5230            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5231                // Check all shared libraries and map to their actual file path.
5232                // We only do this here for apps not on a system dir, because those
5233                // are the only ones that can fail an install due to this.  We
5234                // will take care of the system apps by updating all of their
5235                // library paths after the scan is done.
5236                updateSharedLibrariesLPw(pkg, null);
5237            }
5238
5239            if (mFoundPolicyFile) {
5240                SELinuxMMAC.assignSeinfoValue(pkg);
5241            }
5242
5243            pkg.applicationInfo.uid = pkgSetting.appId;
5244            pkg.mExtras = pkgSetting;
5245            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5246                try {
5247                    verifySignaturesLP(pkgSetting, pkg);
5248                } catch (PackageManagerException e) {
5249                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5250                        throw e;
5251                    }
5252                    // The signature has changed, but this package is in the system
5253                    // image...  let's recover!
5254                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5255                    // However...  if this package is part of a shared user, but it
5256                    // doesn't match the signature of the shared user, let's fail.
5257                    // What this means is that you can't change the signatures
5258                    // associated with an overall shared user, which doesn't seem all
5259                    // that unreasonable.
5260                    if (pkgSetting.sharedUser != null) {
5261                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5262                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5263                            throw new PackageManagerException(
5264                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5265                                            "Signature mismatch for shared user : "
5266                                            + pkgSetting.sharedUser);
5267                        }
5268                    }
5269                    // File a report about this.
5270                    String msg = "System package " + pkg.packageName
5271                        + " signature changed; retaining data.";
5272                    reportSettingsProblem(Log.WARN, msg);
5273                }
5274            } else {
5275                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5276                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5277                            + pkg.packageName + " upgrade keys do not match the "
5278                            + "previously installed version");
5279                } else {
5280                    // signatures may have changed as result of upgrade
5281                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5282                }
5283            }
5284            // Verify that this new package doesn't have any content providers
5285            // that conflict with existing packages.  Only do this if the
5286            // package isn't already installed, since we don't want to break
5287            // things that are installed.
5288            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5289                final int N = pkg.providers.size();
5290                int i;
5291                for (i=0; i<N; i++) {
5292                    PackageParser.Provider p = pkg.providers.get(i);
5293                    if (p.info.authority != null) {
5294                        String names[] = p.info.authority.split(";");
5295                        for (int j = 0; j < names.length; j++) {
5296                            if (mProvidersByAuthority.containsKey(names[j])) {
5297                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5298                                final String otherPackageName =
5299                                        ((other != null && other.getComponentName() != null) ?
5300                                                other.getComponentName().getPackageName() : "?");
5301                                throw new PackageManagerException(
5302                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5303                                                "Can't install because provider name " + names[j]
5304                                                + " (in package " + pkg.applicationInfo.packageName
5305                                                + ") is already used by " + otherPackageName);
5306                            }
5307                        }
5308                    }
5309                }
5310            }
5311
5312            if (pkg.mAdoptPermissions != null) {
5313                // This package wants to adopt ownership of permissions from
5314                // another package.
5315                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5316                    final String origName = pkg.mAdoptPermissions.get(i);
5317                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5318                    if (orig != null) {
5319                        if (verifyPackageUpdateLPr(orig, pkg)) {
5320                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5321                                    + pkg.packageName);
5322                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5323                        }
5324                    }
5325                }
5326            }
5327        }
5328
5329        final String pkgName = pkg.packageName;
5330
5331        final long scanFileTime = scanFile.lastModified();
5332        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5333        pkg.applicationInfo.processName = fixProcessName(
5334                pkg.applicationInfo.packageName,
5335                pkg.applicationInfo.processName,
5336                pkg.applicationInfo.uid);
5337
5338        File dataPath;
5339        if (mPlatformPackage == pkg) {
5340            // The system package is special.
5341            dataPath = new File (Environment.getDataDirectory(), "system");
5342            pkg.applicationInfo.dataDir = dataPath.getPath();
5343
5344        } else {
5345            // This is a normal package, need to make its data directory.
5346            dataPath = getDataPathForPackage(pkg.packageName, 0);
5347
5348            boolean uidError = false;
5349
5350            if (dataPath.exists()) {
5351                int currentUid = 0;
5352                try {
5353                    StructStat stat = Os.stat(dataPath.getPath());
5354                    currentUid = stat.st_uid;
5355                } catch (ErrnoException e) {
5356                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5357                }
5358
5359                // If we have mismatched owners for the data path, we have a problem.
5360                if (currentUid != pkg.applicationInfo.uid) {
5361                    boolean recovered = false;
5362                    if (currentUid == 0) {
5363                        // The directory somehow became owned by root.  Wow.
5364                        // This is probably because the system was stopped while
5365                        // installd was in the middle of messing with its libs
5366                        // directory.  Ask installd to fix that.
5367                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5368                                pkg.applicationInfo.uid);
5369                        if (ret >= 0) {
5370                            recovered = true;
5371                            String msg = "Package " + pkg.packageName
5372                                    + " unexpectedly changed to uid 0; recovered to " +
5373                                    + pkg.applicationInfo.uid;
5374                            reportSettingsProblem(Log.WARN, msg);
5375                        }
5376                    }
5377                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5378                            || (scanMode&SCAN_BOOTING) != 0)) {
5379                        // If this is a system app, we can at least delete its
5380                        // current data so the application will still work.
5381                        int ret = removeDataDirsLI(pkgName);
5382                        if (ret >= 0) {
5383                            // TODO: Kill the processes first
5384                            // Old data gone!
5385                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5386                                    ? "System package " : "Third party package ";
5387                            String msg = prefix + pkg.packageName
5388                                    + " has changed from uid: "
5389                                    + currentUid + " to "
5390                                    + pkg.applicationInfo.uid + "; old data erased";
5391                            reportSettingsProblem(Log.WARN, msg);
5392                            recovered = true;
5393
5394                            // And now re-install the app.
5395                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5396                                                   pkg.applicationInfo.seinfo);
5397                            if (ret == -1) {
5398                                // Ack should not happen!
5399                                msg = prefix + pkg.packageName
5400                                        + " could not have data directory re-created after delete.";
5401                                reportSettingsProblem(Log.WARN, msg);
5402                                throw new PackageManagerException(
5403                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5404                            }
5405                        }
5406                        if (!recovered) {
5407                            mHasSystemUidErrors = true;
5408                        }
5409                    } else if (!recovered) {
5410                        // If we allow this install to proceed, we will be broken.
5411                        // Abort, abort!
5412                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5413                                "scanPackageLI");
5414                    }
5415                    if (!recovered) {
5416                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5417                            + pkg.applicationInfo.uid + "/fs_"
5418                            + currentUid;
5419                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5420                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5421                        String msg = "Package " + pkg.packageName
5422                                + " has mismatched uid: "
5423                                + currentUid + " on disk, "
5424                                + pkg.applicationInfo.uid + " in settings";
5425                        // writer
5426                        synchronized (mPackages) {
5427                            mSettings.mReadMessages.append(msg);
5428                            mSettings.mReadMessages.append('\n');
5429                            uidError = true;
5430                            if (!pkgSetting.uidError) {
5431                                reportSettingsProblem(Log.ERROR, msg);
5432                            }
5433                        }
5434                    }
5435                }
5436                pkg.applicationInfo.dataDir = dataPath.getPath();
5437                if (mShouldRestoreconData) {
5438                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5439                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5440                                pkg.applicationInfo.uid);
5441                }
5442            } else {
5443                if (DEBUG_PACKAGE_SCANNING) {
5444                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5445                        Log.v(TAG, "Want this data dir: " + dataPath);
5446                }
5447                //invoke installer to do the actual installation
5448                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5449                                           pkg.applicationInfo.seinfo);
5450                if (ret < 0) {
5451                    // Error from installer
5452                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5453                            "Unable to create data dirs [errorCode=" + ret + "]");
5454                }
5455
5456                if (dataPath.exists()) {
5457                    pkg.applicationInfo.dataDir = dataPath.getPath();
5458                } else {
5459                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5460                    pkg.applicationInfo.dataDir = null;
5461                }
5462            }
5463
5464            pkgSetting.uidError = uidError;
5465        }
5466
5467        final String path = scanFile.getPath();
5468        final String codePath = pkg.applicationInfo.getCodePath();
5469        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5470        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5471            setBundledAppAbisAndRoots(pkg, pkgSetting);
5472
5473            // If we haven't found any native libraries for the app, check if it has
5474            // renderscript code. We'll need to force the app to 32 bit if it has
5475            // renderscript bitcode.
5476            if (pkg.applicationInfo.primaryCpuAbi == null
5477                    && pkg.applicationInfo.secondaryCpuAbi == null
5478                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5479                NativeLibraryHelper.Handle handle = null;
5480                try {
5481                    handle = NativeLibraryHelper.Handle.create(scanFile);
5482                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5483                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5484                    }
5485                } catch (IOException ioe) {
5486                    Slog.w(TAG, "Error scanning system app : " + ioe);
5487                } finally {
5488                    IoUtils.closeQuietly(handle);
5489                }
5490            }
5491
5492            setNativeLibraryPaths(pkg);
5493        } else {
5494            // TODO: We can probably be smarter about this stuff. For installed apps,
5495            // we can calculate this information at install time once and for all. For
5496            // system apps, we can probably assume that this information doesn't change
5497            // after the first boot scan. As things stand, we do lots of unnecessary work.
5498
5499            // Give ourselves some initial paths; we'll come back for another
5500            // pass once we've determined ABI below.
5501            setNativeLibraryPaths(pkg);
5502
5503            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5504            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5505            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5506
5507            NativeLibraryHelper.Handle handle = null;
5508            try {
5509                handle = NativeLibraryHelper.Handle.create(scanFile);
5510                // TODO(multiArch): This can be null for apps that didn't go through the
5511                // usual installation process. We can calculate it again, like we
5512                // do during install time.
5513                //
5514                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5515                // unnecessary.
5516                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5517
5518                // Null out the abis so that they can be recalculated.
5519                pkg.applicationInfo.primaryCpuAbi = null;
5520                pkg.applicationInfo.secondaryCpuAbi = null;
5521                if (isMultiArch(pkg.applicationInfo)) {
5522                    // Warn if we've set an abiOverride for multi-lib packages..
5523                    // By definition, we need to copy both 32 and 64 bit libraries for
5524                    // such packages.
5525                    if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5526                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5527                    }
5528
5529                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5530                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5531                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5532                        if (isAsec) {
5533                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5534                        } else {
5535                            abi32 = copyNativeLibrariesForInternalApp(handle,
5536                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5537                        }
5538                    }
5539
5540                    maybeThrowExceptionForMultiArchCopy(
5541                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5542
5543                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5544                        if (isAsec) {
5545                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5546                        } else {
5547                            abi64 = copyNativeLibrariesForInternalApp(handle,
5548                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5549                        }
5550                    }
5551
5552                    maybeThrowExceptionForMultiArchCopy(
5553                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5554
5555                    if (abi64 >= 0) {
5556                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5557                    }
5558
5559                    if (abi32 >= 0) {
5560                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5561                        if (abi64 >= 0) {
5562                            pkg.applicationInfo.secondaryCpuAbi = abi;
5563                        } else {
5564                            pkg.applicationInfo.primaryCpuAbi = abi;
5565                        }
5566                    }
5567                } else {
5568                    String[] abiList = (cpuAbiOverride != null) ?
5569                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5570
5571                    // Enable gross and lame hacks for apps that are built with old
5572                    // SDK tools. We must scan their APKs for renderscript bitcode and
5573                    // not launch them if it's present. Don't bother checking on devices
5574                    // that don't have 64 bit support.
5575                    boolean needsRenderScriptOverride = false;
5576                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5577                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5578                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5579                        needsRenderScriptOverride = true;
5580                    }
5581
5582                    final int copyRet;
5583                    if (isAsec) {
5584                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5585                    } else {
5586                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5587                                useIsaSpecificSubdirs);
5588                    }
5589
5590                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5591                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5592                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5593                    }
5594
5595                    if (copyRet >= 0) {
5596                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5597                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5598                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5599                    } else if (needsRenderScriptOverride) {
5600                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5601                    }
5602                }
5603            } catch (IOException ioe) {
5604                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5605            } finally {
5606                IoUtils.closeQuietly(handle);
5607            }
5608
5609            // Now that we've calculated the ABIs and determined if it's an internal app,
5610            // we will go ahead and populate the nativeLibraryPath.
5611            setNativeLibraryPaths(pkg);
5612
5613            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5614            final int[] userIds = sUserManager.getUserIds();
5615            synchronized (mInstallLock) {
5616                // Create a native library symlink only if we have native libraries
5617                // and if the native libraries are 32 bit libraries. We do not provide
5618                // this symlink for 64 bit libraries.
5619                if (pkg.applicationInfo.primaryCpuAbi != null &&
5620                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5621                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5622                    for (int userId : userIds) {
5623                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5624                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5625                                    "Failed linking native library dir (user=" + userId + ")");
5626                        }
5627                    }
5628                }
5629            }
5630        }
5631
5632        // This is a special case for the "system" package, where the ABI is
5633        // dictated by the zygote configuration (and init.rc). We should keep track
5634        // of this ABI so that we can deal with "normal" applications that run under
5635        // the same UID correctly.
5636        if (mPlatformPackage == pkg) {
5637            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5638                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5639        }
5640
5641        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5642        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5643        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5644        // Copy the derived override back to the parsed package, so that we can
5645        // update the package settings accordingly.
5646        pkg.cpuAbiOverride = cpuAbiOverride;
5647
5648        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5649                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5650                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5651
5652        // Push the derived path down into PackageSettings so we know what to
5653        // clean up at uninstall time.
5654        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5655
5656        if (DEBUG_ABI_SELECTION) {
5657            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5658                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5659                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5660        }
5661
5662        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5663            // We don't do this here during boot because we can do it all
5664            // at once after scanning all existing packages.
5665            //
5666            // We also do this *before* we perform dexopt on this package, so that
5667            // we can avoid redundant dexopts, and also to make sure we've got the
5668            // code and package path correct.
5669            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5670                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5671        }
5672
5673        if ((scanMode&SCAN_NO_DEX) == 0) {
5674            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5675                    == DEX_OPT_FAILED) {
5676                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5677                    removeDataDirsLI(pkg.packageName);
5678                }
5679
5680                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5681            }
5682        }
5683
5684        if (mFactoryTest && pkg.requestedPermissions.contains(
5685                android.Manifest.permission.FACTORY_TEST)) {
5686            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5687        }
5688
5689        ArrayList<PackageParser.Package> clientLibPkgs = null;
5690
5691        // writer
5692        synchronized (mPackages) {
5693            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5694                // Only system apps can add new shared libraries.
5695                if (pkg.libraryNames != null) {
5696                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5697                        String name = pkg.libraryNames.get(i);
5698                        boolean allowed = false;
5699                        if (isUpdatedSystemApp(pkg)) {
5700                            // New library entries can only be added through the
5701                            // system image.  This is important to get rid of a lot
5702                            // of nasty edge cases: for example if we allowed a non-
5703                            // system update of the app to add a library, then uninstalling
5704                            // the update would make the library go away, and assumptions
5705                            // we made such as through app install filtering would now
5706                            // have allowed apps on the device which aren't compatible
5707                            // with it.  Better to just have the restriction here, be
5708                            // conservative, and create many fewer cases that can negatively
5709                            // impact the user experience.
5710                            final PackageSetting sysPs = mSettings
5711                                    .getDisabledSystemPkgLPr(pkg.packageName);
5712                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5713                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5714                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5715                                        allowed = true;
5716                                        allowed = true;
5717                                        break;
5718                                    }
5719                                }
5720                            }
5721                        } else {
5722                            allowed = true;
5723                        }
5724                        if (allowed) {
5725                            if (!mSharedLibraries.containsKey(name)) {
5726                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5727                            } else if (!name.equals(pkg.packageName)) {
5728                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5729                                        + name + " already exists; skipping");
5730                            }
5731                        } else {
5732                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5733                                    + name + " that is not declared on system image; skipping");
5734                        }
5735                    }
5736                    if ((scanMode&SCAN_BOOTING) == 0) {
5737                        // If we are not booting, we need to update any applications
5738                        // that are clients of our shared library.  If we are booting,
5739                        // this will all be done once the scan is complete.
5740                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5741                    }
5742                }
5743            }
5744        }
5745
5746        // We also need to dexopt any apps that are dependent on this library.  Note that
5747        // if these fail, we should abort the install since installing the library will
5748        // result in some apps being broken.
5749        if (clientLibPkgs != null) {
5750            if ((scanMode&SCAN_NO_DEX) == 0) {
5751                for (int i=0; i<clientLibPkgs.size(); i++) {
5752                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5753                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5754                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5755                            == DEX_OPT_FAILED) {
5756                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5757                            removeDataDirsLI(pkg.packageName);
5758                        }
5759
5760                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5761                                "scanPackageLI failed to dexopt clientLibPkgs");
5762                    }
5763                }
5764            }
5765        }
5766
5767        // Request the ActivityManager to kill the process(only for existing packages)
5768        // so that we do not end up in a confused state while the user is still using the older
5769        // version of the application while the new one gets installed.
5770        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5771            // If the package lives in an asec, tell everyone that the container is going
5772            // away so they can clean up any references to its resources (which would prevent
5773            // vold from being able to unmount the asec)
5774            if (isForwardLocked(pkg) || isExternal(pkg)) {
5775                if (DEBUG_INSTALL) {
5776                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5777                }
5778                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5779                final ArrayList<String> pkgList = new ArrayList<String>(1);
5780                pkgList.add(pkg.applicationInfo.packageName);
5781                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5782            }
5783
5784            // Post the request that it be killed now that the going-away broadcast is en route
5785            killApplication(pkg.applicationInfo.packageName,
5786                        pkg.applicationInfo.uid, "update pkg");
5787        }
5788
5789        // Also need to kill any apps that are dependent on the library.
5790        if (clientLibPkgs != null) {
5791            for (int i=0; i<clientLibPkgs.size(); i++) {
5792                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5793                killApplication(clientPkg.applicationInfo.packageName,
5794                        clientPkg.applicationInfo.uid, "update lib");
5795            }
5796        }
5797
5798        // writer
5799        synchronized (mPackages) {
5800            // We don't expect installation to fail beyond this point,
5801            if ((scanMode&SCAN_MONITOR) != 0) {
5802                mAppDirs.put(pkg.codePath, pkg);
5803            }
5804            // Add the new setting to mSettings
5805            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5806            // Add the new setting to mPackages
5807            mPackages.put(pkg.applicationInfo.packageName, pkg);
5808            // Make sure we don't accidentally delete its data.
5809            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5810            while (iter.hasNext()) {
5811                PackageCleanItem item = iter.next();
5812                if (pkgName.equals(item.packageName)) {
5813                    iter.remove();
5814                }
5815            }
5816
5817            // Take care of first install / last update times.
5818            if (currentTime != 0) {
5819                if (pkgSetting.firstInstallTime == 0) {
5820                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5821                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5822                    pkgSetting.lastUpdateTime = currentTime;
5823                }
5824            } else if (pkgSetting.firstInstallTime == 0) {
5825                // We need *something*.  Take time time stamp of the file.
5826                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5827            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5828                if (scanFileTime != pkgSetting.timeStamp) {
5829                    // A package on the system image has changed; consider this
5830                    // to be an update.
5831                    pkgSetting.lastUpdateTime = scanFileTime;
5832                }
5833            }
5834
5835            // Add the package's KeySets to the global KeySetManagerService
5836            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5837            try {
5838                // Old KeySetData no longer valid.
5839                ksms.removeAppKeySetDataLPw(pkg.packageName);
5840                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5841                if (pkg.mKeySetMapping != null) {
5842                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5843                            pkg.mKeySetMapping.entrySet()) {
5844                        if (entry.getValue() != null) {
5845                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5846                                                          entry.getValue(), entry.getKey());
5847                        }
5848                    }
5849                    if (pkg.mUpgradeKeySets != null) {
5850                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5851                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5852                        }
5853                    }
5854                }
5855            } catch (NullPointerException e) {
5856                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5857            } catch (IllegalArgumentException e) {
5858                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5859            }
5860
5861            int N = pkg.providers.size();
5862            StringBuilder r = null;
5863            int i;
5864            for (i=0; i<N; i++) {
5865                PackageParser.Provider p = pkg.providers.get(i);
5866                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5867                        p.info.processName, pkg.applicationInfo.uid);
5868                mProviders.addProvider(p);
5869                p.syncable = p.info.isSyncable;
5870                if (p.info.authority != null) {
5871                    String names[] = p.info.authority.split(";");
5872                    p.info.authority = null;
5873                    for (int j = 0; j < names.length; j++) {
5874                        if (j == 1 && p.syncable) {
5875                            // We only want the first authority for a provider to possibly be
5876                            // syncable, so if we already added this provider using a different
5877                            // authority clear the syncable flag. We copy the provider before
5878                            // changing it because the mProviders object contains a reference
5879                            // to a provider that we don't want to change.
5880                            // Only do this for the second authority since the resulting provider
5881                            // object can be the same for all future authorities for this provider.
5882                            p = new PackageParser.Provider(p);
5883                            p.syncable = false;
5884                        }
5885                        if (!mProvidersByAuthority.containsKey(names[j])) {
5886                            mProvidersByAuthority.put(names[j], p);
5887                            if (p.info.authority == null) {
5888                                p.info.authority = names[j];
5889                            } else {
5890                                p.info.authority = p.info.authority + ";" + names[j];
5891                            }
5892                            if (DEBUG_PACKAGE_SCANNING) {
5893                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5894                                    Log.d(TAG, "Registered content provider: " + names[j]
5895                                            + ", className = " + p.info.name + ", isSyncable = "
5896                                            + p.info.isSyncable);
5897                            }
5898                        } else {
5899                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5900                            Slog.w(TAG, "Skipping provider name " + names[j] +
5901                                    " (in package " + pkg.applicationInfo.packageName +
5902                                    "): name already used by "
5903                                    + ((other != null && other.getComponentName() != null)
5904                                            ? other.getComponentName().getPackageName() : "?"));
5905                        }
5906                    }
5907                }
5908                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5909                    if (r == null) {
5910                        r = new StringBuilder(256);
5911                    } else {
5912                        r.append(' ');
5913                    }
5914                    r.append(p.info.name);
5915                }
5916            }
5917            if (r != null) {
5918                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5919            }
5920
5921            N = pkg.services.size();
5922            r = null;
5923            for (i=0; i<N; i++) {
5924                PackageParser.Service s = pkg.services.get(i);
5925                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5926                        s.info.processName, pkg.applicationInfo.uid);
5927                mServices.addService(s);
5928                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5929                    if (r == null) {
5930                        r = new StringBuilder(256);
5931                    } else {
5932                        r.append(' ');
5933                    }
5934                    r.append(s.info.name);
5935                }
5936            }
5937            if (r != null) {
5938                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5939            }
5940
5941            N = pkg.receivers.size();
5942            r = null;
5943            for (i=0; i<N; i++) {
5944                PackageParser.Activity a = pkg.receivers.get(i);
5945                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5946                        a.info.processName, pkg.applicationInfo.uid);
5947                mReceivers.addActivity(a, "receiver");
5948                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5949                    if (r == null) {
5950                        r = new StringBuilder(256);
5951                    } else {
5952                        r.append(' ');
5953                    }
5954                    r.append(a.info.name);
5955                }
5956            }
5957            if (r != null) {
5958                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5959            }
5960
5961            N = pkg.activities.size();
5962            r = null;
5963            for (i=0; i<N; i++) {
5964                PackageParser.Activity a = pkg.activities.get(i);
5965                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5966                        a.info.processName, pkg.applicationInfo.uid);
5967                mActivities.addActivity(a, "activity");
5968                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5969                    if (r == null) {
5970                        r = new StringBuilder(256);
5971                    } else {
5972                        r.append(' ');
5973                    }
5974                    r.append(a.info.name);
5975                }
5976            }
5977            if (r != null) {
5978                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5979            }
5980
5981            N = pkg.permissionGroups.size();
5982            r = null;
5983            for (i=0; i<N; i++) {
5984                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5985                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5986                if (cur == null) {
5987                    mPermissionGroups.put(pg.info.name, pg);
5988                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5989                        if (r == null) {
5990                            r = new StringBuilder(256);
5991                        } else {
5992                            r.append(' ');
5993                        }
5994                        r.append(pg.info.name);
5995                    }
5996                } else {
5997                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5998                            + pg.info.packageName + " ignored: original from "
5999                            + cur.info.packageName);
6000                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6001                        if (r == null) {
6002                            r = new StringBuilder(256);
6003                        } else {
6004                            r.append(' ');
6005                        }
6006                        r.append("DUP:");
6007                        r.append(pg.info.name);
6008                    }
6009                }
6010            }
6011            if (r != null) {
6012                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6013            }
6014
6015            N = pkg.permissions.size();
6016            r = null;
6017            for (i=0; i<N; i++) {
6018                PackageParser.Permission p = pkg.permissions.get(i);
6019                HashMap<String, BasePermission> permissionMap =
6020                        p.tree ? mSettings.mPermissionTrees
6021                        : mSettings.mPermissions;
6022                p.group = mPermissionGroups.get(p.info.group);
6023                if (p.info.group == null || p.group != null) {
6024                    BasePermission bp = permissionMap.get(p.info.name);
6025                    if (bp == null) {
6026                        bp = new BasePermission(p.info.name, p.info.packageName,
6027                                BasePermission.TYPE_NORMAL);
6028                        permissionMap.put(p.info.name, bp);
6029                    }
6030                    if (bp.perm == null) {
6031                        if (bp.sourcePackage != null
6032                                && !bp.sourcePackage.equals(p.info.packageName)) {
6033                            // If this is a permission that was formerly defined by a non-system
6034                            // app, but is now defined by a system app (following an upgrade),
6035                            // discard the previous declaration and consider the system's to be
6036                            // canonical.
6037                            if (isSystemApp(p.owner)) {
6038                                String msg = "New decl " + p.owner + " of permission  "
6039                                        + p.info.name + " is system";
6040                                reportSettingsProblem(Log.WARN, msg);
6041                                bp.sourcePackage = null;
6042                            }
6043                        }
6044                        if (bp.sourcePackage == null
6045                                || bp.sourcePackage.equals(p.info.packageName)) {
6046                            BasePermission tree = findPermissionTreeLP(p.info.name);
6047                            if (tree == null
6048                                    || tree.sourcePackage.equals(p.info.packageName)) {
6049                                bp.packageSetting = pkgSetting;
6050                                bp.perm = p;
6051                                bp.uid = pkg.applicationInfo.uid;
6052                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6053                                    if (r == null) {
6054                                        r = new StringBuilder(256);
6055                                    } else {
6056                                        r.append(' ');
6057                                    }
6058                                    r.append(p.info.name);
6059                                }
6060                            } else {
6061                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6062                                        + p.info.packageName + " ignored: base tree "
6063                                        + tree.name + " is from package "
6064                                        + tree.sourcePackage);
6065                            }
6066                        } else {
6067                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6068                                    + p.info.packageName + " ignored: original from "
6069                                    + bp.sourcePackage);
6070                        }
6071                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6072                        if (r == null) {
6073                            r = new StringBuilder(256);
6074                        } else {
6075                            r.append(' ');
6076                        }
6077                        r.append("DUP:");
6078                        r.append(p.info.name);
6079                    }
6080                    if (bp.perm == p) {
6081                        bp.protectionLevel = p.info.protectionLevel;
6082                    }
6083                } else {
6084                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6085                            + p.info.packageName + " ignored: no group "
6086                            + p.group);
6087                }
6088            }
6089            if (r != null) {
6090                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6091            }
6092
6093            N = pkg.instrumentation.size();
6094            r = null;
6095            for (i=0; i<N; i++) {
6096                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6097                a.info.packageName = pkg.applicationInfo.packageName;
6098                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6099                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6100                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6101                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6102                a.info.dataDir = pkg.applicationInfo.dataDir;
6103
6104                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6105                // need other information about the application, like the ABI and what not ?
6106                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6107                mInstrumentation.put(a.getComponentName(), a);
6108                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6109                    if (r == null) {
6110                        r = new StringBuilder(256);
6111                    } else {
6112                        r.append(' ');
6113                    }
6114                    r.append(a.info.name);
6115                }
6116            }
6117            if (r != null) {
6118                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6119            }
6120
6121            if (pkg.protectedBroadcasts != null) {
6122                N = pkg.protectedBroadcasts.size();
6123                for (i=0; i<N; i++) {
6124                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6125                }
6126            }
6127
6128            pkgSetting.setTimeStamp(scanFileTime);
6129
6130            // Create idmap files for pairs of (packages, overlay packages).
6131            // Note: "android", ie framework-res.apk, is handled by native layers.
6132            if (pkg.mOverlayTarget != null) {
6133                // This is an overlay package.
6134                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6135                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6136                        mOverlays.put(pkg.mOverlayTarget,
6137                                new HashMap<String, PackageParser.Package>());
6138                    }
6139                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6140                    map.put(pkg.packageName, pkg);
6141                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6142                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6143                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6144                                "scanPackageLI failed to createIdmap");
6145                    }
6146                }
6147            } else if (mOverlays.containsKey(pkg.packageName) &&
6148                    !pkg.packageName.equals("android")) {
6149                // This is a regular package, with one or more known overlay packages.
6150                createIdmapsForPackageLI(pkg);
6151            }
6152        }
6153
6154        return pkg;
6155    }
6156
6157    /**
6158     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6159     * i.e, so that all packages can be run inside a single process if required.
6160     *
6161     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6162     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6163     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6164     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6165     * updating a package that belongs to a shared user.
6166     *
6167     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6168     * adds unnecessary complexity.
6169     */
6170    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6171            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6172        String requiredInstructionSet = null;
6173        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6174            requiredInstructionSet = VMRuntime.getInstructionSet(
6175                     scannedPackage.applicationInfo.primaryCpuAbi);
6176        }
6177
6178        PackageSetting requirer = null;
6179        for (PackageSetting ps : packagesForUser) {
6180            // If packagesForUser contains scannedPackage, we skip it. This will happen
6181            // when scannedPackage is an update of an existing package. Without this check,
6182            // we will never be able to change the ABI of any package belonging to a shared
6183            // user, even if it's compatible with other packages.
6184            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6185                if (ps.primaryCpuAbiString == null) {
6186                    continue;
6187                }
6188
6189                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6190                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6191                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6192                    // this but there's not much we can do.
6193                    String errorMessage = "Instruction set mismatch, "
6194                            + ((requirer == null) ? "[caller]" : requirer)
6195                            + " requires " + requiredInstructionSet + " whereas " + ps
6196                            + " requires " + instructionSet;
6197                    Slog.w(TAG, errorMessage);
6198                }
6199
6200                if (requiredInstructionSet == null) {
6201                    requiredInstructionSet = instructionSet;
6202                    requirer = ps;
6203                }
6204            }
6205        }
6206
6207        if (requiredInstructionSet != null) {
6208            String adjustedAbi;
6209            if (requirer != null) {
6210                // requirer != null implies that either scannedPackage was null or that scannedPackage
6211                // did not require an ABI, in which case we have to adjust scannedPackage to match
6212                // the ABI of the set (which is the same as requirer's ABI)
6213                adjustedAbi = requirer.primaryCpuAbiString;
6214                if (scannedPackage != null) {
6215                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6216                }
6217            } else {
6218                // requirer == null implies that we're updating all ABIs in the set to
6219                // match scannedPackage.
6220                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6221            }
6222
6223            for (PackageSetting ps : packagesForUser) {
6224                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6225                    if (ps.primaryCpuAbiString != null) {
6226                        continue;
6227                    }
6228
6229                    ps.primaryCpuAbiString = adjustedAbi;
6230                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6231                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6232                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6233
6234                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6235                                deferDexOpt, true) == DEX_OPT_FAILED) {
6236                            ps.primaryCpuAbiString = null;
6237                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6238                            return;
6239                        } else {
6240                            mInstaller.rmdex(ps.codePathString,
6241                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6242                        }
6243                    }
6244                }
6245            }
6246        }
6247    }
6248
6249    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6250        synchronized (mPackages) {
6251            mResolverReplaced = true;
6252            // Set up information for custom user intent resolution activity.
6253            mResolveActivity.applicationInfo = pkg.applicationInfo;
6254            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6255            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6256            mResolveActivity.processName = null;
6257            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6258            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6259                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6260            mResolveActivity.theme = 0;
6261            mResolveActivity.exported = true;
6262            mResolveActivity.enabled = true;
6263            mResolveInfo.activityInfo = mResolveActivity;
6264            mResolveInfo.priority = 0;
6265            mResolveInfo.preferredOrder = 0;
6266            mResolveInfo.match = 0;
6267            mResolveComponentName = mCustomResolverComponentName;
6268            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6269                    mResolveComponentName);
6270        }
6271    }
6272
6273    private static String calculateBundledApkRoot(final String codePathString) {
6274        final File codePath = new File(codePathString);
6275        final File codeRoot;
6276        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6277            codeRoot = Environment.getRootDirectory();
6278        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6279            codeRoot = Environment.getOemDirectory();
6280        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6281            codeRoot = Environment.getVendorDirectory();
6282        } else {
6283            // Unrecognized code path; take its top real segment as the apk root:
6284            // e.g. /something/app/blah.apk => /something
6285            try {
6286                File f = codePath.getCanonicalFile();
6287                File parent = f.getParentFile();    // non-null because codePath is a file
6288                File tmp;
6289                while ((tmp = parent.getParentFile()) != null) {
6290                    f = parent;
6291                    parent = tmp;
6292                }
6293                codeRoot = f;
6294                Slog.w(TAG, "Unrecognized code path "
6295                        + codePath + " - using " + codeRoot);
6296            } catch (IOException e) {
6297                // Can't canonicalize the code path -- shenanigans?
6298                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6299                return Environment.getRootDirectory().getPath();
6300            }
6301        }
6302        return codeRoot.getPath();
6303    }
6304
6305    /**
6306     * Derive and set the location of native libraries for the given package,
6307     * which varies depending on where and how the package was installed.
6308     */
6309    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6310        final ApplicationInfo info = pkg.applicationInfo;
6311        final String codePath = pkg.codePath;
6312        final File codeFile = new File(codePath);
6313        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6314        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6315
6316        info.nativeLibraryRootDir = null;
6317        info.nativeLibraryRootRequiresIsa = false;
6318        info.nativeLibraryDir = null;
6319        info.secondaryNativeLibraryDir = null;
6320
6321        if (isApkFile(codeFile)) {
6322            // Monolithic install
6323            if (bundledApp) {
6324                // If "/system/lib64/apkname" exists, assume that is the per-package
6325                // native library directory to use; otherwise use "/system/lib/apkname".
6326                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6327                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6328                        getPrimaryInstructionSet(info));
6329
6330                // This is a bundled system app so choose the path based on the ABI.
6331                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6332                // is just the default path.
6333                final String apkName = deriveCodePathName(codePath);
6334                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6335                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6336                        apkName).getAbsolutePath();
6337
6338                if (info.secondaryCpuAbi != null) {
6339                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6340                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6341                            secondaryLibDir, apkName).getAbsolutePath();
6342                }
6343            } else if (asecApp) {
6344                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6345                        .getAbsolutePath();
6346            } else {
6347                final String apkName = deriveCodePathName(codePath);
6348                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6349                        .getAbsolutePath();
6350            }
6351
6352            info.nativeLibraryRootRequiresIsa = false;
6353            info.nativeLibraryDir = info.nativeLibraryRootDir;
6354        } else {
6355            // Cluster install
6356            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6357            info.nativeLibraryRootRequiresIsa = true;
6358
6359            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6360                    getPrimaryInstructionSet(info)).getAbsolutePath();
6361
6362            if (info.secondaryCpuAbi != null) {
6363                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6364                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6365            }
6366        }
6367    }
6368
6369    /**
6370     * Calculate the abis and roots for a bundled app. These can uniquely
6371     * be determined from the contents of the system partition, i.e whether
6372     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6373     * of this information, and instead assume that the system was built
6374     * sensibly.
6375     */
6376    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6377                                           PackageSetting pkgSetting) {
6378        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6379
6380        // If "/system/lib64/apkname" exists, assume that is the per-package
6381        // native library directory to use; otherwise use "/system/lib/apkname".
6382        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6383        setBundledAppAbi(pkg, apkRoot, apkName);
6384        // pkgSetting might be null during rescan following uninstall of updates
6385        // to a bundled app, so accommodate that possibility.  The settings in
6386        // that case will be established later from the parsed package.
6387        //
6388        // If the settings aren't null, sync them up with what we've just derived.
6389        // note that apkRoot isn't stored in the package settings.
6390        if (pkgSetting != null) {
6391            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6392            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6393        }
6394    }
6395
6396    /**
6397     * Deduces the ABI of a bundled app and sets the relevant fields on the
6398     * parsed pkg object.
6399     *
6400     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6401     *        under which system libraries are installed.
6402     * @param apkName the name of the installed package.
6403     */
6404    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6405        final File codeFile = new File(pkg.codePath);
6406
6407        final boolean has64BitLibs;
6408        final boolean has32BitLibs;
6409        if (isApkFile(codeFile)) {
6410            // Monolithic install
6411            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6412            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6413        } else {
6414            // Cluster install
6415            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6416            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6417                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6418                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6419                has64BitLibs = (new File(rootDir, isa)).exists();
6420            } else {
6421                has64BitLibs = false;
6422            }
6423            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6424                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6425                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6426                has32BitLibs = (new File(rootDir, isa)).exists();
6427            } else {
6428                has32BitLibs = false;
6429            }
6430        }
6431
6432        if (has64BitLibs && !has32BitLibs) {
6433            // The package has 64 bit libs, but not 32 bit libs. Its primary
6434            // ABI should be 64 bit. We can safely assume here that the bundled
6435            // native libraries correspond to the most preferred ABI in the list.
6436
6437            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6438            pkg.applicationInfo.secondaryCpuAbi = null;
6439        } else if (has32BitLibs && !has64BitLibs) {
6440            // The package has 32 bit libs but not 64 bit libs. Its primary
6441            // ABI should be 32 bit.
6442
6443            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6444            pkg.applicationInfo.secondaryCpuAbi = null;
6445        } else if (has32BitLibs && has64BitLibs) {
6446            // The application has both 64 and 32 bit bundled libraries. We check
6447            // here that the app declares multiArch support, and warn if it doesn't.
6448            //
6449            // We will be lenient here and record both ABIs. The primary will be the
6450            // ABI that's higher on the list, i.e, a device that's configured to prefer
6451            // 64 bit apps will see a 64 bit primary ABI,
6452
6453            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6454                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6455            }
6456
6457            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6458                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6459                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6460            } else {
6461                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6462                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6463            }
6464        } else {
6465            pkg.applicationInfo.primaryCpuAbi = null;
6466            pkg.applicationInfo.secondaryCpuAbi = null;
6467        }
6468    }
6469
6470    private static void createNativeLibrarySubdir(File path) throws IOException {
6471        if (!path.isDirectory()) {
6472            path.delete();
6473
6474            if (!path.mkdir()) {
6475                throw new IOException("Cannot create " + path.getPath());
6476            }
6477
6478            try {
6479                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6480            } catch (ErrnoException e) {
6481                throw new IOException("Cannot chmod native library directory "
6482                        + path.getPath(), e);
6483            }
6484        } else if (!SELinux.restorecon(path)) {
6485            throw new IOException("Cannot set SELinux context for " + path.getPath());
6486        }
6487    }
6488
6489    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6490            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6491        createNativeLibrarySubdir(nativeLibraryRoot);
6492
6493        /*
6494         * If this is an internal application or our nativeLibraryPath points to
6495         * the app-lib directory, unpack the libraries if necessary.
6496         */
6497        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6498        if (abi >= 0) {
6499            /*
6500             * If we have a matching instruction set, construct a subdir under the native
6501             * library root that corresponds to this instruction set.
6502             */
6503            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6504            final File subDir;
6505            if (useIsaSubdir) {
6506                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6507                createNativeLibrarySubdir(isaSubdir);
6508                subDir = isaSubdir;
6509            } else {
6510                subDir = nativeLibraryRoot;
6511            }
6512
6513            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6514            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6515                return copyRet;
6516            }
6517        }
6518
6519        return abi;
6520    }
6521
6522    private void killApplication(String pkgName, int appId, String reason) {
6523        // Request the ActivityManager to kill the process(only for existing packages)
6524        // so that we do not end up in a confused state while the user is still using the older
6525        // version of the application while the new one gets installed.
6526        IActivityManager am = ActivityManagerNative.getDefault();
6527        if (am != null) {
6528            try {
6529                am.killApplicationWithAppId(pkgName, appId, reason);
6530            } catch (RemoteException e) {
6531            }
6532        }
6533    }
6534
6535    void removePackageLI(PackageSetting ps, boolean chatty) {
6536        if (DEBUG_INSTALL) {
6537            if (chatty)
6538                Log.d(TAG, "Removing package " + ps.name);
6539        }
6540
6541        // writer
6542        synchronized (mPackages) {
6543            mPackages.remove(ps.name);
6544            if (ps.codePathString != null) {
6545                mAppDirs.remove(ps.codePathString);
6546            }
6547
6548            final PackageParser.Package pkg = ps.pkg;
6549            if (pkg != null) {
6550                cleanPackageDataStructuresLILPw(pkg, chatty);
6551            }
6552        }
6553    }
6554
6555    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6556        if (DEBUG_INSTALL) {
6557            if (chatty)
6558                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6559        }
6560
6561        // writer
6562        synchronized (mPackages) {
6563            mPackages.remove(pkg.applicationInfo.packageName);
6564            if (pkg.codePath != null) {
6565                mAppDirs.remove(pkg.codePath);
6566            }
6567            cleanPackageDataStructuresLILPw(pkg, chatty);
6568        }
6569    }
6570
6571    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6572        int N = pkg.providers.size();
6573        StringBuilder r = null;
6574        int i;
6575        for (i=0; i<N; i++) {
6576            PackageParser.Provider p = pkg.providers.get(i);
6577            mProviders.removeProvider(p);
6578            if (p.info.authority == null) {
6579
6580                /* There was another ContentProvider with this authority when
6581                 * this app was installed so this authority is null,
6582                 * Ignore it as we don't have to unregister the provider.
6583                 */
6584                continue;
6585            }
6586            String names[] = p.info.authority.split(";");
6587            for (int j = 0; j < names.length; j++) {
6588                if (mProvidersByAuthority.get(names[j]) == p) {
6589                    mProvidersByAuthority.remove(names[j]);
6590                    if (DEBUG_REMOVE) {
6591                        if (chatty)
6592                            Log.d(TAG, "Unregistered content provider: " + names[j]
6593                                    + ", className = " + p.info.name + ", isSyncable = "
6594                                    + p.info.isSyncable);
6595                    }
6596                }
6597            }
6598            if (DEBUG_REMOVE && chatty) {
6599                if (r == null) {
6600                    r = new StringBuilder(256);
6601                } else {
6602                    r.append(' ');
6603                }
6604                r.append(p.info.name);
6605            }
6606        }
6607        if (r != null) {
6608            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6609        }
6610
6611        N = pkg.services.size();
6612        r = null;
6613        for (i=0; i<N; i++) {
6614            PackageParser.Service s = pkg.services.get(i);
6615            mServices.removeService(s);
6616            if (chatty) {
6617                if (r == null) {
6618                    r = new StringBuilder(256);
6619                } else {
6620                    r.append(' ');
6621                }
6622                r.append(s.info.name);
6623            }
6624        }
6625        if (r != null) {
6626            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6627        }
6628
6629        N = pkg.receivers.size();
6630        r = null;
6631        for (i=0; i<N; i++) {
6632            PackageParser.Activity a = pkg.receivers.get(i);
6633            mReceivers.removeActivity(a, "receiver");
6634            if (DEBUG_REMOVE && chatty) {
6635                if (r == null) {
6636                    r = new StringBuilder(256);
6637                } else {
6638                    r.append(' ');
6639                }
6640                r.append(a.info.name);
6641            }
6642        }
6643        if (r != null) {
6644            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6645        }
6646
6647        N = pkg.activities.size();
6648        r = null;
6649        for (i=0; i<N; i++) {
6650            PackageParser.Activity a = pkg.activities.get(i);
6651            mActivities.removeActivity(a, "activity");
6652            if (DEBUG_REMOVE && chatty) {
6653                if (r == null) {
6654                    r = new StringBuilder(256);
6655                } else {
6656                    r.append(' ');
6657                }
6658                r.append(a.info.name);
6659            }
6660        }
6661        if (r != null) {
6662            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6663        }
6664
6665        N = pkg.permissions.size();
6666        r = null;
6667        for (i=0; i<N; i++) {
6668            PackageParser.Permission p = pkg.permissions.get(i);
6669            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6670            if (bp == null) {
6671                bp = mSettings.mPermissionTrees.get(p.info.name);
6672            }
6673            if (bp != null && bp.perm == p) {
6674                bp.perm = null;
6675                if (DEBUG_REMOVE && chatty) {
6676                    if (r == null) {
6677                        r = new StringBuilder(256);
6678                    } else {
6679                        r.append(' ');
6680                    }
6681                    r.append(p.info.name);
6682                }
6683            }
6684            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6685                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6686                if (appOpPerms != null) {
6687                    appOpPerms.remove(pkg.packageName);
6688                }
6689            }
6690        }
6691        if (r != null) {
6692            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6693        }
6694
6695        N = pkg.requestedPermissions.size();
6696        r = null;
6697        for (i=0; i<N; i++) {
6698            String perm = pkg.requestedPermissions.get(i);
6699            BasePermission bp = mSettings.mPermissions.get(perm);
6700            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6701                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6702                if (appOpPerms != null) {
6703                    appOpPerms.remove(pkg.packageName);
6704                    if (appOpPerms.isEmpty()) {
6705                        mAppOpPermissionPackages.remove(perm);
6706                    }
6707                }
6708            }
6709        }
6710        if (r != null) {
6711            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6712        }
6713
6714        N = pkg.instrumentation.size();
6715        r = null;
6716        for (i=0; i<N; i++) {
6717            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6718            mInstrumentation.remove(a.getComponentName());
6719            if (DEBUG_REMOVE && chatty) {
6720                if (r == null) {
6721                    r = new StringBuilder(256);
6722                } else {
6723                    r.append(' ');
6724                }
6725                r.append(a.info.name);
6726            }
6727        }
6728        if (r != null) {
6729            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6730        }
6731
6732        r = null;
6733        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6734            // Only system apps can hold shared libraries.
6735            if (pkg.libraryNames != null) {
6736                for (i=0; i<pkg.libraryNames.size(); i++) {
6737                    String name = pkg.libraryNames.get(i);
6738                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6739                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6740                        mSharedLibraries.remove(name);
6741                        if (DEBUG_REMOVE && chatty) {
6742                            if (r == null) {
6743                                r = new StringBuilder(256);
6744                            } else {
6745                                r.append(' ');
6746                            }
6747                            r.append(name);
6748                        }
6749                    }
6750                }
6751            }
6752        }
6753        if (r != null) {
6754            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6755        }
6756    }
6757
6758    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6759        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6760            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6761                return true;
6762            }
6763        }
6764        return false;
6765    }
6766
6767    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6768    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6769    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6770
6771    private void updatePermissionsLPw(String changingPkg,
6772            PackageParser.Package pkgInfo, int flags) {
6773        // Make sure there are no dangling permission trees.
6774        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6775        while (it.hasNext()) {
6776            final BasePermission bp = it.next();
6777            if (bp.packageSetting == null) {
6778                // We may not yet have parsed the package, so just see if
6779                // we still know about its settings.
6780                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6781            }
6782            if (bp.packageSetting == null) {
6783                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6784                        + " from package " + bp.sourcePackage);
6785                it.remove();
6786            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6787                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6788                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6789                            + " from package " + bp.sourcePackage);
6790                    flags |= UPDATE_PERMISSIONS_ALL;
6791                    it.remove();
6792                }
6793            }
6794        }
6795
6796        // Make sure all dynamic permissions have been assigned to a package,
6797        // and make sure there are no dangling permissions.
6798        it = mSettings.mPermissions.values().iterator();
6799        while (it.hasNext()) {
6800            final BasePermission bp = it.next();
6801            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6802                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6803                        + bp.name + " pkg=" + bp.sourcePackage
6804                        + " info=" + bp.pendingInfo);
6805                if (bp.packageSetting == null && bp.pendingInfo != null) {
6806                    final BasePermission tree = findPermissionTreeLP(bp.name);
6807                    if (tree != null && tree.perm != null) {
6808                        bp.packageSetting = tree.packageSetting;
6809                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6810                                new PermissionInfo(bp.pendingInfo));
6811                        bp.perm.info.packageName = tree.perm.info.packageName;
6812                        bp.perm.info.name = bp.name;
6813                        bp.uid = tree.uid;
6814                    }
6815                }
6816            }
6817            if (bp.packageSetting == null) {
6818                // We may not yet have parsed the package, so just see if
6819                // we still know about its settings.
6820                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6821            }
6822            if (bp.packageSetting == null) {
6823                Slog.w(TAG, "Removing dangling permission: " + bp.name
6824                        + " from package " + bp.sourcePackage);
6825                it.remove();
6826            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6827                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6828                    Slog.i(TAG, "Removing old permission: " + bp.name
6829                            + " from package " + bp.sourcePackage);
6830                    flags |= UPDATE_PERMISSIONS_ALL;
6831                    it.remove();
6832                }
6833            }
6834        }
6835
6836        // Now update the permissions for all packages, in particular
6837        // replace the granted permissions of the system packages.
6838        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6839            for (PackageParser.Package pkg : mPackages.values()) {
6840                if (pkg != pkgInfo) {
6841                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6842                }
6843            }
6844        }
6845
6846        if (pkgInfo != null) {
6847            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6848        }
6849    }
6850
6851    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6852        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6853        if (ps == null) {
6854            return;
6855        }
6856        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6857        HashSet<String> origPermissions = gp.grantedPermissions;
6858        boolean changedPermission = false;
6859
6860        if (replace) {
6861            ps.permissionsFixed = false;
6862            if (gp == ps) {
6863                origPermissions = new HashSet<String>(gp.grantedPermissions);
6864                gp.grantedPermissions.clear();
6865                gp.gids = mGlobalGids;
6866            }
6867        }
6868
6869        if (gp.gids == null) {
6870            gp.gids = mGlobalGids;
6871        }
6872
6873        final int N = pkg.requestedPermissions.size();
6874        for (int i=0; i<N; i++) {
6875            final String name = pkg.requestedPermissions.get(i);
6876            final boolean required = pkg.requestedPermissionsRequired.get(i);
6877            final BasePermission bp = mSettings.mPermissions.get(name);
6878            if (DEBUG_INSTALL) {
6879                if (gp != ps) {
6880                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6881                }
6882            }
6883
6884            if (bp == null || bp.packageSetting == null) {
6885                Slog.w(TAG, "Unknown permission " + name
6886                        + " in package " + pkg.packageName);
6887                continue;
6888            }
6889
6890            final String perm = bp.name;
6891            boolean allowed;
6892            boolean allowedSig = false;
6893            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6894                // Keep track of app op permissions.
6895                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6896                if (pkgs == null) {
6897                    pkgs = new ArraySet<>();
6898                    mAppOpPermissionPackages.put(bp.name, pkgs);
6899                }
6900                pkgs.add(pkg.packageName);
6901            }
6902            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6903            if (level == PermissionInfo.PROTECTION_NORMAL
6904                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6905                // We grant a normal or dangerous permission if any of the following
6906                // are true:
6907                // 1) The permission is required
6908                // 2) The permission is optional, but was granted in the past
6909                // 3) The permission is optional, but was requested by an
6910                //    app in /system (not /data)
6911                //
6912                // Otherwise, reject the permission.
6913                allowed = (required || origPermissions.contains(perm)
6914                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6915            } else if (bp.packageSetting == null) {
6916                // This permission is invalid; skip it.
6917                allowed = false;
6918            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6919                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6920                if (allowed) {
6921                    allowedSig = true;
6922                }
6923            } else {
6924                allowed = false;
6925            }
6926            if (DEBUG_INSTALL) {
6927                if (gp != ps) {
6928                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6929                }
6930            }
6931            if (allowed) {
6932                if (!isSystemApp(ps) && ps.permissionsFixed) {
6933                    // If this is an existing, non-system package, then
6934                    // we can't add any new permissions to it.
6935                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6936                        // Except...  if this is a permission that was added
6937                        // to the platform (note: need to only do this when
6938                        // updating the platform).
6939                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6940                    }
6941                }
6942                if (allowed) {
6943                    if (!gp.grantedPermissions.contains(perm)) {
6944                        changedPermission = true;
6945                        gp.grantedPermissions.add(perm);
6946                        gp.gids = appendInts(gp.gids, bp.gids);
6947                    } else if (!ps.haveGids) {
6948                        gp.gids = appendInts(gp.gids, bp.gids);
6949                    }
6950                } else {
6951                    Slog.w(TAG, "Not granting permission " + perm
6952                            + " to package " + pkg.packageName
6953                            + " because it was previously installed without");
6954                }
6955            } else {
6956                if (gp.grantedPermissions.remove(perm)) {
6957                    changedPermission = true;
6958                    gp.gids = removeInts(gp.gids, bp.gids);
6959                    Slog.i(TAG, "Un-granting permission " + perm
6960                            + " from package " + pkg.packageName
6961                            + " (protectionLevel=" + bp.protectionLevel
6962                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6963                            + ")");
6964                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6965                    // Don't print warning for app op permissions, since it is fine for them
6966                    // not to be granted, there is a UI for the user to decide.
6967                    Slog.w(TAG, "Not granting permission " + perm
6968                            + " to package " + pkg.packageName
6969                            + " (protectionLevel=" + bp.protectionLevel
6970                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6971                            + ")");
6972                }
6973            }
6974        }
6975
6976        if ((changedPermission || replace) && !ps.permissionsFixed &&
6977                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6978            // This is the first that we have heard about this package, so the
6979            // permissions we have now selected are fixed until explicitly
6980            // changed.
6981            ps.permissionsFixed = true;
6982        }
6983        ps.haveGids = true;
6984    }
6985
6986    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6987        boolean allowed = false;
6988        final int NP = PackageParser.NEW_PERMISSIONS.length;
6989        for (int ip=0; ip<NP; ip++) {
6990            final PackageParser.NewPermissionInfo npi
6991                    = PackageParser.NEW_PERMISSIONS[ip];
6992            if (npi.name.equals(perm)
6993                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6994                allowed = true;
6995                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6996                        + pkg.packageName);
6997                break;
6998            }
6999        }
7000        return allowed;
7001    }
7002
7003    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7004                                          BasePermission bp, HashSet<String> origPermissions) {
7005        boolean allowed;
7006        allowed = (compareSignatures(
7007                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7008                        == PackageManager.SIGNATURE_MATCH)
7009                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7010                        == PackageManager.SIGNATURE_MATCH);
7011        if (!allowed && (bp.protectionLevel
7012                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7013            if (isSystemApp(pkg)) {
7014                // For updated system applications, a system permission
7015                // is granted only if it had been defined by the original application.
7016                if (isUpdatedSystemApp(pkg)) {
7017                    final PackageSetting sysPs = mSettings
7018                            .getDisabledSystemPkgLPr(pkg.packageName);
7019                    final GrantedPermissions origGp = sysPs.sharedUser != null
7020                            ? sysPs.sharedUser : sysPs;
7021
7022                    if (origGp.grantedPermissions.contains(perm)) {
7023                        // If the original was granted this permission, we take
7024                        // that grant decision as read and propagate it to the
7025                        // update.
7026                        allowed = true;
7027                    } else {
7028                        // The system apk may have been updated with an older
7029                        // version of the one on the data partition, but which
7030                        // granted a new system permission that it didn't have
7031                        // before.  In this case we do want to allow the app to
7032                        // now get the new permission if the ancestral apk is
7033                        // privileged to get it.
7034                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7035                            for (int j=0;
7036                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7037                                if (perm.equals(
7038                                        sysPs.pkg.requestedPermissions.get(j))) {
7039                                    allowed = true;
7040                                    break;
7041                                }
7042                            }
7043                        }
7044                    }
7045                } else {
7046                    allowed = isPrivilegedApp(pkg);
7047                }
7048            }
7049        }
7050        if (!allowed && (bp.protectionLevel
7051                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7052            // For development permissions, a development permission
7053            // is granted only if it was already granted.
7054            allowed = origPermissions.contains(perm);
7055        }
7056        return allowed;
7057    }
7058
7059    final class ActivityIntentResolver
7060            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7061        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7062                boolean defaultOnly, int userId) {
7063            if (!sUserManager.exists(userId)) return null;
7064            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7065            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7066        }
7067
7068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7069                int userId) {
7070            if (!sUserManager.exists(userId)) return null;
7071            mFlags = flags;
7072            return super.queryIntent(intent, resolvedType,
7073                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7074        }
7075
7076        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7077                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7078            if (!sUserManager.exists(userId)) return null;
7079            if (packageActivities == null) {
7080                return null;
7081            }
7082            mFlags = flags;
7083            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7084            final int N = packageActivities.size();
7085            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7086                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7087
7088            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7089            for (int i = 0; i < N; ++i) {
7090                intentFilters = packageActivities.get(i).intents;
7091                if (intentFilters != null && intentFilters.size() > 0) {
7092                    PackageParser.ActivityIntentInfo[] array =
7093                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7094                    intentFilters.toArray(array);
7095                    listCut.add(array);
7096                }
7097            }
7098            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7099        }
7100
7101        public final void addActivity(PackageParser.Activity a, String type) {
7102            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7103            mActivities.put(a.getComponentName(), a);
7104            if (DEBUG_SHOW_INFO)
7105                Log.v(
7106                TAG, "  " + type + " " +
7107                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7108            if (DEBUG_SHOW_INFO)
7109                Log.v(TAG, "    Class=" + a.info.name);
7110            final int NI = a.intents.size();
7111            for (int j=0; j<NI; j++) {
7112                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7113                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7114                    intent.setPriority(0);
7115                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7116                            + a.className + " with priority > 0, forcing to 0");
7117                }
7118                if (DEBUG_SHOW_INFO) {
7119                    Log.v(TAG, "    IntentFilter:");
7120                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7121                }
7122                if (!intent.debugCheck()) {
7123                    Log.w(TAG, "==> For Activity " + a.info.name);
7124                }
7125                addFilter(intent);
7126            }
7127        }
7128
7129        public final void removeActivity(PackageParser.Activity a, String type) {
7130            mActivities.remove(a.getComponentName());
7131            if (DEBUG_SHOW_INFO) {
7132                Log.v(TAG, "  " + type + " "
7133                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7134                                : a.info.name) + ":");
7135                Log.v(TAG, "    Class=" + a.info.name);
7136            }
7137            final int NI = a.intents.size();
7138            for (int j=0; j<NI; j++) {
7139                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7140                if (DEBUG_SHOW_INFO) {
7141                    Log.v(TAG, "    IntentFilter:");
7142                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7143                }
7144                removeFilter(intent);
7145            }
7146        }
7147
7148        @Override
7149        protected boolean allowFilterResult(
7150                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7151            ActivityInfo filterAi = filter.activity.info;
7152            for (int i=dest.size()-1; i>=0; i--) {
7153                ActivityInfo destAi = dest.get(i).activityInfo;
7154                if (destAi.name == filterAi.name
7155                        && destAi.packageName == filterAi.packageName) {
7156                    return false;
7157                }
7158            }
7159            return true;
7160        }
7161
7162        @Override
7163        protected ActivityIntentInfo[] newArray(int size) {
7164            return new ActivityIntentInfo[size];
7165        }
7166
7167        @Override
7168        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7169            if (!sUserManager.exists(userId)) return true;
7170            PackageParser.Package p = filter.activity.owner;
7171            if (p != null) {
7172                PackageSetting ps = (PackageSetting)p.mExtras;
7173                if (ps != null) {
7174                    // System apps are never considered stopped for purposes of
7175                    // filtering, because there may be no way for the user to
7176                    // actually re-launch them.
7177                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7178                            && ps.getStopped(userId);
7179                }
7180            }
7181            return false;
7182        }
7183
7184        @Override
7185        protected boolean isPackageForFilter(String packageName,
7186                PackageParser.ActivityIntentInfo info) {
7187            return packageName.equals(info.activity.owner.packageName);
7188        }
7189
7190        @Override
7191        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7192                int match, int userId) {
7193            if (!sUserManager.exists(userId)) return null;
7194            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7195                return null;
7196            }
7197            final PackageParser.Activity activity = info.activity;
7198            if (mSafeMode && (activity.info.applicationInfo.flags
7199                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7200                return null;
7201            }
7202            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7203            if (ps == null) {
7204                return null;
7205            }
7206            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7207                    ps.readUserState(userId), userId);
7208            if (ai == null) {
7209                return null;
7210            }
7211            final ResolveInfo res = new ResolveInfo();
7212            res.activityInfo = ai;
7213            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7214                res.filter = info;
7215            }
7216            res.priority = info.getPriority();
7217            res.preferredOrder = activity.owner.mPreferredOrder;
7218            //System.out.println("Result: " + res.activityInfo.className +
7219            //                   " = " + res.priority);
7220            res.match = match;
7221            res.isDefault = info.hasDefault;
7222            res.labelRes = info.labelRes;
7223            res.nonLocalizedLabel = info.nonLocalizedLabel;
7224            if (userNeedsBadging(userId)) {
7225                res.noResourceId = true;
7226            } else {
7227                res.icon = info.icon;
7228            }
7229            res.system = isSystemApp(res.activityInfo.applicationInfo);
7230            return res;
7231        }
7232
7233        @Override
7234        protected void sortResults(List<ResolveInfo> results) {
7235            Collections.sort(results, mResolvePrioritySorter);
7236        }
7237
7238        @Override
7239        protected void dumpFilter(PrintWriter out, String prefix,
7240                PackageParser.ActivityIntentInfo filter) {
7241            out.print(prefix); out.print(
7242                    Integer.toHexString(System.identityHashCode(filter.activity)));
7243                    out.print(' ');
7244                    filter.activity.printComponentShortName(out);
7245                    out.print(" filter ");
7246                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7247        }
7248
7249//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7250//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7251//            final List<ResolveInfo> retList = Lists.newArrayList();
7252//            while (i.hasNext()) {
7253//                final ResolveInfo resolveInfo = i.next();
7254//                if (isEnabledLP(resolveInfo.activityInfo)) {
7255//                    retList.add(resolveInfo);
7256//                }
7257//            }
7258//            return retList;
7259//        }
7260
7261        // Keys are String (activity class name), values are Activity.
7262        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7263                = new HashMap<ComponentName, PackageParser.Activity>();
7264        private int mFlags;
7265    }
7266
7267    private final class ServiceIntentResolver
7268            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7270                boolean defaultOnly, int userId) {
7271            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7272            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7273        }
7274
7275        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7276                int userId) {
7277            if (!sUserManager.exists(userId)) return null;
7278            mFlags = flags;
7279            return super.queryIntent(intent, resolvedType,
7280                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7281        }
7282
7283        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7284                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7285            if (!sUserManager.exists(userId)) return null;
7286            if (packageServices == null) {
7287                return null;
7288            }
7289            mFlags = flags;
7290            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7291            final int N = packageServices.size();
7292            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7293                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7294
7295            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7296            for (int i = 0; i < N; ++i) {
7297                intentFilters = packageServices.get(i).intents;
7298                if (intentFilters != null && intentFilters.size() > 0) {
7299                    PackageParser.ServiceIntentInfo[] array =
7300                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7301                    intentFilters.toArray(array);
7302                    listCut.add(array);
7303                }
7304            }
7305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7306        }
7307
7308        public final void addService(PackageParser.Service s) {
7309            mServices.put(s.getComponentName(), s);
7310            if (DEBUG_SHOW_INFO) {
7311                Log.v(TAG, "  "
7312                        + (s.info.nonLocalizedLabel != null
7313                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7314                Log.v(TAG, "    Class=" + s.info.name);
7315            }
7316            final int NI = s.intents.size();
7317            int j;
7318            for (j=0; j<NI; j++) {
7319                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7320                if (DEBUG_SHOW_INFO) {
7321                    Log.v(TAG, "    IntentFilter:");
7322                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7323                }
7324                if (!intent.debugCheck()) {
7325                    Log.w(TAG, "==> For Service " + s.info.name);
7326                }
7327                addFilter(intent);
7328            }
7329        }
7330
7331        public final void removeService(PackageParser.Service s) {
7332            mServices.remove(s.getComponentName());
7333            if (DEBUG_SHOW_INFO) {
7334                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7335                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7336                Log.v(TAG, "    Class=" + s.info.name);
7337            }
7338            final int NI = s.intents.size();
7339            int j;
7340            for (j=0; j<NI; j++) {
7341                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7342                if (DEBUG_SHOW_INFO) {
7343                    Log.v(TAG, "    IntentFilter:");
7344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7345                }
7346                removeFilter(intent);
7347            }
7348        }
7349
7350        @Override
7351        protected boolean allowFilterResult(
7352                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7353            ServiceInfo filterSi = filter.service.info;
7354            for (int i=dest.size()-1; i>=0; i--) {
7355                ServiceInfo destAi = dest.get(i).serviceInfo;
7356                if (destAi.name == filterSi.name
7357                        && destAi.packageName == filterSi.packageName) {
7358                    return false;
7359                }
7360            }
7361            return true;
7362        }
7363
7364        @Override
7365        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7366            return new PackageParser.ServiceIntentInfo[size];
7367        }
7368
7369        @Override
7370        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7371            if (!sUserManager.exists(userId)) return true;
7372            PackageParser.Package p = filter.service.owner;
7373            if (p != null) {
7374                PackageSetting ps = (PackageSetting)p.mExtras;
7375                if (ps != null) {
7376                    // System apps are never considered stopped for purposes of
7377                    // filtering, because there may be no way for the user to
7378                    // actually re-launch them.
7379                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7380                            && ps.getStopped(userId);
7381                }
7382            }
7383            return false;
7384        }
7385
7386        @Override
7387        protected boolean isPackageForFilter(String packageName,
7388                PackageParser.ServiceIntentInfo info) {
7389            return packageName.equals(info.service.owner.packageName);
7390        }
7391
7392        @Override
7393        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7394                int match, int userId) {
7395            if (!sUserManager.exists(userId)) return null;
7396            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7397            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7398                return null;
7399            }
7400            final PackageParser.Service service = info.service;
7401            if (mSafeMode && (service.info.applicationInfo.flags
7402                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7403                return null;
7404            }
7405            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7406            if (ps == null) {
7407                return null;
7408            }
7409            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7410                    ps.readUserState(userId), userId);
7411            if (si == null) {
7412                return null;
7413            }
7414            final ResolveInfo res = new ResolveInfo();
7415            res.serviceInfo = si;
7416            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7417                res.filter = filter;
7418            }
7419            res.priority = info.getPriority();
7420            res.preferredOrder = service.owner.mPreferredOrder;
7421            //System.out.println("Result: " + res.activityInfo.className +
7422            //                   " = " + res.priority);
7423            res.match = match;
7424            res.isDefault = info.hasDefault;
7425            res.labelRes = info.labelRes;
7426            res.nonLocalizedLabel = info.nonLocalizedLabel;
7427            res.icon = info.icon;
7428            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7429            return res;
7430        }
7431
7432        @Override
7433        protected void sortResults(List<ResolveInfo> results) {
7434            Collections.sort(results, mResolvePrioritySorter);
7435        }
7436
7437        @Override
7438        protected void dumpFilter(PrintWriter out, String prefix,
7439                PackageParser.ServiceIntentInfo filter) {
7440            out.print(prefix); out.print(
7441                    Integer.toHexString(System.identityHashCode(filter.service)));
7442                    out.print(' ');
7443                    filter.service.printComponentShortName(out);
7444                    out.print(" filter ");
7445                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7446        }
7447
7448//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7449//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7450//            final List<ResolveInfo> retList = Lists.newArrayList();
7451//            while (i.hasNext()) {
7452//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7453//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7454//                    retList.add(resolveInfo);
7455//                }
7456//            }
7457//            return retList;
7458//        }
7459
7460        // Keys are String (activity class name), values are Activity.
7461        private final HashMap<ComponentName, PackageParser.Service> mServices
7462                = new HashMap<ComponentName, PackageParser.Service>();
7463        private int mFlags;
7464    };
7465
7466    private final class ProviderIntentResolver
7467            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7468        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7469                boolean defaultOnly, int userId) {
7470            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7471            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7472        }
7473
7474        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7475                int userId) {
7476            if (!sUserManager.exists(userId))
7477                return null;
7478            mFlags = flags;
7479            return super.queryIntent(intent, resolvedType,
7480                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7481        }
7482
7483        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7484                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7485            if (!sUserManager.exists(userId))
7486                return null;
7487            if (packageProviders == null) {
7488                return null;
7489            }
7490            mFlags = flags;
7491            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7492            final int N = packageProviders.size();
7493            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7494                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7495
7496            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7497            for (int i = 0; i < N; ++i) {
7498                intentFilters = packageProviders.get(i).intents;
7499                if (intentFilters != null && intentFilters.size() > 0) {
7500                    PackageParser.ProviderIntentInfo[] array =
7501                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7502                    intentFilters.toArray(array);
7503                    listCut.add(array);
7504                }
7505            }
7506            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7507        }
7508
7509        public final void addProvider(PackageParser.Provider p) {
7510            if (mProviders.containsKey(p.getComponentName())) {
7511                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7512                return;
7513            }
7514
7515            mProviders.put(p.getComponentName(), p);
7516            if (DEBUG_SHOW_INFO) {
7517                Log.v(TAG, "  "
7518                        + (p.info.nonLocalizedLabel != null
7519                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7520                Log.v(TAG, "    Class=" + p.info.name);
7521            }
7522            final int NI = p.intents.size();
7523            int j;
7524            for (j = 0; j < NI; j++) {
7525                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7526                if (DEBUG_SHOW_INFO) {
7527                    Log.v(TAG, "    IntentFilter:");
7528                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7529                }
7530                if (!intent.debugCheck()) {
7531                    Log.w(TAG, "==> For Provider " + p.info.name);
7532                }
7533                addFilter(intent);
7534            }
7535        }
7536
7537        public final void removeProvider(PackageParser.Provider p) {
7538            mProviders.remove(p.getComponentName());
7539            if (DEBUG_SHOW_INFO) {
7540                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7541                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7542                Log.v(TAG, "    Class=" + p.info.name);
7543            }
7544            final int NI = p.intents.size();
7545            int j;
7546            for (j = 0; j < NI; j++) {
7547                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7548                if (DEBUG_SHOW_INFO) {
7549                    Log.v(TAG, "    IntentFilter:");
7550                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7551                }
7552                removeFilter(intent);
7553            }
7554        }
7555
7556        @Override
7557        protected boolean allowFilterResult(
7558                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7559            ProviderInfo filterPi = filter.provider.info;
7560            for (int i = dest.size() - 1; i >= 0; i--) {
7561                ProviderInfo destPi = dest.get(i).providerInfo;
7562                if (destPi.name == filterPi.name
7563                        && destPi.packageName == filterPi.packageName) {
7564                    return false;
7565                }
7566            }
7567            return true;
7568        }
7569
7570        @Override
7571        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7572            return new PackageParser.ProviderIntentInfo[size];
7573        }
7574
7575        @Override
7576        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7577            if (!sUserManager.exists(userId))
7578                return true;
7579            PackageParser.Package p = filter.provider.owner;
7580            if (p != null) {
7581                PackageSetting ps = (PackageSetting) p.mExtras;
7582                if (ps != null) {
7583                    // System apps are never considered stopped for purposes of
7584                    // filtering, because there may be no way for the user to
7585                    // actually re-launch them.
7586                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7587                            && ps.getStopped(userId);
7588                }
7589            }
7590            return false;
7591        }
7592
7593        @Override
7594        protected boolean isPackageForFilter(String packageName,
7595                PackageParser.ProviderIntentInfo info) {
7596            return packageName.equals(info.provider.owner.packageName);
7597        }
7598
7599        @Override
7600        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7601                int match, int userId) {
7602            if (!sUserManager.exists(userId))
7603                return null;
7604            final PackageParser.ProviderIntentInfo info = filter;
7605            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7606                return null;
7607            }
7608            final PackageParser.Provider provider = info.provider;
7609            if (mSafeMode && (provider.info.applicationInfo.flags
7610                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7611                return null;
7612            }
7613            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7614            if (ps == null) {
7615                return null;
7616            }
7617            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7618                    ps.readUserState(userId), userId);
7619            if (pi == null) {
7620                return null;
7621            }
7622            final ResolveInfo res = new ResolveInfo();
7623            res.providerInfo = pi;
7624            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7625                res.filter = filter;
7626            }
7627            res.priority = info.getPriority();
7628            res.preferredOrder = provider.owner.mPreferredOrder;
7629            res.match = match;
7630            res.isDefault = info.hasDefault;
7631            res.labelRes = info.labelRes;
7632            res.nonLocalizedLabel = info.nonLocalizedLabel;
7633            res.icon = info.icon;
7634            res.system = isSystemApp(res.providerInfo.applicationInfo);
7635            return res;
7636        }
7637
7638        @Override
7639        protected void sortResults(List<ResolveInfo> results) {
7640            Collections.sort(results, mResolvePrioritySorter);
7641        }
7642
7643        @Override
7644        protected void dumpFilter(PrintWriter out, String prefix,
7645                PackageParser.ProviderIntentInfo filter) {
7646            out.print(prefix);
7647            out.print(
7648                    Integer.toHexString(System.identityHashCode(filter.provider)));
7649            out.print(' ');
7650            filter.provider.printComponentShortName(out);
7651            out.print(" filter ");
7652            out.println(Integer.toHexString(System.identityHashCode(filter)));
7653        }
7654
7655        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7656                = new HashMap<ComponentName, PackageParser.Provider>();
7657        private int mFlags;
7658    };
7659
7660    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7661            new Comparator<ResolveInfo>() {
7662        public int compare(ResolveInfo r1, ResolveInfo r2) {
7663            int v1 = r1.priority;
7664            int v2 = r2.priority;
7665            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7666            if (v1 != v2) {
7667                return (v1 > v2) ? -1 : 1;
7668            }
7669            v1 = r1.preferredOrder;
7670            v2 = r2.preferredOrder;
7671            if (v1 != v2) {
7672                return (v1 > v2) ? -1 : 1;
7673            }
7674            if (r1.isDefault != r2.isDefault) {
7675                return r1.isDefault ? -1 : 1;
7676            }
7677            v1 = r1.match;
7678            v2 = r2.match;
7679            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7680            if (v1 != v2) {
7681                return (v1 > v2) ? -1 : 1;
7682            }
7683            if (r1.system != r2.system) {
7684                return r1.system ? -1 : 1;
7685            }
7686            return 0;
7687        }
7688    };
7689
7690    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7691            new Comparator<ProviderInfo>() {
7692        public int compare(ProviderInfo p1, ProviderInfo p2) {
7693            final int v1 = p1.initOrder;
7694            final int v2 = p2.initOrder;
7695            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7696        }
7697    };
7698
7699    static final void sendPackageBroadcast(String action, String pkg,
7700            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7701            int[] userIds) {
7702        IActivityManager am = ActivityManagerNative.getDefault();
7703        if (am != null) {
7704            try {
7705                if (userIds == null) {
7706                    userIds = am.getRunningUserIds();
7707                }
7708                for (int id : userIds) {
7709                    final Intent intent = new Intent(action,
7710                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7711                    if (extras != null) {
7712                        intent.putExtras(extras);
7713                    }
7714                    if (targetPkg != null) {
7715                        intent.setPackage(targetPkg);
7716                    }
7717                    // Modify the UID when posting to other users
7718                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7719                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7720                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7721                        intent.putExtra(Intent.EXTRA_UID, uid);
7722                    }
7723                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7724                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7725                    if (DEBUG_BROADCASTS) {
7726                        RuntimeException here = new RuntimeException("here");
7727                        here.fillInStackTrace();
7728                        Slog.d(TAG, "Sending to user " + id + ": "
7729                                + intent.toShortString(false, true, false, false)
7730                                + " " + intent.getExtras(), here);
7731                    }
7732                    am.broadcastIntent(null, intent, null, finishedReceiver,
7733                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7734                            finishedReceiver != null, false, id);
7735                }
7736            } catch (RemoteException ex) {
7737            }
7738        }
7739    }
7740
7741    /**
7742     * Check if the external storage media is available. This is true if there
7743     * is a mounted external storage medium or if the external storage is
7744     * emulated.
7745     */
7746    private boolean isExternalMediaAvailable() {
7747        return mMediaMounted || Environment.isExternalStorageEmulated();
7748    }
7749
7750    @Override
7751    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7752        // writer
7753        synchronized (mPackages) {
7754            if (!isExternalMediaAvailable()) {
7755                // If the external storage is no longer mounted at this point,
7756                // the caller may not have been able to delete all of this
7757                // packages files and can not delete any more.  Bail.
7758                return null;
7759            }
7760            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7761            if (lastPackage != null) {
7762                pkgs.remove(lastPackage);
7763            }
7764            if (pkgs.size() > 0) {
7765                return pkgs.get(0);
7766            }
7767        }
7768        return null;
7769    }
7770
7771    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7772        if (false) {
7773            RuntimeException here = new RuntimeException("here");
7774            here.fillInStackTrace();
7775            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7776                    + " andCode=" + andCode, here);
7777        }
7778        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7779                userId, andCode ? 1 : 0, packageName));
7780    }
7781
7782    void startCleaningPackages() {
7783        // reader
7784        synchronized (mPackages) {
7785            if (!isExternalMediaAvailable()) {
7786                return;
7787            }
7788            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7789                return;
7790            }
7791        }
7792        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7793        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7794        IActivityManager am = ActivityManagerNative.getDefault();
7795        if (am != null) {
7796            try {
7797                am.startService(null, intent, null, UserHandle.USER_OWNER);
7798            } catch (RemoteException e) {
7799            }
7800        }
7801    }
7802
7803    @Override
7804    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7805            String installerPackageName, VerificationParams verificationParams,
7806            String packageAbiOverride) {
7807        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7808                null);
7809
7810        final File originFile = new File(originPath);
7811        final int uid = Binder.getCallingUid();
7812        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7813            try {
7814                if (observer != null) {
7815                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7816                }
7817            } catch (RemoteException re) {
7818            }
7819            return;
7820        }
7821
7822        UserHandle user;
7823        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7824            user = UserHandle.ALL;
7825        } else {
7826            user = new UserHandle(UserHandle.getUserId(uid));
7827        }
7828
7829        final int filteredFlags;
7830        if (uid == Process.SHELL_UID || uid == 0) {
7831            if (DEBUG_INSTALL) {
7832                Slog.v(TAG, "Install from ADB");
7833            }
7834            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7835        } else {
7836            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7837        }
7838
7839        verificationParams.setInstallerUid(uid);
7840
7841        final Message msg = mHandler.obtainMessage(INIT_COPY);
7842        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7843                installerPackageName, verificationParams, user, packageAbiOverride);
7844        mHandler.sendMessage(msg);
7845    }
7846
7847    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7848            PackageInstaller.SessionParams params, String installerPackageName, int installerUid,
7849            UserHandle user) {
7850        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7851                params.referrerUri, installerUid, null);
7852
7853        final Message msg = mHandler.obtainMessage(INIT_COPY);
7854        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7855                installerPackageName, verifParams, user, params.abiOverride);
7856        mHandler.sendMessage(msg);
7857    }
7858
7859    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7860        Bundle extras = new Bundle(1);
7861        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7862
7863        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7864                packageName, extras, null, null, new int[] {userId});
7865        try {
7866            IActivityManager am = ActivityManagerNative.getDefault();
7867            final boolean isSystem =
7868                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7869            if (isSystem && am.isUserRunning(userId, false)) {
7870                // The just-installed/enabled app is bundled on the system, so presumed
7871                // to be able to run automatically without needing an explicit launch.
7872                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7873                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7874                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7875                        .setPackage(packageName);
7876                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7877                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7878            }
7879        } catch (RemoteException e) {
7880            // shouldn't happen
7881            Slog.w(TAG, "Unable to bootstrap installed package", e);
7882        }
7883    }
7884
7885    @Override
7886    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7887            int userId) {
7888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7889        PackageSetting pkgSetting;
7890        final int uid = Binder.getCallingUid();
7891        if (UserHandle.getUserId(uid) != userId) {
7892            mContext.enforceCallingOrSelfPermission(
7893                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7894                    "setApplicationHiddenSetting for user " + userId);
7895        }
7896
7897        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7898            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7899            return false;
7900        }
7901
7902        long callingId = Binder.clearCallingIdentity();
7903        try {
7904            boolean sendAdded = false;
7905            boolean sendRemoved = false;
7906            // writer
7907            synchronized (mPackages) {
7908                pkgSetting = mSettings.mPackages.get(packageName);
7909                if (pkgSetting == null) {
7910                    return false;
7911                }
7912                if (pkgSetting.getHidden(userId) != hidden) {
7913                    pkgSetting.setHidden(hidden, userId);
7914                    mSettings.writePackageRestrictionsLPr(userId);
7915                    if (hidden) {
7916                        sendRemoved = true;
7917                    } else {
7918                        sendAdded = true;
7919                    }
7920                }
7921            }
7922            if (sendAdded) {
7923                sendPackageAddedForUser(packageName, pkgSetting, userId);
7924                return true;
7925            }
7926            if (sendRemoved) {
7927                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7928                        "hiding pkg");
7929                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7930            }
7931        } finally {
7932            Binder.restoreCallingIdentity(callingId);
7933        }
7934        return false;
7935    }
7936
7937    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7938            int userId) {
7939        final PackageRemovedInfo info = new PackageRemovedInfo();
7940        info.removedPackage = packageName;
7941        info.removedUsers = new int[] {userId};
7942        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7943        info.sendBroadcast(false, false, false);
7944    }
7945
7946    /**
7947     * Returns true if application is not found or there was an error. Otherwise it returns
7948     * the hidden state of the package for the given user.
7949     */
7950    @Override
7951    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7953        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7954                "getApplicationHidden for user " + userId);
7955        PackageSetting pkgSetting;
7956        long callingId = Binder.clearCallingIdentity();
7957        try {
7958            // writer
7959            synchronized (mPackages) {
7960                pkgSetting = mSettings.mPackages.get(packageName);
7961                if (pkgSetting == null) {
7962                    return true;
7963                }
7964                return pkgSetting.getHidden(userId);
7965            }
7966        } finally {
7967            Binder.restoreCallingIdentity(callingId);
7968        }
7969    }
7970
7971    /**
7972     * @hide
7973     */
7974    @Override
7975    public int installExistingPackageAsUser(String packageName, int userId) {
7976        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7977                null);
7978        PackageSetting pkgSetting;
7979        final int uid = Binder.getCallingUid();
7980        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7981        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7982            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7983        }
7984
7985        long callingId = Binder.clearCallingIdentity();
7986        try {
7987            boolean sendAdded = false;
7988            Bundle extras = new Bundle(1);
7989
7990            // writer
7991            synchronized (mPackages) {
7992                pkgSetting = mSettings.mPackages.get(packageName);
7993                if (pkgSetting == null) {
7994                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7995                }
7996                if (!pkgSetting.getInstalled(userId)) {
7997                    pkgSetting.setInstalled(true, userId);
7998                    pkgSetting.setHidden(false, userId);
7999                    mSettings.writePackageRestrictionsLPr(userId);
8000                    sendAdded = true;
8001                }
8002            }
8003
8004            if (sendAdded) {
8005                sendPackageAddedForUser(packageName, pkgSetting, userId);
8006            }
8007        } finally {
8008            Binder.restoreCallingIdentity(callingId);
8009        }
8010
8011        return PackageManager.INSTALL_SUCCEEDED;
8012    }
8013
8014    boolean isUserRestricted(int userId, String restrictionKey) {
8015        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8016        if (restrictions.getBoolean(restrictionKey, false)) {
8017            Log.w(TAG, "User is restricted: " + restrictionKey);
8018            return true;
8019        }
8020        return false;
8021    }
8022
8023    @Override
8024    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8025        mContext.enforceCallingOrSelfPermission(
8026                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8027                "Only package verification agents can verify applications");
8028
8029        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8030        final PackageVerificationResponse response = new PackageVerificationResponse(
8031                verificationCode, Binder.getCallingUid());
8032        msg.arg1 = id;
8033        msg.obj = response;
8034        mHandler.sendMessage(msg);
8035    }
8036
8037    @Override
8038    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8039            long millisecondsToDelay) {
8040        mContext.enforceCallingOrSelfPermission(
8041                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8042                "Only package verification agents can extend verification timeouts");
8043
8044        final PackageVerificationState state = mPendingVerification.get(id);
8045        final PackageVerificationResponse response = new PackageVerificationResponse(
8046                verificationCodeAtTimeout, Binder.getCallingUid());
8047
8048        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8049            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8050        }
8051        if (millisecondsToDelay < 0) {
8052            millisecondsToDelay = 0;
8053        }
8054        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8055                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8056            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8057        }
8058
8059        if ((state != null) && !state.timeoutExtended()) {
8060            state.extendTimeout();
8061
8062            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8063            msg.arg1 = id;
8064            msg.obj = response;
8065            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8066        }
8067    }
8068
8069    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8070            int verificationCode, UserHandle user) {
8071        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8072        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8073        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8074        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8075        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8076
8077        mContext.sendBroadcastAsUser(intent, user,
8078                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8079    }
8080
8081    private ComponentName matchComponentForVerifier(String packageName,
8082            List<ResolveInfo> receivers) {
8083        ActivityInfo targetReceiver = null;
8084
8085        final int NR = receivers.size();
8086        for (int i = 0; i < NR; i++) {
8087            final ResolveInfo info = receivers.get(i);
8088            if (info.activityInfo == null) {
8089                continue;
8090            }
8091
8092            if (packageName.equals(info.activityInfo.packageName)) {
8093                targetReceiver = info.activityInfo;
8094                break;
8095            }
8096        }
8097
8098        if (targetReceiver == null) {
8099            return null;
8100        }
8101
8102        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8103    }
8104
8105    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8106            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8107        if (pkgInfo.verifiers.length == 0) {
8108            return null;
8109        }
8110
8111        final int N = pkgInfo.verifiers.length;
8112        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8113        for (int i = 0; i < N; i++) {
8114            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8115
8116            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8117                    receivers);
8118            if (comp == null) {
8119                continue;
8120            }
8121
8122            final int verifierUid = getUidForVerifier(verifierInfo);
8123            if (verifierUid == -1) {
8124                continue;
8125            }
8126
8127            if (DEBUG_VERIFY) {
8128                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8129                        + " with the correct signature");
8130            }
8131            sufficientVerifiers.add(comp);
8132            verificationState.addSufficientVerifier(verifierUid);
8133        }
8134
8135        return sufficientVerifiers;
8136    }
8137
8138    private int getUidForVerifier(VerifierInfo verifierInfo) {
8139        synchronized (mPackages) {
8140            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8141            if (pkg == null) {
8142                return -1;
8143            } else if (pkg.mSignatures.length != 1) {
8144                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8145                        + " has more than one signature; ignoring");
8146                return -1;
8147            }
8148
8149            /*
8150             * If the public key of the package's signature does not match
8151             * our expected public key, then this is a different package and
8152             * we should skip.
8153             */
8154
8155            final byte[] expectedPublicKey;
8156            try {
8157                final Signature verifierSig = pkg.mSignatures[0];
8158                final PublicKey publicKey = verifierSig.getPublicKey();
8159                expectedPublicKey = publicKey.getEncoded();
8160            } catch (CertificateException e) {
8161                return -1;
8162            }
8163
8164            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8165
8166            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8167                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8168                        + " does not have the expected public key; ignoring");
8169                return -1;
8170            }
8171
8172            return pkg.applicationInfo.uid;
8173        }
8174    }
8175
8176    @Override
8177    public void finishPackageInstall(int token) {
8178        enforceSystemOrRoot("Only the system is allowed to finish installs");
8179
8180        if (DEBUG_INSTALL) {
8181            Slog.v(TAG, "BM finishing package install for " + token);
8182        }
8183
8184        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8185        mHandler.sendMessage(msg);
8186    }
8187
8188    /**
8189     * Get the verification agent timeout.
8190     *
8191     * @return verification timeout in milliseconds
8192     */
8193    private long getVerificationTimeout() {
8194        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8195                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8196                DEFAULT_VERIFICATION_TIMEOUT);
8197    }
8198
8199    /**
8200     * Get the default verification agent response code.
8201     *
8202     * @return default verification response code
8203     */
8204    private int getDefaultVerificationResponse() {
8205        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8206                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8207                DEFAULT_VERIFICATION_RESPONSE);
8208    }
8209
8210    /**
8211     * Check whether or not package verification has been enabled.
8212     *
8213     * @return true if verification should be performed
8214     */
8215    private boolean isVerificationEnabled(int userId, int flags) {
8216        if (!DEFAULT_VERIFY_ENABLE) {
8217            return false;
8218        }
8219
8220        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8221
8222        // Check if installing from ADB
8223        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8224            // Do not run verification in a test harness environment
8225            if (ActivityManager.isRunningInTestHarness()) {
8226                return false;
8227            }
8228            if (ensureVerifyAppsEnabled) {
8229                return true;
8230            }
8231            // Check if the developer does not want package verification for ADB installs
8232            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8233                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8234                return false;
8235            }
8236        }
8237
8238        if (ensureVerifyAppsEnabled) {
8239            return true;
8240        }
8241
8242        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8243                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8244    }
8245
8246    /**
8247     * Get the "allow unknown sources" setting.
8248     *
8249     * @return the current "allow unknown sources" setting
8250     */
8251    private int getUnknownSourcesSettings() {
8252        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8253                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8254                -1);
8255    }
8256
8257    @Override
8258    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8259        final int uid = Binder.getCallingUid();
8260        // writer
8261        synchronized (mPackages) {
8262            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8263            if (targetPackageSetting == null) {
8264                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8265            }
8266
8267            PackageSetting installerPackageSetting;
8268            if (installerPackageName != null) {
8269                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8270                if (installerPackageSetting == null) {
8271                    throw new IllegalArgumentException("Unknown installer package: "
8272                            + installerPackageName);
8273                }
8274            } else {
8275                installerPackageSetting = null;
8276            }
8277
8278            Signature[] callerSignature;
8279            Object obj = mSettings.getUserIdLPr(uid);
8280            if (obj != null) {
8281                if (obj instanceof SharedUserSetting) {
8282                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8283                } else if (obj instanceof PackageSetting) {
8284                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8285                } else {
8286                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8287                }
8288            } else {
8289                throw new SecurityException("Unknown calling uid " + uid);
8290            }
8291
8292            // Verify: can't set installerPackageName to a package that is
8293            // not signed with the same cert as the caller.
8294            if (installerPackageSetting != null) {
8295                if (compareSignatures(callerSignature,
8296                        installerPackageSetting.signatures.mSignatures)
8297                        != PackageManager.SIGNATURE_MATCH) {
8298                    throw new SecurityException(
8299                            "Caller does not have same cert as new installer package "
8300                            + installerPackageName);
8301                }
8302            }
8303
8304            // Verify: if target already has an installer package, it must
8305            // be signed with the same cert as the caller.
8306            if (targetPackageSetting.installerPackageName != null) {
8307                PackageSetting setting = mSettings.mPackages.get(
8308                        targetPackageSetting.installerPackageName);
8309                // If the currently set package isn't valid, then it's always
8310                // okay to change it.
8311                if (setting != null) {
8312                    if (compareSignatures(callerSignature,
8313                            setting.signatures.mSignatures)
8314                            != PackageManager.SIGNATURE_MATCH) {
8315                        throw new SecurityException(
8316                                "Caller does not have same cert as old installer package "
8317                                + targetPackageSetting.installerPackageName);
8318                    }
8319                }
8320            }
8321
8322            // Okay!
8323            targetPackageSetting.installerPackageName = installerPackageName;
8324            scheduleWriteSettingsLocked();
8325        }
8326    }
8327
8328    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8329        // Queue up an async operation since the package installation may take a little while.
8330        mHandler.post(new Runnable() {
8331            public void run() {
8332                mHandler.removeCallbacks(this);
8333                 // Result object to be returned
8334                PackageInstalledInfo res = new PackageInstalledInfo();
8335                res.returnCode = currentStatus;
8336                res.uid = -1;
8337                res.pkg = null;
8338                res.removedInfo = new PackageRemovedInfo();
8339                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8340                    args.doPreInstall(res.returnCode);
8341                    synchronized (mInstallLock) {
8342                        installPackageLI(args, true, res);
8343                    }
8344                    args.doPostInstall(res.returnCode, res.uid);
8345                }
8346
8347                // A restore should be performed at this point if (a) the install
8348                // succeeded, (b) the operation is not an update, and (c) the new
8349                // package has not opted out of backup participation.
8350                final boolean update = res.removedInfo.removedPackage != null;
8351                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8352                boolean doRestore = !update
8353                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8354
8355                // Set up the post-install work request bookkeeping.  This will be used
8356                // and cleaned up by the post-install event handling regardless of whether
8357                // there's a restore pass performed.  Token values are >= 1.
8358                int token;
8359                if (mNextInstallToken < 0) mNextInstallToken = 1;
8360                token = mNextInstallToken++;
8361
8362                PostInstallData data = new PostInstallData(args, res);
8363                mRunningInstalls.put(token, data);
8364                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8365
8366                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8367                    // Pass responsibility to the Backup Manager.  It will perform a
8368                    // restore if appropriate, then pass responsibility back to the
8369                    // Package Manager to run the post-install observer callbacks
8370                    // and broadcasts.
8371                    IBackupManager bm = IBackupManager.Stub.asInterface(
8372                            ServiceManager.getService(Context.BACKUP_SERVICE));
8373                    if (bm != null) {
8374                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8375                                + " to BM for possible restore");
8376                        try {
8377                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8378                        } catch (RemoteException e) {
8379                            // can't happen; the backup manager is local
8380                        } catch (Exception e) {
8381                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8382                            doRestore = false;
8383                        }
8384                    } else {
8385                        Slog.e(TAG, "Backup Manager not found!");
8386                        doRestore = false;
8387                    }
8388                }
8389
8390                if (!doRestore) {
8391                    // No restore possible, or the Backup Manager was mysteriously not
8392                    // available -- just fire the post-install work request directly.
8393                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8394                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8395                    mHandler.sendMessage(msg);
8396                }
8397            }
8398        });
8399    }
8400
8401    private abstract class HandlerParams {
8402        private static final int MAX_RETRIES = 4;
8403
8404        /**
8405         * Number of times startCopy() has been attempted and had a non-fatal
8406         * error.
8407         */
8408        private int mRetries = 0;
8409
8410        /** User handle for the user requesting the information or installation. */
8411        private final UserHandle mUser;
8412
8413        HandlerParams(UserHandle user) {
8414            mUser = user;
8415        }
8416
8417        UserHandle getUser() {
8418            return mUser;
8419        }
8420
8421        final boolean startCopy() {
8422            boolean res;
8423            try {
8424                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8425
8426                if (++mRetries > MAX_RETRIES) {
8427                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8428                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8429                    handleServiceError();
8430                    return false;
8431                } else {
8432                    handleStartCopy();
8433                    res = true;
8434                }
8435            } catch (RemoteException e) {
8436                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8437                mHandler.sendEmptyMessage(MCS_RECONNECT);
8438                res = false;
8439            }
8440            handleReturnCode();
8441            return res;
8442        }
8443
8444        final void serviceError() {
8445            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8446            handleServiceError();
8447            handleReturnCode();
8448        }
8449
8450        abstract void handleStartCopy() throws RemoteException;
8451        abstract void handleServiceError();
8452        abstract void handleReturnCode();
8453    }
8454
8455    class MeasureParams extends HandlerParams {
8456        private final PackageStats mStats;
8457        private boolean mSuccess;
8458
8459        private final IPackageStatsObserver mObserver;
8460
8461        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8462            super(new UserHandle(stats.userHandle));
8463            mObserver = observer;
8464            mStats = stats;
8465        }
8466
8467        @Override
8468        public String toString() {
8469            return "MeasureParams{"
8470                + Integer.toHexString(System.identityHashCode(this))
8471                + " " + mStats.packageName + "}";
8472        }
8473
8474        @Override
8475        void handleStartCopy() throws RemoteException {
8476            synchronized (mInstallLock) {
8477                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8478            }
8479
8480            if (mSuccess) {
8481                final boolean mounted;
8482                if (Environment.isExternalStorageEmulated()) {
8483                    mounted = true;
8484                } else {
8485                    final String status = Environment.getExternalStorageState();
8486                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8487                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8488                }
8489
8490                if (mounted) {
8491                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8492
8493                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8494                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8495
8496                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8497                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8498
8499                    // Always subtract cache size, since it's a subdirectory
8500                    mStats.externalDataSize -= mStats.externalCacheSize;
8501
8502                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8503                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8504
8505                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8506                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8507                }
8508            }
8509        }
8510
8511        @Override
8512        void handleReturnCode() {
8513            if (mObserver != null) {
8514                try {
8515                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8516                } catch (RemoteException e) {
8517                    Slog.i(TAG, "Observer no longer exists.");
8518                }
8519            }
8520        }
8521
8522        @Override
8523        void handleServiceError() {
8524            Slog.e(TAG, "Could not measure application " + mStats.packageName
8525                            + " external storage");
8526        }
8527    }
8528
8529    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8530            throws RemoteException {
8531        long result = 0;
8532        for (File path : paths) {
8533            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8534        }
8535        return result;
8536    }
8537
8538    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8539        for (File path : paths) {
8540            try {
8541                mcs.clearDirectory(path.getAbsolutePath());
8542            } catch (RemoteException e) {
8543            }
8544        }
8545    }
8546
8547    class InstallParams extends HandlerParams {
8548        /**
8549         * Location where install is coming from, before it has been
8550         * copied/renamed into place. This could be a single monolithic APK
8551         * file, or a cluster directory. This location may be untrusted.
8552         */
8553        final File originFile;
8554
8555        /**
8556         * Flag indicating that {@link #originFile} has already been staged,
8557         * meaning downstream users don't need to defensively copy the contents.
8558         */
8559        boolean originStaged;
8560
8561        final IPackageInstallObserver2 observer;
8562        int flags;
8563        final String installerPackageName;
8564        final VerificationParams verificationParams;
8565        private InstallArgs mArgs;
8566        private int mRet;
8567        final String packageAbiOverride;
8568        boolean multiArch;
8569
8570        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8571                int flags, String installerPackageName, VerificationParams verificationParams,
8572                UserHandle user, String packageAbiOverride) {
8573            super(user);
8574            this.originFile = Preconditions.checkNotNull(originFile);
8575            this.originStaged = originStaged;
8576            this.observer = observer;
8577            this.flags = flags;
8578            this.installerPackageName = installerPackageName;
8579            this.verificationParams = verificationParams;
8580            this.packageAbiOverride = packageAbiOverride;
8581        }
8582
8583        @Override
8584        public String toString() {
8585            return "InstallParams{"
8586                + Integer.toHexString(System.identityHashCode(this))
8587                + " " + originFile + "}";
8588        }
8589
8590        public ManifestDigest getManifestDigest() {
8591            if (verificationParams == null) {
8592                return null;
8593            }
8594            return verificationParams.getManifestDigest();
8595        }
8596
8597        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8598            String packageName = pkgLite.packageName;
8599            int installLocation = pkgLite.installLocation;
8600            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8601            // reader
8602            synchronized (mPackages) {
8603                PackageParser.Package pkg = mPackages.get(packageName);
8604                if (pkg != null) {
8605                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8606                        // Check for downgrading.
8607                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8608                            if (pkgLite.versionCode < pkg.mVersionCode) {
8609                                Slog.w(TAG, "Can't install update of " + packageName
8610                                        + " update version " + pkgLite.versionCode
8611                                        + " is older than installed version "
8612                                        + pkg.mVersionCode);
8613                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8614                            }
8615                        }
8616                        // Check for updated system application.
8617                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8618                            if (onSd) {
8619                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8620                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8621                            }
8622                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8623                        } else {
8624                            if (onSd) {
8625                                // Install flag overrides everything.
8626                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8627                            }
8628                            // If current upgrade specifies particular preference
8629                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8630                                // Application explicitly specified internal.
8631                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8632                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8633                                // App explictly prefers external. Let policy decide
8634                            } else {
8635                                // Prefer previous location
8636                                if (isExternal(pkg)) {
8637                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8638                                }
8639                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8640                            }
8641                        }
8642                    } else {
8643                        // Invalid install. Return error code
8644                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8645                    }
8646                }
8647            }
8648            // All the special cases have been taken care of.
8649            // Return result based on recommended install location.
8650            if (onSd) {
8651                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8652            }
8653            return pkgLite.recommendedInstallLocation;
8654        }
8655
8656        private long getMemoryLowThreshold() {
8657            final DeviceStorageMonitorInternal
8658                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8659            if (dsm == null) {
8660                return 0L;
8661            }
8662            return dsm.getMemoryLowThreshold();
8663        }
8664
8665        /*
8666         * Invoke remote method to get package information and install
8667         * location values. Override install location based on default
8668         * policy if needed and then create install arguments based
8669         * on the install location.
8670         */
8671        public void handleStartCopy() throws RemoteException {
8672            int ret = PackageManager.INSTALL_SUCCEEDED;
8673            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8674            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8675            PackageInfoLite pkgLite = null;
8676
8677            if (onInt && onSd) {
8678                // Check if both bits are set.
8679                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8680                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8681            } else {
8682                final long lowThreshold = getMemoryLowThreshold();
8683                if (lowThreshold == 0L) {
8684                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8685                }
8686
8687                // Remote call to find out default install location
8688                final String originPath = originFile.getAbsolutePath();
8689                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8690                        packageAbiOverride);
8691                // Keep track of whether this package is a multiArch package until
8692                // we perform a full scan of it. We need to do this because we might
8693                // end up extracting the package shared libraries before we perform
8694                // a full scan.
8695                multiArch = pkgLite.multiArch;
8696
8697                /*
8698                 * If we have too little free space, try to free cache
8699                 * before giving up.
8700                 */
8701                if (pkgLite.recommendedInstallLocation
8702                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8703                    final long size = mContainerService.calculateInstalledSize(
8704                            originPath, isForwardLocked(), packageAbiOverride);
8705                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8706                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8707                                lowThreshold, packageAbiOverride);
8708                    }
8709                    /*
8710                     * The cache free must have deleted the file we
8711                     * downloaded to install.
8712                     *
8713                     * TODO: fix the "freeCache" call to not delete
8714                     *       the file we care about.
8715                     */
8716                    if (pkgLite.recommendedInstallLocation
8717                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8718                        pkgLite.recommendedInstallLocation
8719                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8720                    }
8721                }
8722            }
8723
8724            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8725                int loc = pkgLite.recommendedInstallLocation;
8726                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8727                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8728                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8729                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8730                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8731                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8732                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8733                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8734                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8735                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8736                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8737                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8738                } else {
8739                    // Override with defaults if needed.
8740                    loc = installLocationPolicy(pkgLite, flags);
8741                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8742                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8743                    } else if (!onSd && !onInt) {
8744                        // Override install location with flags
8745                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8746                            // Set the flag to install on external media.
8747                            flags |= PackageManager.INSTALL_EXTERNAL;
8748                            flags &= ~PackageManager.INSTALL_INTERNAL;
8749                        } else {
8750                            // Make sure the flag for installing on external
8751                            // media is unset
8752                            flags |= PackageManager.INSTALL_INTERNAL;
8753                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8754                        }
8755                    }
8756                }
8757            }
8758
8759            final InstallArgs args = createInstallArgs(this);
8760            mArgs = args;
8761
8762            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8763                 /*
8764                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8765                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8766                 */
8767                int userIdentifier = getUser().getIdentifier();
8768                if (userIdentifier == UserHandle.USER_ALL
8769                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8770                    userIdentifier = UserHandle.USER_OWNER;
8771                }
8772
8773                /*
8774                 * Determine if we have any installed package verifiers. If we
8775                 * do, then we'll defer to them to verify the packages.
8776                 */
8777                final int requiredUid = mRequiredVerifierPackage == null ? -1
8778                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8779                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8780                    // TODO: send verifier the install session instead of uri
8781                    final Intent verification = new Intent(
8782                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8783                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8784                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8785
8786                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8787                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8788                            0 /* TODO: Which userId? */);
8789
8790                    if (DEBUG_VERIFY) {
8791                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8792                                + verification.toString() + " with " + pkgLite.verifiers.length
8793                                + " optional verifiers");
8794                    }
8795
8796                    final int verificationId = mPendingVerificationToken++;
8797
8798                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8799
8800                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8801                            installerPackageName);
8802
8803                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8804
8805                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8806                            pkgLite.packageName);
8807
8808                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8809                            pkgLite.versionCode);
8810
8811                    if (verificationParams != null) {
8812                        if (verificationParams.getVerificationURI() != null) {
8813                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8814                                 verificationParams.getVerificationURI());
8815                        }
8816                        if (verificationParams.getOriginatingURI() != null) {
8817                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8818                                  verificationParams.getOriginatingURI());
8819                        }
8820                        if (verificationParams.getReferrer() != null) {
8821                            verification.putExtra(Intent.EXTRA_REFERRER,
8822                                  verificationParams.getReferrer());
8823                        }
8824                        if (verificationParams.getOriginatingUid() >= 0) {
8825                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8826                                  verificationParams.getOriginatingUid());
8827                        }
8828                        if (verificationParams.getInstallerUid() >= 0) {
8829                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8830                                  verificationParams.getInstallerUid());
8831                        }
8832                    }
8833
8834                    final PackageVerificationState verificationState = new PackageVerificationState(
8835                            requiredUid, args);
8836
8837                    mPendingVerification.append(verificationId, verificationState);
8838
8839                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8840                            receivers, verificationState);
8841
8842                    /*
8843                     * If any sufficient verifiers were listed in the package
8844                     * manifest, attempt to ask them.
8845                     */
8846                    if (sufficientVerifiers != null) {
8847                        final int N = sufficientVerifiers.size();
8848                        if (N == 0) {
8849                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8850                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8851                        } else {
8852                            for (int i = 0; i < N; i++) {
8853                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8854
8855                                final Intent sufficientIntent = new Intent(verification);
8856                                sufficientIntent.setComponent(verifierComponent);
8857
8858                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8859                            }
8860                        }
8861                    }
8862
8863                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8864                            mRequiredVerifierPackage, receivers);
8865                    if (ret == PackageManager.INSTALL_SUCCEEDED
8866                            && mRequiredVerifierPackage != null) {
8867                        /*
8868                         * Send the intent to the required verification agent,
8869                         * but only start the verification timeout after the
8870                         * target BroadcastReceivers have run.
8871                         */
8872                        verification.setComponent(requiredVerifierComponent);
8873                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8874                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8875                                new BroadcastReceiver() {
8876                                    @Override
8877                                    public void onReceive(Context context, Intent intent) {
8878                                        final Message msg = mHandler
8879                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8880                                        msg.arg1 = verificationId;
8881                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8882                                    }
8883                                }, null, 0, null, null);
8884
8885                        /*
8886                         * We don't want the copy to proceed until verification
8887                         * succeeds, so null out this field.
8888                         */
8889                        mArgs = null;
8890                    }
8891                } else {
8892                    /*
8893                     * No package verification is enabled, so immediately start
8894                     * the remote call to initiate copy using temporary file.
8895                     */
8896                    ret = args.copyApk(mContainerService, true);
8897                }
8898            }
8899
8900            mRet = ret;
8901        }
8902
8903        @Override
8904        void handleReturnCode() {
8905            // If mArgs is null, then MCS couldn't be reached. When it
8906            // reconnects, it will try again to install. At that point, this
8907            // will succeed.
8908            if (mArgs != null) {
8909                processPendingInstall(mArgs, mRet);
8910            }
8911        }
8912
8913        @Override
8914        void handleServiceError() {
8915            mArgs = createInstallArgs(this);
8916            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8917        }
8918
8919        public boolean isForwardLocked() {
8920            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8921        }
8922    }
8923
8924    /*
8925     * Utility class used in movePackage api.
8926     * srcArgs and targetArgs are not set for invalid flags and make
8927     * sure to do null checks when invoking methods on them.
8928     * We probably want to return ErrorPrams for both failed installs
8929     * and moves.
8930     */
8931    class MoveParams extends HandlerParams {
8932        final IPackageMoveObserver observer;
8933        final int flags;
8934        final String packageName;
8935        final InstallArgs srcArgs;
8936        final InstallArgs targetArgs;
8937        int uid;
8938        int mRet;
8939
8940        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8941                String packageName, String[] instructionSets, int uid, UserHandle user,
8942                boolean isMultiArch) {
8943            super(user);
8944            this.srcArgs = srcArgs;
8945            this.observer = observer;
8946            this.flags = flags;
8947            this.packageName = packageName;
8948            this.uid = uid;
8949            if (srcArgs != null) {
8950                final String codePath = srcArgs.getCodePath();
8951                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8952                        instructionSets, isMultiArch);
8953            } else {
8954                targetArgs = null;
8955            }
8956        }
8957
8958        @Override
8959        public String toString() {
8960            return "MoveParams{"
8961                + Integer.toHexString(System.identityHashCode(this))
8962                + " " + packageName + "}";
8963        }
8964
8965        public void handleStartCopy() throws RemoteException {
8966            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8967            // Check for storage space on target medium
8968            if (!targetArgs.checkFreeStorage(mContainerService)) {
8969                Log.w(TAG, "Insufficient storage to install");
8970                return;
8971            }
8972
8973            mRet = srcArgs.doPreCopy();
8974            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8975                return;
8976            }
8977
8978            mRet = targetArgs.copyApk(mContainerService, false);
8979            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8980                srcArgs.doPostCopy(uid);
8981                return;
8982            }
8983
8984            mRet = srcArgs.doPostCopy(uid);
8985            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8986                return;
8987            }
8988
8989            mRet = targetArgs.doPreInstall(mRet);
8990            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8991                return;
8992            }
8993
8994            if (DEBUG_SD_INSTALL) {
8995                StringBuilder builder = new StringBuilder();
8996                if (srcArgs != null) {
8997                    builder.append("src: ");
8998                    builder.append(srcArgs.getCodePath());
8999                }
9000                if (targetArgs != null) {
9001                    builder.append(" target : ");
9002                    builder.append(targetArgs.getCodePath());
9003                }
9004                Log.i(TAG, builder.toString());
9005            }
9006        }
9007
9008        @Override
9009        void handleReturnCode() {
9010            targetArgs.doPostInstall(mRet, uid);
9011            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9012            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9013                currentStatus = PackageManager.MOVE_SUCCEEDED;
9014            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9015                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9016            }
9017            processPendingMove(this, currentStatus);
9018        }
9019
9020        @Override
9021        void handleServiceError() {
9022            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9023        }
9024    }
9025
9026    /**
9027     * Used during creation of InstallArgs
9028     *
9029     * @param flags package installation flags
9030     * @return true if should be installed on external storage
9031     */
9032    private static boolean installOnSd(int flags) {
9033        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9034            return false;
9035        }
9036        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9037            return true;
9038        }
9039        return false;
9040    }
9041
9042    /**
9043     * Used during creation of InstallArgs
9044     *
9045     * @param flags package installation flags
9046     * @return true if should be installed as forward locked
9047     */
9048    private static boolean installForwardLocked(int flags) {
9049        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9050    }
9051
9052    private InstallArgs createInstallArgs(InstallParams params) {
9053        // TODO: extend to support incoming zero-copy locations
9054
9055        if (installOnSd(params.flags) || params.isForwardLocked()) {
9056            return new AsecInstallArgs(params);
9057        } else {
9058            return new FileInstallArgs(params);
9059        }
9060    }
9061
9062    /**
9063     * Create args that describe an existing installed package. Typically used
9064     * when cleaning up old installs, or used as a move source.
9065     */
9066    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9067            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9068            boolean isMultiArch) {
9069        final boolean isInAsec;
9070        if (installOnSd(flags)) {
9071            /* Apps on SD card are always in ASEC containers. */
9072            isInAsec = true;
9073        } else if (installForwardLocked(flags)
9074                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9075            /*
9076             * Forward-locked apps are only in ASEC containers if they're the
9077             * new style
9078             */
9079            isInAsec = true;
9080        } else {
9081            isInAsec = false;
9082        }
9083
9084        if (isInAsec) {
9085            return new AsecInstallArgs(codePath, instructionSets,
9086                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9087        } else {
9088            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9089                    instructionSets, isMultiArch);
9090        }
9091    }
9092
9093    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9094            String[] instructionSets, boolean isMultiArch) {
9095        final File codeFile = new File(codePath);
9096        if (installOnSd(flags) || installForwardLocked(flags)) {
9097            String cid = getNextCodePath(codePath, pkgName, "/"
9098                    + AsecInstallArgs.RES_FILE_NAME);
9099            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9100                    installForwardLocked(flags), isMultiArch);
9101        } else {
9102            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9103        }
9104    }
9105
9106    static abstract class InstallArgs {
9107        /** @see InstallParams#originFile */
9108        final File originFile;
9109        /** @see InstallParams#originStaged */
9110        final boolean originStaged;
9111
9112        // TODO: define inherit location
9113
9114        final IPackageInstallObserver2 observer;
9115        // Always refers to PackageManager flags only
9116        final int flags;
9117        final String installerPackageName;
9118        final ManifestDigest manifestDigest;
9119        final UserHandle user;
9120        final String abiOverride;
9121        final boolean multiArch;
9122
9123        // The list of instruction sets supported by this app. This is currently
9124        // only used during the rmdex() phase to clean up resources. We can get rid of this
9125        // if we move dex files under the common app path.
9126        /* nullable */ String[] instructionSets;
9127
9128        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9129                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9130                    UserHandle user, String[] instructionSets,
9131                    String abiOverride, boolean multiArch) {
9132            this.originFile = originFile;
9133            this.originStaged = originStaged;
9134            this.flags = flags;
9135            this.observer = observer;
9136            this.installerPackageName = installerPackageName;
9137            this.manifestDigest = manifestDigest;
9138            this.user = user;
9139            this.instructionSets = instructionSets;
9140            this.abiOverride = abiOverride;
9141            this.multiArch = multiArch;
9142        }
9143
9144        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9145        abstract int doPreInstall(int status);
9146
9147        /**
9148         * Rename package into final resting place. All paths on the given
9149         * scanned package should be updated to reflect the rename.
9150         */
9151        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9152        abstract int doPostInstall(int status, int uid);
9153
9154        /** @see PackageSettingBase#codePathString */
9155        abstract String getCodePath();
9156        /** @see PackageSettingBase#resourcePathString */
9157        abstract String getResourcePath();
9158        abstract String getLegacyNativeLibraryPath();
9159
9160        // Need installer lock especially for dex file removal.
9161        abstract void cleanUpResourcesLI();
9162        abstract boolean doPostDeleteLI(boolean delete);
9163        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9164
9165        /**
9166         * Called before the source arguments are copied. This is used mostly
9167         * for MoveParams when it needs to read the source file to put it in the
9168         * destination.
9169         */
9170        int doPreCopy() {
9171            return PackageManager.INSTALL_SUCCEEDED;
9172        }
9173
9174        /**
9175         * Called after the source arguments are copied. This is used mostly for
9176         * MoveParams when it needs to read the source file to put it in the
9177         * destination.
9178         *
9179         * @return
9180         */
9181        int doPostCopy(int uid) {
9182            return PackageManager.INSTALL_SUCCEEDED;
9183        }
9184
9185        protected boolean isFwdLocked() {
9186            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9187        }
9188
9189        UserHandle getUser() {
9190            return user;
9191        }
9192    }
9193
9194    /**
9195     * Logic to handle installation of non-ASEC applications, including copying
9196     * and renaming logic.
9197     */
9198    class FileInstallArgs extends InstallArgs {
9199        private File codeFile;
9200        private File resourceFile;
9201        private File legacyNativeLibraryPath;
9202
9203        // Example topology:
9204        // /data/app/com.example/base.apk
9205        // /data/app/com.example/split_foo.apk
9206        // /data/app/com.example/lib/arm/libfoo.so
9207        // /data/app/com.example/lib/arm64/libfoo.so
9208        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9209
9210        /** New install */
9211        FileInstallArgs(InstallParams params) {
9212            super(params.originFile, params.originStaged, params.observer, params.flags,
9213                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9214                    null /* instruction sets */, params.packageAbiOverride,
9215                    params.multiArch);
9216            if (isFwdLocked()) {
9217                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9218            }
9219        }
9220
9221        /** Existing install */
9222        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9223                String[] instructionSets, boolean isMultiArch) {
9224            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9225            this.codeFile = (codePath != null) ? new File(codePath) : null;
9226            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9227            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9228                    new File(legacyNativeLibraryPath) : null;
9229        }
9230
9231        /** New install from existing */
9232        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9233            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9234                    isMultiArch);
9235        }
9236
9237        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9238            final long lowThreshold;
9239
9240            final DeviceStorageMonitorInternal
9241                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9242            if (dsm == null) {
9243                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9244                lowThreshold = 0L;
9245            } else {
9246                if (dsm.isMemoryLow()) {
9247                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9248                    return false;
9249                }
9250
9251                lowThreshold = dsm.getMemoryLowThreshold();
9252            }
9253
9254            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9255                    lowThreshold);
9256        }
9257
9258        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9259            int ret = PackageManager.INSTALL_SUCCEEDED;
9260
9261            if (originStaged) {
9262                Slog.d(TAG, originFile + " already staged; skipping copy");
9263                codeFile = originFile;
9264                resourceFile = originFile;
9265            } else {
9266                try {
9267                    final File tempDir = mInstallerService.allocateSessionDir();
9268                    codeFile = tempDir;
9269                    resourceFile = tempDir;
9270                } catch (IOException e) {
9271                    Slog.w(TAG, "Failed to create copy file: " + e);
9272                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9273                }
9274
9275                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9276                    @Override
9277                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9278                        if (!FileUtils.isValidExtFilename(name)) {
9279                            throw new IllegalArgumentException("Invalid filename: " + name);
9280                        }
9281                        try {
9282                            final File file = new File(codeFile, name);
9283                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9284                                    O_RDWR | O_CREAT, 0644);
9285                            Os.chmod(file.getAbsolutePath(), 0644);
9286                            return new ParcelFileDescriptor(fd);
9287                        } catch (ErrnoException e) {
9288                            throw new RemoteException("Failed to open: " + e.getMessage());
9289                        }
9290                    }
9291                };
9292
9293                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9294                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9295                    Slog.e(TAG, "Failed to copy package");
9296                    return ret;
9297                }
9298            }
9299
9300            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9301            NativeLibraryHelper.Handle handle = null;
9302            try {
9303                handle = NativeLibraryHelper.Handle.create(codeFile);
9304                if (multiArch) {
9305                    // Warn if we've set an abiOverride for multi-lib packages..
9306                    // By definition, we need to copy both 32 and 64 bit libraries for
9307                    // such packages.
9308                    if (abiOverride != null &&  !CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9309                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9310                    }
9311
9312                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9313                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9314                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9315                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9316                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9317                    }
9318
9319                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9320                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9321                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9322                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9323                    }
9324                } else {
9325                    final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */);
9326                    String[] abiList = (cpuAbiOverride != null) ?
9327                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9328
9329                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9330                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9331                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9332                    }
9333
9334                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9335                            true /* use isa specific subdirs */);
9336                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9337                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9338                        return copyRet;
9339                    }
9340                }
9341            } catch (IOException e) {
9342                Slog.e(TAG, "Copying native libraries failed", e);
9343                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9344            } catch (PackageManagerException pme) {
9345                Slog.e(TAG, "Copying native libraries failed", pme);
9346                ret = pme.error;
9347            } finally {
9348                IoUtils.closeQuietly(handle);
9349            }
9350
9351            return ret;
9352        }
9353
9354        int doPreInstall(int status) {
9355            if (status != PackageManager.INSTALL_SUCCEEDED) {
9356                cleanUp();
9357            }
9358            return status;
9359        }
9360
9361        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9362            if (status != PackageManager.INSTALL_SUCCEEDED) {
9363                cleanUp();
9364                return false;
9365            } else {
9366                final File beforeCodeFile = codeFile;
9367                final File afterCodeFile = getNextCodePath(pkg.packageName);
9368
9369                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9370                try {
9371                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9372                } catch (ErrnoException e) {
9373                    Slog.d(TAG, "Failed to rename", e);
9374                    return false;
9375                }
9376
9377                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9378                    Slog.d(TAG, "Failed to restorecon");
9379                    return false;
9380                }
9381
9382                // Reflect the rename internally
9383                codeFile = afterCodeFile;
9384                resourceFile = afterCodeFile;
9385
9386                // Reflect the rename in scanned details
9387                pkg.codePath = afterCodeFile.getAbsolutePath();
9388                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9389                        pkg.baseCodePath);
9390                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9391                        pkg.splitCodePaths);
9392
9393                // Reflect the rename in app info
9394                pkg.applicationInfo.setCodePath(pkg.codePath);
9395                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9396                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9397                pkg.applicationInfo.setResourcePath(pkg.codePath);
9398                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9399                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9400
9401                return true;
9402            }
9403        }
9404
9405        int doPostInstall(int status, int uid) {
9406            if (status != PackageManager.INSTALL_SUCCEEDED) {
9407                cleanUp();
9408            }
9409            return status;
9410        }
9411
9412        @Override
9413        String getCodePath() {
9414            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9415        }
9416
9417        @Override
9418        String getResourcePath() {
9419            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9420        }
9421
9422        @Override
9423        String getLegacyNativeLibraryPath() {
9424            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9425        }
9426
9427        private boolean cleanUp() {
9428            if (codeFile == null || !codeFile.exists()) {
9429                return false;
9430            }
9431
9432            if (codeFile.isDirectory()) {
9433                FileUtils.deleteContents(codeFile);
9434            }
9435            codeFile.delete();
9436
9437            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9438                resourceFile.delete();
9439            }
9440
9441            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9442                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9443                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9444                }
9445                legacyNativeLibraryPath.delete();
9446            }
9447
9448            return true;
9449        }
9450
9451        void cleanUpResourcesLI() {
9452            // Try enumerating all code paths before deleting
9453            List<String> allCodePaths = Collections.EMPTY_LIST;
9454            if (codeFile != null && codeFile.exists()) {
9455                try {
9456                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9457                    allCodePaths = pkg.getAllCodePaths();
9458                } catch (PackageParserException e) {
9459                    // Ignored; we tried our best
9460                }
9461            }
9462
9463            cleanUp();
9464
9465            if (!allCodePaths.isEmpty()) {
9466                if (instructionSets == null) {
9467                    throw new IllegalStateException("instructionSet == null");
9468                }
9469                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9470                for (String codePath : allCodePaths) {
9471                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9472                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9473                        if (retCode < 0) {
9474                            Slog.w(TAG, "Couldn't remove dex file for package: "
9475                                    + " at location " + codePath + ", retcode=" + retCode);
9476                            // we don't consider this to be a failure of the core package deletion
9477                        }
9478                    }
9479                }
9480            }
9481        }
9482
9483        boolean doPostDeleteLI(boolean delete) {
9484            // XXX err, shouldn't we respect the delete flag?
9485            cleanUpResourcesLI();
9486            return true;
9487        }
9488    }
9489
9490    private boolean isAsecExternal(String cid) {
9491        final String asecPath = PackageHelper.getSdFilesystem(cid);
9492        return !asecPath.startsWith(mAsecInternalPath);
9493    }
9494
9495    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9496            PackageManagerException {
9497        if (copyRet < 0) {
9498            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9499                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9500                throw new PackageManagerException(copyRet, message);
9501            }
9502        }
9503    }
9504
9505    /**
9506     * Extract the MountService "container ID" from the full code path of an
9507     * .apk.
9508     */
9509    static String cidFromCodePath(String fullCodePath) {
9510        int eidx = fullCodePath.lastIndexOf("/");
9511        String subStr1 = fullCodePath.substring(0, eidx);
9512        int sidx = subStr1.lastIndexOf("/");
9513        return subStr1.substring(sidx+1, eidx);
9514    }
9515
9516    /**
9517     * Logic to handle installation of ASEC applications, including copying and
9518     * renaming logic.
9519     */
9520    class AsecInstallArgs extends InstallArgs {
9521        // TODO: teach about handling cluster directories
9522
9523        static final String RES_FILE_NAME = "pkg.apk";
9524        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9525
9526        String cid;
9527        String packagePath;
9528        String resourcePath;
9529        String legacyNativeLibraryDir;
9530
9531        /** New install */
9532        AsecInstallArgs(InstallParams params) {
9533            super(params.originFile, params.originStaged, params.observer, params.flags,
9534                    params.installerPackageName, params.getManifestDigest(),
9535                    params.getUser(), null /* instruction sets */,
9536                    params.packageAbiOverride, params.multiArch);
9537        }
9538
9539        /** Existing install */
9540        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9541                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9542            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9543                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9544                    instructionSets, null, isMultiArch);
9545            // Extract cid from fullCodePath
9546            int eidx = fullCodePath.lastIndexOf("/");
9547            String subStr1 = fullCodePath.substring(0, eidx);
9548            int sidx = subStr1.lastIndexOf("/");
9549            cid = subStr1.substring(sidx+1, eidx);
9550            setCachePath(subStr1);
9551        }
9552
9553        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9554                        boolean isMultiArch) {
9555            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9556                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9557                    instructionSets, null, isMultiArch);
9558            this.cid = cid;
9559            setCachePath(PackageHelper.getSdDir(cid));
9560        }
9561
9562        /** New install from existing */
9563        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9564                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9565            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9566                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9567                    instructionSets, null, isMultiArch);
9568            this.cid = cid;
9569        }
9570
9571        void createCopyFile() {
9572            cid = getTempContainerId();
9573        }
9574
9575        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9576            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9577                    abiOverride);
9578        }
9579
9580        private final boolean isExternal() {
9581            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9582        }
9583
9584        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9585            if (temp) {
9586                createCopyFile();
9587            } else {
9588                /*
9589                 * Pre-emptively destroy the container since it's destroyed if
9590                 * copying fails due to it existing anyway.
9591                 */
9592                PackageHelper.destroySdDir(cid);
9593            }
9594
9595            final String newCachePath = imcs.copyPackageToContainer(
9596                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9597                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9598
9599            if (newCachePath != null) {
9600                setCachePath(newCachePath);
9601                return PackageManager.INSTALL_SUCCEEDED;
9602            } else {
9603                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9604            }
9605        }
9606
9607        @Override
9608        String getCodePath() {
9609            return packagePath;
9610        }
9611
9612        @Override
9613        String getResourcePath() {
9614            return resourcePath;
9615        }
9616
9617        @Override
9618        String getLegacyNativeLibraryPath() {
9619            return legacyNativeLibraryDir;
9620        }
9621
9622        int doPreInstall(int status) {
9623            if (status != PackageManager.INSTALL_SUCCEEDED) {
9624                // Destroy container
9625                PackageHelper.destroySdDir(cid);
9626            } else {
9627                boolean mounted = PackageHelper.isContainerMounted(cid);
9628                if (!mounted) {
9629                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9630                            Process.SYSTEM_UID);
9631                    if (newCachePath != null) {
9632                        setCachePath(newCachePath);
9633                    } else {
9634                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9635                    }
9636                }
9637            }
9638            return status;
9639        }
9640
9641        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9642            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9643            String newCachePath = null;
9644            if (PackageHelper.isContainerMounted(cid)) {
9645                // Unmount the container
9646                if (!PackageHelper.unMountSdDir(cid)) {
9647                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9648                    return false;
9649                }
9650            }
9651            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9652                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9653                        " which might be stale. Will try to clean up.");
9654                // Clean up the stale container and proceed to recreate.
9655                if (!PackageHelper.destroySdDir(newCacheId)) {
9656                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9657                    return false;
9658                }
9659                // Successfully cleaned up stale container. Try to rename again.
9660                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9661                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9662                            + " inspite of cleaning it up.");
9663                    return false;
9664                }
9665            }
9666            if (!PackageHelper.isContainerMounted(newCacheId)) {
9667                Slog.w(TAG, "Mounting container " + newCacheId);
9668                newCachePath = PackageHelper.mountSdDir(newCacheId,
9669                        getEncryptKey(), Process.SYSTEM_UID);
9670            } else {
9671                newCachePath = PackageHelper.getSdDir(newCacheId);
9672            }
9673            if (newCachePath == null) {
9674                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9675                return false;
9676            }
9677            Log.i(TAG, "Succesfully renamed " + cid +
9678                    " to " + newCacheId +
9679                    " at new path: " + newCachePath);
9680            cid = newCacheId;
9681            setCachePath(newCachePath);
9682
9683            // TODO: extend to support split APKs
9684            pkg.codePath = getCodePath();
9685            pkg.baseCodePath = getCodePath();
9686            pkg.splitCodePaths = null;
9687
9688            pkg.applicationInfo.setCodePath(getCodePath());
9689            pkg.applicationInfo.setBaseCodePath(getCodePath());
9690            pkg.applicationInfo.setSplitCodePaths(null);
9691            pkg.applicationInfo.setResourcePath(getResourcePath());
9692            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9693            pkg.applicationInfo.setSplitResourcePaths(null);
9694
9695            return true;
9696        }
9697
9698        private void setCachePath(String newCachePath) {
9699            File cachePath = new File(newCachePath);
9700            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9701            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9702
9703            if (isFwdLocked()) {
9704                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9705            } else {
9706                resourcePath = packagePath;
9707            }
9708        }
9709
9710        int doPostInstall(int status, int uid) {
9711            if (status != PackageManager.INSTALL_SUCCEEDED) {
9712                cleanUp();
9713            } else {
9714                final int groupOwner;
9715                final String protectedFile;
9716                if (isFwdLocked()) {
9717                    groupOwner = UserHandle.getSharedAppGid(uid);
9718                    protectedFile = RES_FILE_NAME;
9719                } else {
9720                    groupOwner = -1;
9721                    protectedFile = null;
9722                }
9723
9724                if (uid < Process.FIRST_APPLICATION_UID
9725                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9726                    Slog.e(TAG, "Failed to finalize " + cid);
9727                    PackageHelper.destroySdDir(cid);
9728                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9729                }
9730
9731                boolean mounted = PackageHelper.isContainerMounted(cid);
9732                if (!mounted) {
9733                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9734                }
9735            }
9736            return status;
9737        }
9738
9739        private void cleanUp() {
9740            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9741
9742            // Destroy secure container
9743            PackageHelper.destroySdDir(cid);
9744        }
9745
9746        void cleanUpResourcesLI() {
9747            String sourceFile = getCodePath();
9748            // Remove dex file
9749            if (instructionSets == null) {
9750                throw new IllegalStateException("instructionSet == null");
9751            }
9752            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9753            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9754                int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet);
9755                if (retCode < 0) {
9756                    Slog.w(TAG, "Couldn't remove dex file for package: "
9757                            + " at location "
9758                            + sourceFile.toString() + ", retcode=" + retCode);
9759                    // we don't consider this to be a failure of the core package deletion
9760                }
9761            }
9762            cleanUp();
9763        }
9764
9765        boolean matchContainer(String app) {
9766            if (cid.startsWith(app)) {
9767                return true;
9768            }
9769            return false;
9770        }
9771
9772        String getPackageName() {
9773            return getAsecPackageName(cid);
9774        }
9775
9776        boolean doPostDeleteLI(boolean delete) {
9777            boolean ret = false;
9778            boolean mounted = PackageHelper.isContainerMounted(cid);
9779            if (mounted) {
9780                // Unmount first
9781                ret = PackageHelper.unMountSdDir(cid);
9782            }
9783            if (ret && delete) {
9784                cleanUpResourcesLI();
9785            }
9786            return ret;
9787        }
9788
9789        @Override
9790        int doPreCopy() {
9791            if (isFwdLocked()) {
9792                if (!PackageHelper.fixSdPermissions(cid,
9793                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9794                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9795                }
9796            }
9797
9798            return PackageManager.INSTALL_SUCCEEDED;
9799        }
9800
9801        @Override
9802        int doPostCopy(int uid) {
9803            if (isFwdLocked()) {
9804                if (uid < Process.FIRST_APPLICATION_UID
9805                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9806                                RES_FILE_NAME)) {
9807                    Slog.e(TAG, "Failed to finalize " + cid);
9808                    PackageHelper.destroySdDir(cid);
9809                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9810                }
9811            }
9812
9813            return PackageManager.INSTALL_SUCCEEDED;
9814        }
9815    }
9816
9817    static String getAsecPackageName(String packageCid) {
9818        int idx = packageCid.lastIndexOf("-");
9819        if (idx == -1) {
9820            return packageCid;
9821        }
9822        return packageCid.substring(0, idx);
9823    }
9824
9825    // Utility method used to create code paths based on package name and available index.
9826    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9827        String idxStr = "";
9828        int idx = 1;
9829        // Fall back to default value of idx=1 if prefix is not
9830        // part of oldCodePath
9831        if (oldCodePath != null) {
9832            String subStr = oldCodePath;
9833            // Drop the suffix right away
9834            if (suffix != null && subStr.endsWith(suffix)) {
9835                subStr = subStr.substring(0, subStr.length() - suffix.length());
9836            }
9837            // If oldCodePath already contains prefix find out the
9838            // ending index to either increment or decrement.
9839            int sidx = subStr.lastIndexOf(prefix);
9840            if (sidx != -1) {
9841                subStr = subStr.substring(sidx + prefix.length());
9842                if (subStr != null) {
9843                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9844                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9845                    }
9846                    try {
9847                        idx = Integer.parseInt(subStr);
9848                        if (idx <= 1) {
9849                            idx++;
9850                        } else {
9851                            idx--;
9852                        }
9853                    } catch(NumberFormatException e) {
9854                    }
9855                }
9856            }
9857        }
9858        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9859        return prefix + idxStr;
9860    }
9861
9862    private File getNextCodePath(String packageName) {
9863        int suffix = 1;
9864        File result;
9865        do {
9866            result = new File(mAppInstallDir, packageName + "-" + suffix);
9867            suffix++;
9868        } while (result.exists());
9869        return result;
9870    }
9871
9872    // Utility method used to ignore ADD/REMOVE events
9873    // by directory observer.
9874    private static boolean ignoreCodePath(String fullPathStr) {
9875        String apkName = deriveCodePathName(fullPathStr);
9876        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9877        if (idx != -1 && ((idx+1) < apkName.length())) {
9878            // Make sure the package ends with a numeral
9879            String version = apkName.substring(idx+1);
9880            try {
9881                Integer.parseInt(version);
9882                return true;
9883            } catch (NumberFormatException e) {}
9884        }
9885        return false;
9886    }
9887
9888    // Utility method that returns the relative package path with respect
9889    // to the installation directory. Like say for /data/data/com.test-1.apk
9890    // string com.test-1 is returned.
9891    static String deriveCodePathName(String codePath) {
9892        if (codePath == null) {
9893            return null;
9894        }
9895        final File codeFile = new File(codePath);
9896        final String name = codeFile.getName();
9897        if (codeFile.isDirectory()) {
9898            return name;
9899        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9900            final int lastDot = name.lastIndexOf('.');
9901            return name.substring(0, lastDot);
9902        } else {
9903            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9904            return null;
9905        }
9906    }
9907
9908    class PackageInstalledInfo {
9909        String name;
9910        int uid;
9911        // The set of users that originally had this package installed.
9912        int[] origUsers;
9913        // The set of users that now have this package installed.
9914        int[] newUsers;
9915        PackageParser.Package pkg;
9916        int returnCode;
9917        String returnMsg;
9918        PackageRemovedInfo removedInfo;
9919
9920        public void setError(int code, String msg) {
9921            returnCode = code;
9922            returnMsg = msg;
9923            Slog.w(TAG, msg);
9924        }
9925
9926        public void setError(String msg, PackageParserException e) {
9927            returnCode = e.error;
9928            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9929            Slog.w(TAG, msg, e);
9930        }
9931
9932        public void setError(String msg, PackageManagerException e) {
9933            returnCode = e.error;
9934            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9935            Slog.w(TAG, msg, e);
9936        }
9937
9938        // In some error cases we want to convey more info back to the observer
9939        String origPackage;
9940        String origPermission;
9941    }
9942
9943    /*
9944     * Install a non-existing package.
9945     */
9946    private void installNewPackageLI(PackageParser.Package pkg,
9947            int parseFlags, int scanMode, UserHandle user,
9948            String installerPackageName, PackageInstalledInfo res) {
9949        // Remember this for later, in case we need to rollback this install
9950        String pkgName = pkg.packageName;
9951
9952        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9953        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9954        synchronized(mPackages) {
9955            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9956                // A package with the same name is already installed, though
9957                // it has been renamed to an older name.  The package we
9958                // are trying to install should be installed as an update to
9959                // the existing one, but that has not been requested, so bail.
9960                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9961                        + " without first uninstalling package running as "
9962                        + mSettings.mRenamedPackages.get(pkgName));
9963                return;
9964            }
9965            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9966                // Don't allow installation over an existing package with the same name.
9967                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9968                        + " without first uninstalling.");
9969                return;
9970            }
9971        }
9972
9973        try {
9974            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9975                    System.currentTimeMillis(), user);
9976
9977            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9978            // delete the partially installed application. the data directory will have to be
9979            // restored if it was already existing
9980            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9981                // remove package from internal structures.  Note that we want deletePackageX to
9982                // delete the package data and cache directories that it created in
9983                // scanPackageLocked, unless those directories existed before we even tried to
9984                // install.
9985                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9986                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9987                                res.removedInfo, true);
9988            }
9989
9990        } catch (PackageManagerException e) {
9991            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9992        }
9993    }
9994
9995    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9996        // Upgrade keysets are being used.  Determine if new package has a superset of the
9997        // required keys.
9998        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9999        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10000        for (int i = 0; i < upgradeKeySets.length; i++) {
10001            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10002            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10003                return true;
10004            }
10005        }
10006        return false;
10007    }
10008
10009    private void replacePackageLI(PackageParser.Package pkg,
10010            int parseFlags, int scanMode, UserHandle user,
10011            String installerPackageName, PackageInstalledInfo res) {
10012        PackageParser.Package oldPackage;
10013        String pkgName = pkg.packageName;
10014        int[] allUsers;
10015        boolean[] perUserInstalled;
10016
10017        // First find the old package info and check signatures
10018        synchronized(mPackages) {
10019            oldPackage = mPackages.get(pkgName);
10020            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10021            PackageSetting ps = mSettings.mPackages.get(pkgName);
10022            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10023                // default to original signature matching
10024                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10025                    != PackageManager.SIGNATURE_MATCH) {
10026                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10027                            "New package has a different signature: " + pkgName);
10028                    return;
10029                }
10030            } else {
10031                if(!checkUpgradeKeySetLP(ps, pkg)) {
10032                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10033                            "New package not signed by keys specified by upgrade-keysets: "
10034                            + pkgName);
10035                    return;
10036                }
10037            }
10038
10039            // In case of rollback, remember per-user/profile install state
10040            allUsers = sUserManager.getUserIds();
10041            perUserInstalled = new boolean[allUsers.length];
10042            for (int i = 0; i < allUsers.length; i++) {
10043                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10044            }
10045        }
10046
10047        boolean sysPkg = (isSystemApp(oldPackage));
10048        if (sysPkg) {
10049            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10050                    user, allUsers, perUserInstalled, installerPackageName, res);
10051        } else {
10052            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10053                    user, allUsers, perUserInstalled, installerPackageName, res);
10054        }
10055    }
10056
10057    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10058            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10059            int[] allUsers, boolean[] perUserInstalled,
10060            String installerPackageName, PackageInstalledInfo res) {
10061        String pkgName = deletedPackage.packageName;
10062        boolean deletedPkg = true;
10063        boolean updatedSettings = false;
10064
10065        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10066                + deletedPackage);
10067        long origUpdateTime;
10068        if (pkg.mExtras != null) {
10069            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10070        } else {
10071            origUpdateTime = 0;
10072        }
10073
10074        // First delete the existing package while retaining the data directory
10075        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10076                res.removedInfo, true)) {
10077            // If the existing package wasn't successfully deleted
10078            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10079            deletedPkg = false;
10080        } else {
10081            // Successfully deleted the old package. Now proceed with re-installation
10082            deleteCodeCacheDirsLI(pkgName);
10083            try {
10084                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10085                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10086                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10087                updatedSettings = true;
10088            } catch (PackageManagerException e) {
10089                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10090            }
10091        }
10092
10093        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10094            // remove package from internal structures.  Note that we want deletePackageX to
10095            // delete the package data and cache directories that it created in
10096            // scanPackageLocked, unless those directories existed before we even tried to
10097            // install.
10098            if(updatedSettings) {
10099                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10100                deletePackageLI(
10101                        pkgName, null, true, allUsers, perUserInstalled,
10102                        PackageManager.DELETE_KEEP_DATA,
10103                                res.removedInfo, true);
10104            }
10105            // Since we failed to install the new package we need to restore the old
10106            // package that we deleted.
10107            if (deletedPkg) {
10108                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10109                File restoreFile = new File(deletedPackage.codePath);
10110                // Parse old package
10111                boolean oldOnSd = isExternal(deletedPackage);
10112                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10113                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10114                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10115                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10116                        | SCAN_UPDATE_TIME;
10117                try {
10118                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null);
10119                } catch (PackageManagerException e) {
10120                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10121                            + e.getMessage());
10122                    return;
10123                }
10124                // Restore of old package succeeded. Update permissions.
10125                // writer
10126                synchronized (mPackages) {
10127                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10128                            UPDATE_PERMISSIONS_ALL);
10129                    // can downgrade to reader
10130                    mSettings.writeLPr();
10131                }
10132                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10133            }
10134        }
10135    }
10136
10137    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10138            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10139            int[] allUsers, boolean[] perUserInstalled,
10140            String installerPackageName, PackageInstalledInfo res) {
10141        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10142                + ", old=" + deletedPackage);
10143        boolean updatedSettings = false;
10144        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10145                PackageParser.PARSE_IS_SYSTEM;
10146        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10147            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10148        }
10149        String packageName = deletedPackage.packageName;
10150        if (packageName == null) {
10151            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10152                    "Attempt to delete null packageName.");
10153            return;
10154        }
10155        PackageParser.Package oldPkg;
10156        PackageSetting oldPkgSetting;
10157        // reader
10158        synchronized (mPackages) {
10159            oldPkg = mPackages.get(packageName);
10160            oldPkgSetting = mSettings.mPackages.get(packageName);
10161            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10162                    (oldPkgSetting == null)) {
10163                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10164                        "Couldn't find package:" + packageName + " information");
10165                return;
10166            }
10167        }
10168
10169        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10170
10171        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10172        res.removedInfo.removedPackage = packageName;
10173        // Remove existing system package
10174        removePackageLI(oldPkgSetting, true);
10175        // writer
10176        synchronized (mPackages) {
10177            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10178                // We didn't need to disable the .apk as a current system package,
10179                // which means we are replacing another update that is already
10180                // installed.  We need to make sure to delete the older one's .apk.
10181                res.removedInfo.args = createInstallArgsForExisting(0,
10182                        deletedPackage.applicationInfo.getCodePath(),
10183                        deletedPackage.applicationInfo.getResourcePath(),
10184                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10185                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10186                        isMultiArch(deletedPackage.applicationInfo));
10187            } else {
10188                res.removedInfo.args = null;
10189            }
10190        }
10191
10192        // Successfully disabled the old package. Now proceed with re-installation
10193        deleteCodeCacheDirsLI(packageName);
10194
10195        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10196        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10197
10198        PackageParser.Package newPackage = null;
10199        try {
10200            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
10201            if (newPackage.mExtras != null) {
10202                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10203                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10204                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10205
10206                // is the update attempting to change shared user? that isn't going to work...
10207                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10208                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10209                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10210                            + " to " + newPkgSetting.sharedUser);
10211                    updatedSettings = true;
10212                }
10213            }
10214
10215            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10216                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10217                updatedSettings = true;
10218            }
10219
10220        } catch (PackageManagerException e) {
10221            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10222        }
10223
10224        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10225            // Re installation failed. Restore old information
10226            // Remove new pkg information
10227            if (newPackage != null) {
10228                removeInstalledPackageLI(newPackage, true);
10229            }
10230            // Add back the old system package
10231            try {
10232                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
10233            } catch (PackageManagerException e) {
10234                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10235            }
10236            // Restore the old system information in Settings
10237            synchronized(mPackages) {
10238                if (updatedSettings) {
10239                    mSettings.enableSystemPackageLPw(packageName);
10240                    mSettings.setInstallerPackageName(packageName,
10241                            oldPkgSetting.installerPackageName);
10242                }
10243                mSettings.writeLPr();
10244            }
10245        }
10246    }
10247
10248    // Utility method used to move dex files during install.
10249    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10250        // TODO: extend to move split APK dex files
10251        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10252            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10253            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10254            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10255                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10256                        dexCodeInstructionSet);
10257                if (retCode != 0) {
10258                /*
10259                 * Programs may be lazily run through dexopt, so the
10260                 * source may not exist. However, something seems to
10261                 * have gone wrong, so note that dexopt needs to be
10262                 * run again and remove the source file. In addition,
10263                 * remove the target to make sure there isn't a stale
10264                 * file from a previous version of the package.
10265                 */
10266                    newPackage.mDexOptPerformed.clear();
10267                    mInstaller.rmdex(oldCodePath, dexCodeInstructionSet);
10268                    mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet);
10269                }
10270            }
10271        }
10272        return PackageManager.INSTALL_SUCCEEDED;
10273    }
10274
10275    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10276            int[] allUsers, boolean[] perUserInstalled,
10277            PackageInstalledInfo res) {
10278        String pkgName = newPackage.packageName;
10279        synchronized (mPackages) {
10280            //write settings. the installStatus will be incomplete at this stage.
10281            //note that the new package setting would have already been
10282            //added to mPackages. It hasn't been persisted yet.
10283            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10284            mSettings.writeLPr();
10285        }
10286
10287        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10288
10289        synchronized (mPackages) {
10290            updatePermissionsLPw(newPackage.packageName, newPackage,
10291                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10292                            ? UPDATE_PERMISSIONS_ALL : 0));
10293            // For system-bundled packages, we assume that installing an upgraded version
10294            // of the package implies that the user actually wants to run that new code,
10295            // so we enable the package.
10296            if (isSystemApp(newPackage)) {
10297                // NB: implicit assumption that system package upgrades apply to all users
10298                if (DEBUG_INSTALL) {
10299                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10300                }
10301                PackageSetting ps = mSettings.mPackages.get(pkgName);
10302                if (ps != null) {
10303                    if (res.origUsers != null) {
10304                        for (int userHandle : res.origUsers) {
10305                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10306                                    userHandle, installerPackageName);
10307                        }
10308                    }
10309                    // Also convey the prior install/uninstall state
10310                    if (allUsers != null && perUserInstalled != null) {
10311                        for (int i = 0; i < allUsers.length; i++) {
10312                            if (DEBUG_INSTALL) {
10313                                Slog.d(TAG, "    user " + allUsers[i]
10314                                        + " => " + perUserInstalled[i]);
10315                            }
10316                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10317                        }
10318                        // these install state changes will be persisted in the
10319                        // upcoming call to mSettings.writeLPr().
10320                    }
10321                }
10322            }
10323            res.name = pkgName;
10324            res.uid = newPackage.applicationInfo.uid;
10325            res.pkg = newPackage;
10326            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10327            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10328            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10329            //to update install status
10330            mSettings.writeLPr();
10331        }
10332    }
10333
10334    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10335        int pFlags = args.flags;
10336        String installerPackageName = args.installerPackageName;
10337        File tmpPackageFile = new File(args.getCodePath());
10338        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10339        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10340        boolean replace = false;
10341        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10342                | (newInstall ? SCAN_NEW_INSTALL : 0);
10343        // Result object to be returned
10344        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10345
10346        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10347        // Retrieve PackageSettings and parse package
10348        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10349                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10350                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10351        PackageParser pp = new PackageParser();
10352        pp.setSeparateProcesses(mSeparateProcesses);
10353        pp.setDisplayMetrics(mMetrics);
10354
10355        final PackageParser.Package pkg;
10356        try {
10357            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10358        } catch (PackageParserException e) {
10359            res.setError("Failed parse during installPackageLI", e);
10360            return;
10361        }
10362
10363        // Mark that we have an install time CPU ABI override.
10364        pkg.cpuAbiOverride = args.abiOverride;
10365
10366        String pkgName = res.name = pkg.packageName;
10367        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10368            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10369                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10370                return;
10371            }
10372        }
10373
10374        try {
10375            pp.collectCertificates(pkg, parseFlags);
10376            pp.collectManifestDigest(pkg);
10377        } catch (PackageParserException e) {
10378            res.setError("Failed collect during installPackageLI", e);
10379            return;
10380        }
10381
10382        /* If the installer passed in a manifest digest, compare it now. */
10383        if (args.manifestDigest != null) {
10384            if (DEBUG_INSTALL) {
10385                final String parsedManifest = pkg.manifestDigest == null ? "null"
10386                        : pkg.manifestDigest.toString();
10387                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10388                        + parsedManifest);
10389            }
10390
10391            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10392                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10393                return;
10394            }
10395        } else if (DEBUG_INSTALL) {
10396            final String parsedManifest = pkg.manifestDigest == null
10397                    ? "null" : pkg.manifestDigest.toString();
10398            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10399        }
10400
10401        // Get rid of all references to package scan path via parser.
10402        pp = null;
10403        String oldCodePath = null;
10404        boolean systemApp = false;
10405        synchronized (mPackages) {
10406            // Check whether the newly-scanned package wants to define an already-defined perm
10407            int N = pkg.permissions.size();
10408            for (int i = N-1; i >= 0; i--) {
10409                PackageParser.Permission perm = pkg.permissions.get(i);
10410                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10411                if (bp != null) {
10412                    // If the defining package is signed with our cert, it's okay.  This
10413                    // also includes the "updating the same package" case, of course.
10414                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10415                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10416                        // If the owning package is the system itself, we log but allow
10417                        // install to proceed; we fail the install on all other permission
10418                        // redefinitions.
10419                        if (!bp.sourcePackage.equals("android")) {
10420                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10421                                    + pkg.packageName + " attempting to redeclare permission "
10422                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10423                            res.origPermission = perm.info.name;
10424                            res.origPackage = bp.sourcePackage;
10425                            return;
10426                        } else {
10427                            Slog.w(TAG, "Package " + pkg.packageName
10428                                    + " attempting to redeclare system permission "
10429                                    + perm.info.name + "; ignoring new declaration");
10430                            pkg.permissions.remove(i);
10431                        }
10432                    }
10433                }
10434            }
10435
10436            // Check if installing already existing package
10437            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10438                String oldName = mSettings.mRenamedPackages.get(pkgName);
10439                if (pkg.mOriginalPackages != null
10440                        && pkg.mOriginalPackages.contains(oldName)
10441                        && mPackages.containsKey(oldName)) {
10442                    // This package is derived from an original package,
10443                    // and this device has been updating from that original
10444                    // name.  We must continue using the original name, so
10445                    // rename the new package here.
10446                    pkg.setPackageName(oldName);
10447                    pkgName = pkg.packageName;
10448                    replace = true;
10449                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10450                            + oldName + " pkgName=" + pkgName);
10451                } else if (mPackages.containsKey(pkgName)) {
10452                    // This package, under its official name, already exists
10453                    // on the device; we should replace it.
10454                    replace = true;
10455                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10456                }
10457            }
10458            PackageSetting ps = mSettings.mPackages.get(pkgName);
10459            if (ps != null) {
10460                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10461                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10462                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10463                    systemApp = (ps.pkg.applicationInfo.flags &
10464                            ApplicationInfo.FLAG_SYSTEM) != 0;
10465                }
10466                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10467            }
10468        }
10469
10470        if (systemApp && onSd) {
10471            // Disable updates to system apps on sdcard
10472            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10473                    "Cannot install updates to system apps on sdcard");
10474            return;
10475        }
10476
10477        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10478            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10479            return;
10480        }
10481
10482        if (replace) {
10483            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10484                    installerPackageName, res);
10485        } else {
10486            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10487                    installerPackageName, res);
10488        }
10489        synchronized (mPackages) {
10490            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10491            if (ps != null) {
10492                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10493            }
10494        }
10495    }
10496
10497    private static boolean isForwardLocked(PackageParser.Package pkg) {
10498        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10499    }
10500
10501    private static boolean isForwardLocked(ApplicationInfo info) {
10502        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10503    }
10504
10505    private boolean isForwardLocked(PackageSetting ps) {
10506        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10507    }
10508
10509    private static boolean isMultiArch(PackageSetting ps) {
10510        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10511    }
10512
10513    private static boolean isMultiArch(ApplicationInfo info) {
10514        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10515    }
10516
10517    private static boolean isExternal(PackageParser.Package pkg) {
10518        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10519    }
10520
10521    private static boolean isExternal(PackageSetting ps) {
10522        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10523    }
10524
10525    private static boolean isExternal(ApplicationInfo info) {
10526        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10527    }
10528
10529    private static boolean isSystemApp(PackageParser.Package pkg) {
10530        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10531    }
10532
10533    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10534        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10535    }
10536
10537    private static boolean isSystemApp(ApplicationInfo info) {
10538        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10539    }
10540
10541    private static boolean isSystemApp(PackageSetting ps) {
10542        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10543    }
10544
10545    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10546        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10547    }
10548
10549    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10550        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10551    }
10552
10553    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10554        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10555    }
10556
10557    private int packageFlagsToInstallFlags(PackageSetting ps) {
10558        int installFlags = 0;
10559        if (isExternal(ps)) {
10560            installFlags |= PackageManager.INSTALL_EXTERNAL;
10561        }
10562        if (isForwardLocked(ps)) {
10563            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10564        }
10565        return installFlags;
10566    }
10567
10568    private void deleteTempPackageFiles() {
10569        final FilenameFilter filter = new FilenameFilter() {
10570            public boolean accept(File dir, String name) {
10571                return name.startsWith("vmdl") && name.endsWith(".tmp");
10572            }
10573        };
10574        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10575            file.delete();
10576        }
10577    }
10578
10579    @Override
10580    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10581            int flags) {
10582        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10583                flags);
10584    }
10585
10586    @Override
10587    public void deletePackage(final String packageName,
10588            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10589        mContext.enforceCallingOrSelfPermission(
10590                android.Manifest.permission.DELETE_PACKAGES, null);
10591        final int uid = Binder.getCallingUid();
10592        if (UserHandle.getUserId(uid) != userId) {
10593            mContext.enforceCallingPermission(
10594                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10595                    "deletePackage for user " + userId);
10596        }
10597        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10598            try {
10599                observer.onPackageDeleted(packageName,
10600                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10601            } catch (RemoteException re) {
10602            }
10603            return;
10604        }
10605
10606        boolean uninstallBlocked = false;
10607        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10608            int[] users = sUserManager.getUserIds();
10609            for (int i = 0; i < users.length; ++i) {
10610                if (getBlockUninstallForUser(packageName, users[i])) {
10611                    uninstallBlocked = true;
10612                    break;
10613                }
10614            }
10615        } else {
10616            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10617        }
10618        if (uninstallBlocked) {
10619            try {
10620                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10621                        null);
10622            } catch (RemoteException re) {
10623            }
10624            return;
10625        }
10626
10627        if (DEBUG_REMOVE) {
10628            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10629        }
10630        // Queue up an async operation since the package deletion may take a little while.
10631        mHandler.post(new Runnable() {
10632            public void run() {
10633                mHandler.removeCallbacks(this);
10634                final int returnCode = deletePackageX(packageName, userId, flags);
10635                if (observer != null) {
10636                    try {
10637                        observer.onPackageDeleted(packageName, returnCode, null);
10638                    } catch (RemoteException e) {
10639                        Log.i(TAG, "Observer no longer exists.");
10640                    } //end catch
10641                } //end if
10642            } //end run
10643        });
10644    }
10645
10646    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10647        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10648                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10649        try {
10650            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10651                    || dpm.isDeviceOwner(packageName))) {
10652                return true;
10653            }
10654        } catch (RemoteException e) {
10655        }
10656        return false;
10657    }
10658
10659    /**
10660     *  This method is an internal method that could be get invoked either
10661     *  to delete an installed package or to clean up a failed installation.
10662     *  After deleting an installed package, a broadcast is sent to notify any
10663     *  listeners that the package has been installed. For cleaning up a failed
10664     *  installation, the broadcast is not necessary since the package's
10665     *  installation wouldn't have sent the initial broadcast either
10666     *  The key steps in deleting a package are
10667     *  deleting the package information in internal structures like mPackages,
10668     *  deleting the packages base directories through installd
10669     *  updating mSettings to reflect current status
10670     *  persisting settings for later use
10671     *  sending a broadcast if necessary
10672     */
10673    private int deletePackageX(String packageName, int userId, int flags) {
10674        final PackageRemovedInfo info = new PackageRemovedInfo();
10675        final boolean res;
10676
10677        if (isPackageDeviceAdmin(packageName, userId)) {
10678            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10679            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10680        }
10681
10682        boolean removedForAllUsers = false;
10683        boolean systemUpdate = false;
10684
10685        // for the uninstall-updates case and restricted profiles, remember the per-
10686        // userhandle installed state
10687        int[] allUsers;
10688        boolean[] perUserInstalled;
10689        synchronized (mPackages) {
10690            PackageSetting ps = mSettings.mPackages.get(packageName);
10691            allUsers = sUserManager.getUserIds();
10692            perUserInstalled = new boolean[allUsers.length];
10693            for (int i = 0; i < allUsers.length; i++) {
10694                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10695            }
10696        }
10697
10698        synchronized (mInstallLock) {
10699            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10700            res = deletePackageLI(packageName,
10701                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10702                            ? UserHandle.ALL : new UserHandle(userId),
10703                    true, allUsers, perUserInstalled,
10704                    flags | REMOVE_CHATTY, info, true);
10705            systemUpdate = info.isRemovedPackageSystemUpdate;
10706            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10707                removedForAllUsers = true;
10708            }
10709            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10710                    + " removedForAllUsers=" + removedForAllUsers);
10711        }
10712
10713        if (res) {
10714            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10715
10716            // If the removed package was a system update, the old system package
10717            // was re-enabled; we need to broadcast this information
10718            if (systemUpdate) {
10719                Bundle extras = new Bundle(1);
10720                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10721                        ? info.removedAppId : info.uid);
10722                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10723
10724                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10725                        extras, null, null, null);
10726                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10727                        extras, null, null, null);
10728                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10729                        null, packageName, null, null);
10730            }
10731        }
10732        // Force a gc here.
10733        Runtime.getRuntime().gc();
10734        // Delete the resources here after sending the broadcast to let
10735        // other processes clean up before deleting resources.
10736        if (info.args != null) {
10737            synchronized (mInstallLock) {
10738                info.args.doPostDeleteLI(true);
10739            }
10740        }
10741
10742        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10743    }
10744
10745    static class PackageRemovedInfo {
10746        String removedPackage;
10747        int uid = -1;
10748        int removedAppId = -1;
10749        int[] removedUsers = null;
10750        boolean isRemovedPackageSystemUpdate = false;
10751        // Clean up resources deleted packages.
10752        InstallArgs args = null;
10753
10754        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10755            Bundle extras = new Bundle(1);
10756            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10757            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10758            if (replacing) {
10759                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10760            }
10761            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10762            if (removedPackage != null) {
10763                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10764                        extras, null, null, removedUsers);
10765                if (fullRemove && !replacing) {
10766                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10767                            extras, null, null, removedUsers);
10768                }
10769            }
10770            if (removedAppId >= 0) {
10771                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10772                        removedUsers);
10773            }
10774        }
10775    }
10776
10777    /*
10778     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10779     * flag is not set, the data directory is removed as well.
10780     * make sure this flag is set for partially installed apps. If not its meaningless to
10781     * delete a partially installed application.
10782     */
10783    private void removePackageDataLI(PackageSetting ps,
10784            int[] allUserHandles, boolean[] perUserInstalled,
10785            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10786        String packageName = ps.name;
10787        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10788        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10789        // Retrieve object to delete permissions for shared user later on
10790        final PackageSetting deletedPs;
10791        // reader
10792        synchronized (mPackages) {
10793            deletedPs = mSettings.mPackages.get(packageName);
10794            if (outInfo != null) {
10795                outInfo.removedPackage = packageName;
10796                outInfo.removedUsers = deletedPs != null
10797                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10798                        : null;
10799            }
10800        }
10801        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10802            removeDataDirsLI(packageName);
10803            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10804        }
10805        // writer
10806        synchronized (mPackages) {
10807            if (deletedPs != null) {
10808                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10809                    if (outInfo != null) {
10810                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10811                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10812                    }
10813                    if (deletedPs != null) {
10814                        updatePermissionsLPw(deletedPs.name, null, 0);
10815                        if (deletedPs.sharedUser != null) {
10816                            // remove permissions associated with package
10817                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10818                        }
10819                    }
10820                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10821                }
10822                // make sure to preserve per-user disabled state if this removal was just
10823                // a downgrade of a system app to the factory package
10824                if (allUserHandles != null && perUserInstalled != null) {
10825                    if (DEBUG_REMOVE) {
10826                        Slog.d(TAG, "Propagating install state across downgrade");
10827                    }
10828                    for (int i = 0; i < allUserHandles.length; i++) {
10829                        if (DEBUG_REMOVE) {
10830                            Slog.d(TAG, "    user " + allUserHandles[i]
10831                                    + " => " + perUserInstalled[i]);
10832                        }
10833                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10834                    }
10835                }
10836            }
10837            // can downgrade to reader
10838            if (writeSettings) {
10839                // Save settings now
10840                mSettings.writeLPr();
10841            }
10842        }
10843        if (outInfo != null) {
10844            // A user ID was deleted here. Go through all users and remove it
10845            // from KeyStore.
10846            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10847        }
10848    }
10849
10850    static boolean locationIsPrivileged(File path) {
10851        try {
10852            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10853                    .getCanonicalPath();
10854            return path.getCanonicalPath().startsWith(privilegedAppDir);
10855        } catch (IOException e) {
10856            Slog.e(TAG, "Unable to access code path " + path);
10857        }
10858        return false;
10859    }
10860
10861    /*
10862     * Tries to delete system package.
10863     */
10864    private boolean deleteSystemPackageLI(PackageSetting newPs,
10865            int[] allUserHandles, boolean[] perUserInstalled,
10866            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10867        final boolean applyUserRestrictions
10868                = (allUserHandles != null) && (perUserInstalled != null);
10869        PackageSetting disabledPs = null;
10870        // Confirm if the system package has been updated
10871        // An updated system app can be deleted. This will also have to restore
10872        // the system pkg from system partition
10873        // reader
10874        synchronized (mPackages) {
10875            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10876        }
10877        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10878                + " disabledPs=" + disabledPs);
10879        if (disabledPs == null) {
10880            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10881            return false;
10882        } else if (DEBUG_REMOVE) {
10883            Slog.d(TAG, "Deleting system pkg from data partition");
10884        }
10885        if (DEBUG_REMOVE) {
10886            if (applyUserRestrictions) {
10887                Slog.d(TAG, "Remembering install states:");
10888                for (int i = 0; i < allUserHandles.length; i++) {
10889                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10890                }
10891            }
10892        }
10893        // Delete the updated package
10894        outInfo.isRemovedPackageSystemUpdate = true;
10895        if (disabledPs.versionCode < newPs.versionCode) {
10896            // Delete data for downgrades
10897            flags &= ~PackageManager.DELETE_KEEP_DATA;
10898        } else {
10899            // Preserve data by setting flag
10900            flags |= PackageManager.DELETE_KEEP_DATA;
10901        }
10902        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10903                allUserHandles, perUserInstalled, outInfo, writeSettings);
10904        if (!ret) {
10905            return false;
10906        }
10907        // writer
10908        synchronized (mPackages) {
10909            // Reinstate the old system package
10910            mSettings.enableSystemPackageLPw(newPs.name);
10911            // Remove any native libraries from the upgraded package.
10912            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10913        }
10914        // Install the system package
10915        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10916        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10917        if (locationIsPrivileged(disabledPs.codePath)) {
10918            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10919        }
10920
10921        final PackageParser.Package newPkg;
10922        try {
10923            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10924        } catch (PackageManagerException e) {
10925            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10926            return false;
10927        }
10928
10929        // writer
10930        synchronized (mPackages) {
10931            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10932            updatePermissionsLPw(newPkg.packageName, newPkg,
10933                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10934            if (applyUserRestrictions) {
10935                if (DEBUG_REMOVE) {
10936                    Slog.d(TAG, "Propagating install state across reinstall");
10937                }
10938                for (int i = 0; i < allUserHandles.length; i++) {
10939                    if (DEBUG_REMOVE) {
10940                        Slog.d(TAG, "    user " + allUserHandles[i]
10941                                + " => " + perUserInstalled[i]);
10942                    }
10943                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10944                }
10945                // Regardless of writeSettings we need to ensure that this restriction
10946                // state propagation is persisted
10947                mSettings.writeAllUsersPackageRestrictionsLPr();
10948            }
10949            // can downgrade to reader here
10950            if (writeSettings) {
10951                mSettings.writeLPr();
10952            }
10953        }
10954        return true;
10955    }
10956
10957    private boolean deleteInstalledPackageLI(PackageSetting ps,
10958            boolean deleteCodeAndResources, int flags,
10959            int[] allUserHandles, boolean[] perUserInstalled,
10960            PackageRemovedInfo outInfo, boolean writeSettings) {
10961        if (outInfo != null) {
10962            outInfo.uid = ps.appId;
10963        }
10964
10965        // Delete package data from internal structures and also remove data if flag is set
10966        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10967
10968        // Delete application code and resources
10969        if (deleteCodeAndResources && (outInfo != null)) {
10970            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10971                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10972                    getAppDexInstructionSets(ps), isMultiArch(ps));
10973        }
10974        return true;
10975    }
10976
10977    @Override
10978    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10979            int userId) {
10980        mContext.enforceCallingOrSelfPermission(
10981                android.Manifest.permission.DELETE_PACKAGES, null);
10982        synchronized (mPackages) {
10983            PackageSetting ps = mSettings.mPackages.get(packageName);
10984            if (ps == null) {
10985                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10986                return false;
10987            }
10988            if (!ps.getInstalled(userId)) {
10989                // Can't block uninstall for an app that is not installed or enabled.
10990                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10991                return false;
10992            }
10993            ps.setBlockUninstall(blockUninstall, userId);
10994            mSettings.writePackageRestrictionsLPr(userId);
10995        }
10996        return true;
10997    }
10998
10999    @Override
11000    public boolean getBlockUninstallForUser(String packageName, int userId) {
11001        synchronized (mPackages) {
11002            PackageSetting ps = mSettings.mPackages.get(packageName);
11003            if (ps == null) {
11004                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11005                return false;
11006            }
11007            return ps.getBlockUninstall(userId);
11008        }
11009    }
11010
11011    /*
11012     * This method handles package deletion in general
11013     */
11014    private boolean deletePackageLI(String packageName, UserHandle user,
11015            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11016            int flags, PackageRemovedInfo outInfo,
11017            boolean writeSettings) {
11018        if (packageName == null) {
11019            Slog.w(TAG, "Attempt to delete null packageName.");
11020            return false;
11021        }
11022        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11023        PackageSetting ps;
11024        boolean dataOnly = false;
11025        int removeUser = -1;
11026        int appId = -1;
11027        synchronized (mPackages) {
11028            ps = mSettings.mPackages.get(packageName);
11029            if (ps == null) {
11030                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11031                return false;
11032            }
11033            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11034                    && user.getIdentifier() != UserHandle.USER_ALL) {
11035                // The caller is asking that the package only be deleted for a single
11036                // user.  To do this, we just mark its uninstalled state and delete
11037                // its data.  If this is a system app, we only allow this to happen if
11038                // they have set the special DELETE_SYSTEM_APP which requests different
11039                // semantics than normal for uninstalling system apps.
11040                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11041                ps.setUserState(user.getIdentifier(),
11042                        COMPONENT_ENABLED_STATE_DEFAULT,
11043                        false, //installed
11044                        true,  //stopped
11045                        true,  //notLaunched
11046                        false, //hidden
11047                        null, null, null,
11048                        false // blockUninstall
11049                        );
11050                if (!isSystemApp(ps)) {
11051                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11052                        // Other user still have this package installed, so all
11053                        // we need to do is clear this user's data and save that
11054                        // it is uninstalled.
11055                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11056                        removeUser = user.getIdentifier();
11057                        appId = ps.appId;
11058                        mSettings.writePackageRestrictionsLPr(removeUser);
11059                    } else {
11060                        // We need to set it back to 'installed' so the uninstall
11061                        // broadcasts will be sent correctly.
11062                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11063                        ps.setInstalled(true, user.getIdentifier());
11064                    }
11065                } else {
11066                    // This is a system app, so we assume that the
11067                    // other users still have this package installed, so all
11068                    // we need to do is clear this user's data and save that
11069                    // it is uninstalled.
11070                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11071                    removeUser = user.getIdentifier();
11072                    appId = ps.appId;
11073                    mSettings.writePackageRestrictionsLPr(removeUser);
11074                }
11075            }
11076        }
11077
11078        if (removeUser >= 0) {
11079            // From above, we determined that we are deleting this only
11080            // for a single user.  Continue the work here.
11081            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11082            if (outInfo != null) {
11083                outInfo.removedPackage = packageName;
11084                outInfo.removedAppId = appId;
11085                outInfo.removedUsers = new int[] {removeUser};
11086            }
11087            mInstaller.clearUserData(packageName, removeUser);
11088            removeKeystoreDataIfNeeded(removeUser, appId);
11089            schedulePackageCleaning(packageName, removeUser, false);
11090            return true;
11091        }
11092
11093        if (dataOnly) {
11094            // Delete application data first
11095            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11096            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11097            return true;
11098        }
11099
11100        boolean ret = false;
11101        if (isSystemApp(ps)) {
11102            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11103            // When an updated system application is deleted we delete the existing resources as well and
11104            // fall back to existing code in system partition
11105            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11106                    flags, outInfo, writeSettings);
11107        } else {
11108            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11109            // Kill application pre-emptively especially for apps on sd.
11110            killApplication(packageName, ps.appId, "uninstall pkg");
11111            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11112                    allUserHandles, perUserInstalled,
11113                    outInfo, writeSettings);
11114        }
11115
11116        return ret;
11117    }
11118
11119    private final class ClearStorageConnection implements ServiceConnection {
11120        IMediaContainerService mContainerService;
11121
11122        @Override
11123        public void onServiceConnected(ComponentName name, IBinder service) {
11124            synchronized (this) {
11125                mContainerService = IMediaContainerService.Stub.asInterface(service);
11126                notifyAll();
11127            }
11128        }
11129
11130        @Override
11131        public void onServiceDisconnected(ComponentName name) {
11132        }
11133    }
11134
11135    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11136        final boolean mounted;
11137        if (Environment.isExternalStorageEmulated()) {
11138            mounted = true;
11139        } else {
11140            final String status = Environment.getExternalStorageState();
11141
11142            mounted = status.equals(Environment.MEDIA_MOUNTED)
11143                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11144        }
11145
11146        if (!mounted) {
11147            return;
11148        }
11149
11150        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11151        int[] users;
11152        if (userId == UserHandle.USER_ALL) {
11153            users = sUserManager.getUserIds();
11154        } else {
11155            users = new int[] { userId };
11156        }
11157        final ClearStorageConnection conn = new ClearStorageConnection();
11158        if (mContext.bindServiceAsUser(
11159                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11160            try {
11161                for (int curUser : users) {
11162                    long timeout = SystemClock.uptimeMillis() + 5000;
11163                    synchronized (conn) {
11164                        long now = SystemClock.uptimeMillis();
11165                        while (conn.mContainerService == null && now < timeout) {
11166                            try {
11167                                conn.wait(timeout - now);
11168                            } catch (InterruptedException e) {
11169                            }
11170                        }
11171                    }
11172                    if (conn.mContainerService == null) {
11173                        return;
11174                    }
11175
11176                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11177                    clearDirectory(conn.mContainerService,
11178                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11179                    if (allData) {
11180                        clearDirectory(conn.mContainerService,
11181                                userEnv.buildExternalStorageAppDataDirs(packageName));
11182                        clearDirectory(conn.mContainerService,
11183                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11184                    }
11185                }
11186            } finally {
11187                mContext.unbindService(conn);
11188            }
11189        }
11190    }
11191
11192    @Override
11193    public void clearApplicationUserData(final String packageName,
11194            final IPackageDataObserver observer, final int userId) {
11195        mContext.enforceCallingOrSelfPermission(
11196                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11197        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11198        // Queue up an async operation since the package deletion may take a little while.
11199        mHandler.post(new Runnable() {
11200            public void run() {
11201                mHandler.removeCallbacks(this);
11202                final boolean succeeded;
11203                synchronized (mInstallLock) {
11204                    succeeded = clearApplicationUserDataLI(packageName, userId);
11205                }
11206                clearExternalStorageDataSync(packageName, userId, true);
11207                if (succeeded) {
11208                    // invoke DeviceStorageMonitor's update method to clear any notifications
11209                    DeviceStorageMonitorInternal
11210                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11211                    if (dsm != null) {
11212                        dsm.checkMemory();
11213                    }
11214                }
11215                if(observer != null) {
11216                    try {
11217                        observer.onRemoveCompleted(packageName, succeeded);
11218                    } catch (RemoteException e) {
11219                        Log.i(TAG, "Observer no longer exists.");
11220                    }
11221                } //end if observer
11222            } //end run
11223        });
11224    }
11225
11226    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11227        if (packageName == null) {
11228            Slog.w(TAG, "Attempt to delete null packageName.");
11229            return false;
11230        }
11231        PackageParser.Package p;
11232        boolean dataOnly = false;
11233        final int appId;
11234        synchronized (mPackages) {
11235            p = mPackages.get(packageName);
11236            if (p == null) {
11237                dataOnly = true;
11238                PackageSetting ps = mSettings.mPackages.get(packageName);
11239                if ((ps == null) || (ps.pkg == null)) {
11240                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11241                    return false;
11242                }
11243                p = ps.pkg;
11244            }
11245            if (!dataOnly) {
11246                // need to check this only for fully installed applications
11247                if (p == null) {
11248                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11249                    return false;
11250                }
11251                final ApplicationInfo applicationInfo = p.applicationInfo;
11252                if (applicationInfo == null) {
11253                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11254                    return false;
11255                }
11256            }
11257            if (p != null && p.applicationInfo != null) {
11258                appId = p.applicationInfo.uid;
11259            } else {
11260                appId = -1;
11261            }
11262        }
11263        int retCode = mInstaller.clearUserData(packageName, userId);
11264        if (retCode < 0) {
11265            Slog.w(TAG, "Couldn't remove cache files for package: "
11266                    + packageName);
11267            return false;
11268        }
11269        removeKeystoreDataIfNeeded(userId, appId);
11270        return true;
11271    }
11272
11273    /**
11274     * Remove entries from the keystore daemon. Will only remove it if the
11275     * {@code appId} is valid.
11276     */
11277    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11278        if (appId < 0) {
11279            return;
11280        }
11281
11282        final KeyStore keyStore = KeyStore.getInstance();
11283        if (keyStore != null) {
11284            if (userId == UserHandle.USER_ALL) {
11285                for (final int individual : sUserManager.getUserIds()) {
11286                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11287                }
11288            } else {
11289                keyStore.clearUid(UserHandle.getUid(userId, appId));
11290            }
11291        } else {
11292            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11293        }
11294    }
11295
11296    @Override
11297    public void deleteApplicationCacheFiles(final String packageName,
11298            final IPackageDataObserver observer) {
11299        mContext.enforceCallingOrSelfPermission(
11300                android.Manifest.permission.DELETE_CACHE_FILES, null);
11301        // Queue up an async operation since the package deletion may take a little while.
11302        final int userId = UserHandle.getCallingUserId();
11303        mHandler.post(new Runnable() {
11304            public void run() {
11305                mHandler.removeCallbacks(this);
11306                final boolean succeded;
11307                synchronized (mInstallLock) {
11308                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11309                }
11310                clearExternalStorageDataSync(packageName, userId, false);
11311                if(observer != null) {
11312                    try {
11313                        observer.onRemoveCompleted(packageName, succeded);
11314                    } catch (RemoteException e) {
11315                        Log.i(TAG, "Observer no longer exists.");
11316                    }
11317                } //end if observer
11318            } //end run
11319        });
11320    }
11321
11322    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11323        if (packageName == null) {
11324            Slog.w(TAG, "Attempt to delete null packageName.");
11325            return false;
11326        }
11327        PackageParser.Package p;
11328        synchronized (mPackages) {
11329            p = mPackages.get(packageName);
11330        }
11331        if (p == null) {
11332            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11333            return false;
11334        }
11335        final ApplicationInfo applicationInfo = p.applicationInfo;
11336        if (applicationInfo == null) {
11337            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11338            return false;
11339        }
11340        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11341        if (retCode < 0) {
11342            Slog.w(TAG, "Couldn't remove cache files for package: "
11343                       + packageName + " u" + userId);
11344            return false;
11345        }
11346        return true;
11347    }
11348
11349    @Override
11350    public void getPackageSizeInfo(final String packageName, int userHandle,
11351            final IPackageStatsObserver observer) {
11352        mContext.enforceCallingOrSelfPermission(
11353                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11354        if (packageName == null) {
11355            throw new IllegalArgumentException("Attempt to get size of null packageName");
11356        }
11357
11358        PackageStats stats = new PackageStats(packageName, userHandle);
11359
11360        /*
11361         * Queue up an async operation since the package measurement may take a
11362         * little while.
11363         */
11364        Message msg = mHandler.obtainMessage(INIT_COPY);
11365        msg.obj = new MeasureParams(stats, observer);
11366        mHandler.sendMessage(msg);
11367    }
11368
11369    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11370            PackageStats pStats) {
11371        if (packageName == null) {
11372            Slog.w(TAG, "Attempt to get size of null packageName.");
11373            return false;
11374        }
11375        PackageParser.Package p;
11376        boolean dataOnly = false;
11377        String libDirRoot = null;
11378        String asecPath = null;
11379        PackageSetting ps = null;
11380        synchronized (mPackages) {
11381            p = mPackages.get(packageName);
11382            ps = mSettings.mPackages.get(packageName);
11383            if(p == null) {
11384                dataOnly = true;
11385                if((ps == null) || (ps.pkg == null)) {
11386                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11387                    return false;
11388                }
11389                p = ps.pkg;
11390            }
11391            if (ps != null) {
11392                libDirRoot = ps.legacyNativeLibraryPathString;
11393            }
11394            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11395                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11396                if (secureContainerId != null) {
11397                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11398                }
11399            }
11400        }
11401        String publicSrcDir = null;
11402        if(!dataOnly) {
11403            final ApplicationInfo applicationInfo = p.applicationInfo;
11404            if (applicationInfo == null) {
11405                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11406                return false;
11407            }
11408            if (isForwardLocked(p)) {
11409                publicSrcDir = applicationInfo.getBaseResourcePath();
11410            }
11411        }
11412        // TODO: extend to measure size of split APKs
11413        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11414        // not just the first level.
11415        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11416        // just the primary.
11417        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11418        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11419                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11420        if (res < 0) {
11421            return false;
11422        }
11423
11424        // Fix-up for forward-locked applications in ASEC containers.
11425        if (!isExternal(p)) {
11426            pStats.codeSize += pStats.externalCodeSize;
11427            pStats.externalCodeSize = 0L;
11428        }
11429
11430        return true;
11431    }
11432
11433
11434    @Override
11435    public void addPackageToPreferred(String packageName) {
11436        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11437    }
11438
11439    @Override
11440    public void removePackageFromPreferred(String packageName) {
11441        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11442    }
11443
11444    @Override
11445    public List<PackageInfo> getPreferredPackages(int flags) {
11446        return new ArrayList<PackageInfo>();
11447    }
11448
11449    private int getUidTargetSdkVersionLockedLPr(int uid) {
11450        Object obj = mSettings.getUserIdLPr(uid);
11451        if (obj instanceof SharedUserSetting) {
11452            final SharedUserSetting sus = (SharedUserSetting) obj;
11453            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11454            final Iterator<PackageSetting> it = sus.packages.iterator();
11455            while (it.hasNext()) {
11456                final PackageSetting ps = it.next();
11457                if (ps.pkg != null) {
11458                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11459                    if (v < vers) vers = v;
11460                }
11461            }
11462            return vers;
11463        } else if (obj instanceof PackageSetting) {
11464            final PackageSetting ps = (PackageSetting) obj;
11465            if (ps.pkg != null) {
11466                return ps.pkg.applicationInfo.targetSdkVersion;
11467            }
11468        }
11469        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11470    }
11471
11472    @Override
11473    public void addPreferredActivity(IntentFilter filter, int match,
11474            ComponentName[] set, ComponentName activity, int userId) {
11475        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11476                "Adding preferred");
11477    }
11478
11479    private void addPreferredActivityInternal(IntentFilter filter, int match,
11480            ComponentName[] set, ComponentName activity, boolean always, int userId,
11481            String opname) {
11482        // writer
11483        int callingUid = Binder.getCallingUid();
11484        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11485        if (filter.countActions() == 0) {
11486            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11487            return;
11488        }
11489        synchronized (mPackages) {
11490            if (mContext.checkCallingOrSelfPermission(
11491                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11492                    != PackageManager.PERMISSION_GRANTED) {
11493                if (getUidTargetSdkVersionLockedLPr(callingUid)
11494                        < Build.VERSION_CODES.FROYO) {
11495                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11496                            + callingUid);
11497                    return;
11498                }
11499                mContext.enforceCallingOrSelfPermission(
11500                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11501            }
11502
11503            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11504            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11505                    + userId + ":");
11506            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11507            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11508            mSettings.writePackageRestrictionsLPr(userId);
11509        }
11510    }
11511
11512    @Override
11513    public void replacePreferredActivity(IntentFilter filter, int match,
11514            ComponentName[] set, ComponentName activity, int userId) {
11515        if (filter.countActions() != 1) {
11516            throw new IllegalArgumentException(
11517                    "replacePreferredActivity expects filter to have only 1 action.");
11518        }
11519        if (filter.countDataAuthorities() != 0
11520                || filter.countDataPaths() != 0
11521                || filter.countDataSchemes() > 1
11522                || filter.countDataTypes() != 0) {
11523            throw new IllegalArgumentException(
11524                    "replacePreferredActivity expects filter to have no data authorities, " +
11525                    "paths, or types; and at most one scheme.");
11526        }
11527
11528        final int callingUid = Binder.getCallingUid();
11529        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11530        synchronized (mPackages) {
11531            if (mContext.checkCallingOrSelfPermission(
11532                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11533                    != PackageManager.PERMISSION_GRANTED) {
11534                if (getUidTargetSdkVersionLockedLPr(callingUid)
11535                        < Build.VERSION_CODES.FROYO) {
11536                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11537                            + Binder.getCallingUid());
11538                    return;
11539                }
11540                mContext.enforceCallingOrSelfPermission(
11541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11542            }
11543
11544            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11545            if (pir != null) {
11546                // Get all of the existing entries that exactly match this filter.
11547                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11548                if (existing != null && existing.size() == 1) {
11549                    PreferredActivity cur = existing.get(0);
11550                    if (DEBUG_PREFERRED) {
11551                        Slog.i(TAG, "Checking replace of preferred:");
11552                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11553                        if (!cur.mPref.mAlways) {
11554                            Slog.i(TAG, "  -- CUR; not mAlways!");
11555                        } else {
11556                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11557                            Slog.i(TAG, "  -- CUR: mSet="
11558                                    + Arrays.toString(cur.mPref.mSetComponents));
11559                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11560                            Slog.i(TAG, "  -- NEW: mMatch="
11561                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11562                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11563                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11564                        }
11565                    }
11566                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11567                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11568                            && cur.mPref.sameSet(set)) {
11569                        if (DEBUG_PREFERRED) {
11570                            Slog.i(TAG, "Replacing with same preferred activity "
11571                                    + cur.mPref.mShortComponent + " for user "
11572                                    + userId + ":");
11573                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11574                        } else {
11575                            Slog.i(TAG, "Replacing with same preferred activity "
11576                                    + cur.mPref.mShortComponent + " for user "
11577                                    + userId);
11578                        }
11579                        return;
11580                    }
11581                }
11582
11583                if (existing != null) {
11584                    if (DEBUG_PREFERRED) {
11585                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11586                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11587                    }
11588                    for (int i = 0; i < existing.size(); i++) {
11589                        PreferredActivity pa = existing.get(i);
11590                        if (DEBUG_PREFERRED) {
11591                            Slog.i(TAG, "Removing existing preferred activity "
11592                                    + pa.mPref.mComponent + ":");
11593                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11594                        }
11595                        pir.removeFilter(pa);
11596                    }
11597                }
11598            }
11599            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11600                    "Replacing preferred");
11601        }
11602    }
11603
11604    @Override
11605    public void clearPackagePreferredActivities(String packageName) {
11606        final int uid = Binder.getCallingUid();
11607        // writer
11608        synchronized (mPackages) {
11609            PackageParser.Package pkg = mPackages.get(packageName);
11610            if (pkg == null || pkg.applicationInfo.uid != uid) {
11611                if (mContext.checkCallingOrSelfPermission(
11612                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11613                        != PackageManager.PERMISSION_GRANTED) {
11614                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11615                            < Build.VERSION_CODES.FROYO) {
11616                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11617                                + Binder.getCallingUid());
11618                        return;
11619                    }
11620                    mContext.enforceCallingOrSelfPermission(
11621                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11622                }
11623            }
11624
11625            int user = UserHandle.getCallingUserId();
11626            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11627                mSettings.writePackageRestrictionsLPr(user);
11628                scheduleWriteSettingsLocked();
11629            }
11630        }
11631    }
11632
11633    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11634    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11635        ArrayList<PreferredActivity> removed = null;
11636        boolean changed = false;
11637        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11638            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11639            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11640            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11641                continue;
11642            }
11643            Iterator<PreferredActivity> it = pir.filterIterator();
11644            while (it.hasNext()) {
11645                PreferredActivity pa = it.next();
11646                // Mark entry for removal only if it matches the package name
11647                // and the entry is of type "always".
11648                if (packageName == null ||
11649                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11650                                && pa.mPref.mAlways)) {
11651                    if (removed == null) {
11652                        removed = new ArrayList<PreferredActivity>();
11653                    }
11654                    removed.add(pa);
11655                }
11656            }
11657            if (removed != null) {
11658                for (int j=0; j<removed.size(); j++) {
11659                    PreferredActivity pa = removed.get(j);
11660                    pir.removeFilter(pa);
11661                }
11662                changed = true;
11663            }
11664        }
11665        return changed;
11666    }
11667
11668    @Override
11669    public void resetPreferredActivities(int userId) {
11670        mContext.enforceCallingOrSelfPermission(
11671                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11672        // writer
11673        synchronized (mPackages) {
11674            int user = UserHandle.getCallingUserId();
11675            clearPackagePreferredActivitiesLPw(null, user);
11676            mSettings.readDefaultPreferredAppsLPw(this, user);
11677            mSettings.writePackageRestrictionsLPr(user);
11678            scheduleWriteSettingsLocked();
11679        }
11680    }
11681
11682    @Override
11683    public int getPreferredActivities(List<IntentFilter> outFilters,
11684            List<ComponentName> outActivities, String packageName) {
11685
11686        int num = 0;
11687        final int userId = UserHandle.getCallingUserId();
11688        // reader
11689        synchronized (mPackages) {
11690            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11691            if (pir != null) {
11692                final Iterator<PreferredActivity> it = pir.filterIterator();
11693                while (it.hasNext()) {
11694                    final PreferredActivity pa = it.next();
11695                    if (packageName == null
11696                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11697                                    && pa.mPref.mAlways)) {
11698                        if (outFilters != null) {
11699                            outFilters.add(new IntentFilter(pa));
11700                        }
11701                        if (outActivities != null) {
11702                            outActivities.add(pa.mPref.mComponent);
11703                        }
11704                    }
11705                }
11706            }
11707        }
11708
11709        return num;
11710    }
11711
11712    @Override
11713    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11714            int userId) {
11715        int callingUid = Binder.getCallingUid();
11716        if (callingUid != Process.SYSTEM_UID) {
11717            throw new SecurityException(
11718                    "addPersistentPreferredActivity can only be run by the system");
11719        }
11720        if (filter.countActions() == 0) {
11721            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11722            return;
11723        }
11724        synchronized (mPackages) {
11725            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11726                    " :");
11727            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11728            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11729                    new PersistentPreferredActivity(filter, activity));
11730            mSettings.writePackageRestrictionsLPr(userId);
11731        }
11732    }
11733
11734    @Override
11735    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11736        int callingUid = Binder.getCallingUid();
11737        if (callingUid != Process.SYSTEM_UID) {
11738            throw new SecurityException(
11739                    "clearPackagePersistentPreferredActivities can only be run by the system");
11740        }
11741        ArrayList<PersistentPreferredActivity> removed = null;
11742        boolean changed = false;
11743        synchronized (mPackages) {
11744            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11745                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11746                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11747                        .valueAt(i);
11748                if (userId != thisUserId) {
11749                    continue;
11750                }
11751                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11752                while (it.hasNext()) {
11753                    PersistentPreferredActivity ppa = it.next();
11754                    // Mark entry for removal only if it matches the package name.
11755                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11756                        if (removed == null) {
11757                            removed = new ArrayList<PersistentPreferredActivity>();
11758                        }
11759                        removed.add(ppa);
11760                    }
11761                }
11762                if (removed != null) {
11763                    for (int j=0; j<removed.size(); j++) {
11764                        PersistentPreferredActivity ppa = removed.get(j);
11765                        ppir.removeFilter(ppa);
11766                    }
11767                    changed = true;
11768                }
11769            }
11770
11771            if (changed) {
11772                mSettings.writePackageRestrictionsLPr(userId);
11773            }
11774        }
11775    }
11776
11777    @Override
11778    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11779            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11780        mContext.enforceCallingOrSelfPermission(
11781                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11782        int callingUid = Binder.getCallingUid();
11783        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11784        if (intentFilter.countActions() == 0) {
11785            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11786            return;
11787        }
11788        synchronized (mPackages) {
11789            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11790                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11791            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11792            mSettings.writePackageRestrictionsLPr(sourceUserId);
11793        }
11794    }
11795
11796    @Override
11797    public void addCrossProfileIntentsForPackage(String packageName,
11798            int sourceUserId, int targetUserId) {
11799        mContext.enforceCallingOrSelfPermission(
11800                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11801        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11802        mSettings.writePackageRestrictionsLPr(sourceUserId);
11803    }
11804
11805    @Override
11806    public void removeCrossProfileIntentsForPackage(String packageName,
11807            int sourceUserId, int targetUserId) {
11808        mContext.enforceCallingOrSelfPermission(
11809                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11810        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11811        mSettings.writePackageRestrictionsLPr(sourceUserId);
11812    }
11813
11814    @Override
11815    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11816            int ownerUserId) {
11817        mContext.enforceCallingOrSelfPermission(
11818                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11819        int callingUid = Binder.getCallingUid();
11820        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11821        int callingUserId = UserHandle.getUserId(callingUid);
11822        synchronized (mPackages) {
11823            CrossProfileIntentResolver resolver =
11824                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11825            HashSet<CrossProfileIntentFilter> set =
11826                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11827            for (CrossProfileIntentFilter filter : set) {
11828                if (filter.getOwnerPackage().equals(ownerPackage)
11829                        && filter.getOwnerUserId() == callingUserId) {
11830                    resolver.removeFilter(filter);
11831                }
11832            }
11833            mSettings.writePackageRestrictionsLPr(sourceUserId);
11834        }
11835    }
11836
11837    // Enforcing that callingUid is owning pkg on userId
11838    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11839        // The system owns everything.
11840        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11841            return;
11842        }
11843        int callingUserId = UserHandle.getUserId(callingUid);
11844        if (callingUserId != userId) {
11845            throw new SecurityException("calling uid " + callingUid
11846                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11847                    + callingUserId);
11848        }
11849        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11850        if (pi == null) {
11851            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11852                    + callingUserId);
11853        }
11854        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11855            throw new SecurityException("Calling uid " + callingUid
11856                    + " does not own package " + pkg);
11857        }
11858    }
11859
11860    @Override
11861    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11862        Intent intent = new Intent(Intent.ACTION_MAIN);
11863        intent.addCategory(Intent.CATEGORY_HOME);
11864
11865        final int callingUserId = UserHandle.getCallingUserId();
11866        List<ResolveInfo> list = queryIntentActivities(intent, null,
11867                PackageManager.GET_META_DATA, callingUserId);
11868        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11869                true, false, false, callingUserId);
11870
11871        allHomeCandidates.clear();
11872        if (list != null) {
11873            for (ResolveInfo ri : list) {
11874                allHomeCandidates.add(ri);
11875            }
11876        }
11877        return (preferred == null || preferred.activityInfo == null)
11878                ? null
11879                : new ComponentName(preferred.activityInfo.packageName,
11880                        preferred.activityInfo.name);
11881    }
11882
11883    /**
11884     * Check if calling UID is the current home app. This handles both the case
11885     * where the user has selected a specific home app, and where there is only
11886     * one home app.
11887     */
11888    public boolean checkCallerIsHomeApp() {
11889        final Intent intent = new Intent(Intent.ACTION_MAIN);
11890        intent.addCategory(Intent.CATEGORY_HOME);
11891
11892        final int callingUid = Binder.getCallingUid();
11893        final int callingUserId = UserHandle.getCallingUserId();
11894        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11895        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11896                false, false, callingUserId);
11897
11898        if (preferredHome != null) {
11899            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11900                return true;
11901            }
11902        } else {
11903            for (ResolveInfo info : allHomes) {
11904                if (callingUid == info.activityInfo.applicationInfo.uid) {
11905                    return true;
11906                }
11907            }
11908        }
11909
11910        return false;
11911    }
11912
11913    /**
11914     * Enforce that calling UID is the current home app. This handles both the
11915     * case where the user has selected a specific home app, and where there is
11916     * only one home app.
11917     */
11918    public void enforceCallerIsHomeApp() {
11919        if (!checkCallerIsHomeApp()) {
11920            throw new SecurityException("Caller is not currently selected home app");
11921        }
11922    }
11923
11924    @Override
11925    public void setApplicationEnabledSetting(String appPackageName,
11926            int newState, int flags, int userId, String callingPackage) {
11927        if (!sUserManager.exists(userId)) return;
11928        if (callingPackage == null) {
11929            callingPackage = Integer.toString(Binder.getCallingUid());
11930        }
11931        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11932    }
11933
11934    @Override
11935    public void setComponentEnabledSetting(ComponentName componentName,
11936            int newState, int flags, int userId) {
11937        if (!sUserManager.exists(userId)) return;
11938        setEnabledSetting(componentName.getPackageName(),
11939                componentName.getClassName(), newState, flags, userId, null);
11940    }
11941
11942    private void setEnabledSetting(final String packageName, String className, int newState,
11943            final int flags, int userId, String callingPackage) {
11944        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11945              || newState == COMPONENT_ENABLED_STATE_ENABLED
11946              || newState == COMPONENT_ENABLED_STATE_DISABLED
11947              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11948              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11949            throw new IllegalArgumentException("Invalid new component state: "
11950                    + newState);
11951        }
11952        PackageSetting pkgSetting;
11953        final int uid = Binder.getCallingUid();
11954        final int permission = mContext.checkCallingOrSelfPermission(
11955                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11956        enforceCrossUserPermission(uid, userId, false, "set enabled");
11957        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11958        boolean sendNow = false;
11959        boolean isApp = (className == null);
11960        String componentName = isApp ? packageName : className;
11961        int packageUid = -1;
11962        ArrayList<String> components;
11963
11964        // writer
11965        synchronized (mPackages) {
11966            pkgSetting = mSettings.mPackages.get(packageName);
11967            if (pkgSetting == null) {
11968                if (className == null) {
11969                    throw new IllegalArgumentException(
11970                            "Unknown package: " + packageName);
11971                }
11972                throw new IllegalArgumentException(
11973                        "Unknown component: " + packageName
11974                        + "/" + className);
11975            }
11976            // Allow root and verify that userId is not being specified by a different user
11977            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11978                throw new SecurityException(
11979                        "Permission Denial: attempt to change component state from pid="
11980                        + Binder.getCallingPid()
11981                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11982            }
11983            if (className == null) {
11984                // We're dealing with an application/package level state change
11985                if (pkgSetting.getEnabled(userId) == newState) {
11986                    // Nothing to do
11987                    return;
11988                }
11989                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11990                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11991                    // Don't care about who enables an app.
11992                    callingPackage = null;
11993                }
11994                pkgSetting.setEnabled(newState, userId, callingPackage);
11995                // pkgSetting.pkg.mSetEnabled = newState;
11996            } else {
11997                // We're dealing with a component level state change
11998                // First, verify that this is a valid class name.
11999                PackageParser.Package pkg = pkgSetting.pkg;
12000                if (pkg == null || !pkg.hasComponentClassName(className)) {
12001                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12002                        throw new IllegalArgumentException("Component class " + className
12003                                + " does not exist in " + packageName);
12004                    } else {
12005                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12006                                + className + " does not exist in " + packageName);
12007                    }
12008                }
12009                switch (newState) {
12010                case COMPONENT_ENABLED_STATE_ENABLED:
12011                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12012                        return;
12013                    }
12014                    break;
12015                case COMPONENT_ENABLED_STATE_DISABLED:
12016                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12017                        return;
12018                    }
12019                    break;
12020                case COMPONENT_ENABLED_STATE_DEFAULT:
12021                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12022                        return;
12023                    }
12024                    break;
12025                default:
12026                    Slog.e(TAG, "Invalid new component state: " + newState);
12027                    return;
12028                }
12029            }
12030            mSettings.writePackageRestrictionsLPr(userId);
12031            components = mPendingBroadcasts.get(userId, packageName);
12032            final boolean newPackage = components == null;
12033            if (newPackage) {
12034                components = new ArrayList<String>();
12035            }
12036            if (!components.contains(componentName)) {
12037                components.add(componentName);
12038            }
12039            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12040                sendNow = true;
12041                // Purge entry from pending broadcast list if another one exists already
12042                // since we are sending one right away.
12043                mPendingBroadcasts.remove(userId, packageName);
12044            } else {
12045                if (newPackage) {
12046                    mPendingBroadcasts.put(userId, packageName, components);
12047                }
12048                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12049                    // Schedule a message
12050                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12051                }
12052            }
12053        }
12054
12055        long callingId = Binder.clearCallingIdentity();
12056        try {
12057            if (sendNow) {
12058                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12059                sendPackageChangedBroadcast(packageName,
12060                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12061            }
12062        } finally {
12063            Binder.restoreCallingIdentity(callingId);
12064        }
12065    }
12066
12067    private void sendPackageChangedBroadcast(String packageName,
12068            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12069        if (DEBUG_INSTALL)
12070            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12071                    + componentNames);
12072        Bundle extras = new Bundle(4);
12073        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12074        String nameList[] = new String[componentNames.size()];
12075        componentNames.toArray(nameList);
12076        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12077        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12078        extras.putInt(Intent.EXTRA_UID, packageUid);
12079        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12080                new int[] {UserHandle.getUserId(packageUid)});
12081    }
12082
12083    @Override
12084    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12085        if (!sUserManager.exists(userId)) return;
12086        final int uid = Binder.getCallingUid();
12087        final int permission = mContext.checkCallingOrSelfPermission(
12088                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12089        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12090        enforceCrossUserPermission(uid, userId, true, "stop package");
12091        // writer
12092        synchronized (mPackages) {
12093            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12094                    uid, userId)) {
12095                scheduleWritePackageRestrictionsLocked(userId);
12096            }
12097        }
12098    }
12099
12100    @Override
12101    public String getInstallerPackageName(String packageName) {
12102        // reader
12103        synchronized (mPackages) {
12104            return mSettings.getInstallerPackageNameLPr(packageName);
12105        }
12106    }
12107
12108    @Override
12109    public int getApplicationEnabledSetting(String packageName, int userId) {
12110        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12111        int uid = Binder.getCallingUid();
12112        enforceCrossUserPermission(uid, userId, false, "get enabled");
12113        // reader
12114        synchronized (mPackages) {
12115            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12116        }
12117    }
12118
12119    @Override
12120    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12121        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12122        int uid = Binder.getCallingUid();
12123        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12124        // reader
12125        synchronized (mPackages) {
12126            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12127        }
12128    }
12129
12130    @Override
12131    public void enterSafeMode() {
12132        enforceSystemOrRoot("Only the system can request entering safe mode");
12133
12134        if (!mSystemReady) {
12135            mSafeMode = true;
12136        }
12137    }
12138
12139    @Override
12140    public void systemReady() {
12141        mSystemReady = true;
12142
12143        // Read the compatibilty setting when the system is ready.
12144        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12145                mContext.getContentResolver(),
12146                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12147        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12148        if (DEBUG_SETTINGS) {
12149            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12150        }
12151
12152        synchronized (mPackages) {
12153            // Verify that all of the preferred activity components actually
12154            // exist.  It is possible for applications to be updated and at
12155            // that point remove a previously declared activity component that
12156            // had been set as a preferred activity.  We try to clean this up
12157            // the next time we encounter that preferred activity, but it is
12158            // possible for the user flow to never be able to return to that
12159            // situation so here we do a sanity check to make sure we haven't
12160            // left any junk around.
12161            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12162            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12163                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12164                removed.clear();
12165                for (PreferredActivity pa : pir.filterSet()) {
12166                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12167                        removed.add(pa);
12168                    }
12169                }
12170                if (removed.size() > 0) {
12171                    for (int r=0; r<removed.size(); r++) {
12172                        PreferredActivity pa = removed.get(r);
12173                        Slog.w(TAG, "Removing dangling preferred activity: "
12174                                + pa.mPref.mComponent);
12175                        pir.removeFilter(pa);
12176                    }
12177                    mSettings.writePackageRestrictionsLPr(
12178                            mSettings.mPreferredActivities.keyAt(i));
12179                }
12180            }
12181        }
12182        sUserManager.systemReady();
12183    }
12184
12185    @Override
12186    public boolean isSafeMode() {
12187        return mSafeMode;
12188    }
12189
12190    @Override
12191    public boolean hasSystemUidErrors() {
12192        return mHasSystemUidErrors;
12193    }
12194
12195    static String arrayToString(int[] array) {
12196        StringBuffer buf = new StringBuffer(128);
12197        buf.append('[');
12198        if (array != null) {
12199            for (int i=0; i<array.length; i++) {
12200                if (i > 0) buf.append(", ");
12201                buf.append(array[i]);
12202            }
12203        }
12204        buf.append(']');
12205        return buf.toString();
12206    }
12207
12208    static class DumpState {
12209        public static final int DUMP_LIBS = 1 << 0;
12210        public static final int DUMP_FEATURES = 1 << 1;
12211        public static final int DUMP_RESOLVERS = 1 << 2;
12212        public static final int DUMP_PERMISSIONS = 1 << 3;
12213        public static final int DUMP_PACKAGES = 1 << 4;
12214        public static final int DUMP_SHARED_USERS = 1 << 5;
12215        public static final int DUMP_MESSAGES = 1 << 6;
12216        public static final int DUMP_PROVIDERS = 1 << 7;
12217        public static final int DUMP_VERIFIERS = 1 << 8;
12218        public static final int DUMP_PREFERRED = 1 << 9;
12219        public static final int DUMP_PREFERRED_XML = 1 << 10;
12220        public static final int DUMP_KEYSETS = 1 << 11;
12221        public static final int DUMP_VERSION = 1 << 12;
12222        public static final int DUMP_INSTALLS = 1 << 13;
12223
12224        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12225
12226        private int mTypes;
12227
12228        private int mOptions;
12229
12230        private boolean mTitlePrinted;
12231
12232        private SharedUserSetting mSharedUser;
12233
12234        public boolean isDumping(int type) {
12235            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12236                return true;
12237            }
12238
12239            return (mTypes & type) != 0;
12240        }
12241
12242        public void setDump(int type) {
12243            mTypes |= type;
12244        }
12245
12246        public boolean isOptionEnabled(int option) {
12247            return (mOptions & option) != 0;
12248        }
12249
12250        public void setOptionEnabled(int option) {
12251            mOptions |= option;
12252        }
12253
12254        public boolean onTitlePrinted() {
12255            final boolean printed = mTitlePrinted;
12256            mTitlePrinted = true;
12257            return printed;
12258        }
12259
12260        public boolean getTitlePrinted() {
12261            return mTitlePrinted;
12262        }
12263
12264        public void setTitlePrinted(boolean enabled) {
12265            mTitlePrinted = enabled;
12266        }
12267
12268        public SharedUserSetting getSharedUser() {
12269            return mSharedUser;
12270        }
12271
12272        public void setSharedUser(SharedUserSetting user) {
12273            mSharedUser = user;
12274        }
12275    }
12276
12277    @Override
12278    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12279        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12280                != PackageManager.PERMISSION_GRANTED) {
12281            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12282                    + Binder.getCallingPid()
12283                    + ", uid=" + Binder.getCallingUid()
12284                    + " without permission "
12285                    + android.Manifest.permission.DUMP);
12286            return;
12287        }
12288
12289        DumpState dumpState = new DumpState();
12290        boolean fullPreferred = false;
12291        boolean checkin = false;
12292
12293        String packageName = null;
12294
12295        int opti = 0;
12296        while (opti < args.length) {
12297            String opt = args[opti];
12298            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12299                break;
12300            }
12301            opti++;
12302            if ("-a".equals(opt)) {
12303                // Right now we only know how to print all.
12304            } else if ("-h".equals(opt)) {
12305                pw.println("Package manager dump options:");
12306                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12307                pw.println("    --checkin: dump for a checkin");
12308                pw.println("    -f: print details of intent filters");
12309                pw.println("    -h: print this help");
12310                pw.println("  cmd may be one of:");
12311                pw.println("    l[ibraries]: list known shared libraries");
12312                pw.println("    f[ibraries]: list device features");
12313                pw.println("    k[eysets]: print known keysets");
12314                pw.println("    r[esolvers]: dump intent resolvers");
12315                pw.println("    perm[issions]: dump permissions");
12316                pw.println("    pref[erred]: print preferred package settings");
12317                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12318                pw.println("    prov[iders]: dump content providers");
12319                pw.println("    p[ackages]: dump installed packages");
12320                pw.println("    s[hared-users]: dump shared user IDs");
12321                pw.println("    m[essages]: print collected runtime messages");
12322                pw.println("    v[erifiers]: print package verifier info");
12323                pw.println("    version: print database version info");
12324                pw.println("    write: write current settings now");
12325                pw.println("    <package.name>: info about given package");
12326                pw.println("    installs: details about install sessions");
12327                return;
12328            } else if ("--checkin".equals(opt)) {
12329                checkin = true;
12330            } else if ("-f".equals(opt)) {
12331                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12332            } else {
12333                pw.println("Unknown argument: " + opt + "; use -h for help");
12334            }
12335        }
12336
12337        // Is the caller requesting to dump a particular piece of data?
12338        if (opti < args.length) {
12339            String cmd = args[opti];
12340            opti++;
12341            // Is this a package name?
12342            if ("android".equals(cmd) || cmd.contains(".")) {
12343                packageName = cmd;
12344                // When dumping a single package, we always dump all of its
12345                // filter information since the amount of data will be reasonable.
12346                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12347            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12348                dumpState.setDump(DumpState.DUMP_LIBS);
12349            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12350                dumpState.setDump(DumpState.DUMP_FEATURES);
12351            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12352                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12353            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12354                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12355            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12356                dumpState.setDump(DumpState.DUMP_PREFERRED);
12357            } else if ("preferred-xml".equals(cmd)) {
12358                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12359                if (opti < args.length && "--full".equals(args[opti])) {
12360                    fullPreferred = true;
12361                    opti++;
12362                }
12363            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12364                dumpState.setDump(DumpState.DUMP_PACKAGES);
12365            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12366                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12367            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12368                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12369            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12370                dumpState.setDump(DumpState.DUMP_MESSAGES);
12371            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12372                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12373            } else if ("version".equals(cmd)) {
12374                dumpState.setDump(DumpState.DUMP_VERSION);
12375            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12376                dumpState.setDump(DumpState.DUMP_KEYSETS);
12377            } else if ("write".equals(cmd)) {
12378                synchronized (mPackages) {
12379                    mSettings.writeLPr();
12380                    pw.println("Settings written.");
12381                    return;
12382                }
12383            } else if ("installs".equals(cmd)) {
12384                dumpState.setDump(DumpState.DUMP_INSTALLS);
12385            }
12386        }
12387
12388        if (checkin) {
12389            pw.println("vers,1");
12390        }
12391
12392        // reader
12393        synchronized (mPackages) {
12394            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12395                if (!checkin) {
12396                    if (dumpState.onTitlePrinted())
12397                        pw.println();
12398                    pw.println("Database versions:");
12399                    pw.print("  SDK Version:");
12400                    pw.print(" internal=");
12401                    pw.print(mSettings.mInternalSdkPlatform);
12402                    pw.print(" external=");
12403                    pw.println(mSettings.mExternalSdkPlatform);
12404                    pw.print("  DB Version:");
12405                    pw.print(" internal=");
12406                    pw.print(mSettings.mInternalDatabaseVersion);
12407                    pw.print(" external=");
12408                    pw.println(mSettings.mExternalDatabaseVersion);
12409                }
12410            }
12411
12412            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12413                if (!checkin) {
12414                    if (dumpState.onTitlePrinted())
12415                        pw.println();
12416                    pw.println("Verifiers:");
12417                    pw.print("  Required: ");
12418                    pw.print(mRequiredVerifierPackage);
12419                    pw.print(" (uid=");
12420                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12421                    pw.println(")");
12422                } else if (mRequiredVerifierPackage != null) {
12423                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12424                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12425                }
12426            }
12427
12428            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12429                boolean printedHeader = false;
12430                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12431                while (it.hasNext()) {
12432                    String name = it.next();
12433                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12434                    if (!checkin) {
12435                        if (!printedHeader) {
12436                            if (dumpState.onTitlePrinted())
12437                                pw.println();
12438                            pw.println("Libraries:");
12439                            printedHeader = true;
12440                        }
12441                        pw.print("  ");
12442                    } else {
12443                        pw.print("lib,");
12444                    }
12445                    pw.print(name);
12446                    if (!checkin) {
12447                        pw.print(" -> ");
12448                    }
12449                    if (ent.path != null) {
12450                        if (!checkin) {
12451                            pw.print("(jar) ");
12452                            pw.print(ent.path);
12453                        } else {
12454                            pw.print(",jar,");
12455                            pw.print(ent.path);
12456                        }
12457                    } else {
12458                        if (!checkin) {
12459                            pw.print("(apk) ");
12460                            pw.print(ent.apk);
12461                        } else {
12462                            pw.print(",apk,");
12463                            pw.print(ent.apk);
12464                        }
12465                    }
12466                    pw.println();
12467                }
12468            }
12469
12470            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12471                if (dumpState.onTitlePrinted())
12472                    pw.println();
12473                if (!checkin) {
12474                    pw.println("Features:");
12475                }
12476                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12477                while (it.hasNext()) {
12478                    String name = it.next();
12479                    if (!checkin) {
12480                        pw.print("  ");
12481                    } else {
12482                        pw.print("feat,");
12483                    }
12484                    pw.println(name);
12485                }
12486            }
12487
12488            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12489                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12490                        : "Activity Resolver Table:", "  ", packageName,
12491                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12492                    dumpState.setTitlePrinted(true);
12493                }
12494                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12495                        : "Receiver Resolver Table:", "  ", packageName,
12496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12497                    dumpState.setTitlePrinted(true);
12498                }
12499                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12500                        : "Service Resolver Table:", "  ", packageName,
12501                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12502                    dumpState.setTitlePrinted(true);
12503                }
12504                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12505                        : "Provider Resolver Table:", "  ", packageName,
12506                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12507                    dumpState.setTitlePrinted(true);
12508                }
12509            }
12510
12511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12512                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12513                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12514                    int user = mSettings.mPreferredActivities.keyAt(i);
12515                    if (pir.dump(pw,
12516                            dumpState.getTitlePrinted()
12517                                ? "\nPreferred Activities User " + user + ":"
12518                                : "Preferred Activities User " + user + ":", "  ",
12519                            packageName, true)) {
12520                        dumpState.setTitlePrinted(true);
12521                    }
12522                }
12523            }
12524
12525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12526                pw.flush();
12527                FileOutputStream fout = new FileOutputStream(fd);
12528                BufferedOutputStream str = new BufferedOutputStream(fout);
12529                XmlSerializer serializer = new FastXmlSerializer();
12530                try {
12531                    serializer.setOutput(str, "utf-8");
12532                    serializer.startDocument(null, true);
12533                    serializer.setFeature(
12534                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12535                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12536                    serializer.endDocument();
12537                    serializer.flush();
12538                } catch (IllegalArgumentException e) {
12539                    pw.println("Failed writing: " + e);
12540                } catch (IllegalStateException e) {
12541                    pw.println("Failed writing: " + e);
12542                } catch (IOException e) {
12543                    pw.println("Failed writing: " + e);
12544                }
12545            }
12546
12547            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12548                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12549                if (packageName == null) {
12550                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12551                        if (iperm == 0) {
12552                            if (dumpState.onTitlePrinted())
12553                                pw.println();
12554                            pw.println("AppOp Permissions:");
12555                        }
12556                        pw.print("  AppOp Permission ");
12557                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12558                        pw.println(":");
12559                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12560                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12561                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12562                        }
12563                    }
12564                }
12565            }
12566
12567            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12568                boolean printedSomething = false;
12569                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12570                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12571                        continue;
12572                    }
12573                    if (!printedSomething) {
12574                        if (dumpState.onTitlePrinted())
12575                            pw.println();
12576                        pw.println("Registered ContentProviders:");
12577                        printedSomething = true;
12578                    }
12579                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12580                    pw.print("    "); pw.println(p.toString());
12581                }
12582                printedSomething = false;
12583                for (Map.Entry<String, PackageParser.Provider> entry :
12584                        mProvidersByAuthority.entrySet()) {
12585                    PackageParser.Provider p = entry.getValue();
12586                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12587                        continue;
12588                    }
12589                    if (!printedSomething) {
12590                        if (dumpState.onTitlePrinted())
12591                            pw.println();
12592                        pw.println("ContentProvider Authorities:");
12593                        printedSomething = true;
12594                    }
12595                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12596                    pw.print("    "); pw.println(p.toString());
12597                    if (p.info != null && p.info.applicationInfo != null) {
12598                        final String appInfo = p.info.applicationInfo.toString();
12599                        pw.print("      applicationInfo="); pw.println(appInfo);
12600                    }
12601                }
12602            }
12603
12604            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12605                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12606            }
12607
12608            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12609                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12610            }
12611
12612            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12613                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12614            }
12615
12616            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12617                if (dumpState.onTitlePrinted()) pw.println();
12618                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12619            }
12620
12621            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12622                if (dumpState.onTitlePrinted()) pw.println();
12623                mSettings.dumpReadMessagesLPr(pw, dumpState);
12624
12625                pw.println();
12626                pw.println("Package warning messages:");
12627                final File fname = getSettingsProblemFile();
12628                FileInputStream in = null;
12629                try {
12630                    in = new FileInputStream(fname);
12631                    final int avail = in.available();
12632                    final byte[] data = new byte[avail];
12633                    in.read(data);
12634                    pw.print(new String(data));
12635                } catch (FileNotFoundException e) {
12636                } catch (IOException e) {
12637                } finally {
12638                    if (in != null) {
12639                        try {
12640                            in.close();
12641                        } catch (IOException e) {
12642                        }
12643                    }
12644                }
12645            }
12646        }
12647    }
12648
12649    // ------- apps on sdcard specific code -------
12650    static final boolean DEBUG_SD_INSTALL = false;
12651
12652    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12653
12654    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12655
12656    private boolean mMediaMounted = false;
12657
12658    private String getEncryptKey() {
12659        try {
12660            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12661                    SD_ENCRYPTION_KEYSTORE_NAME);
12662            if (sdEncKey == null) {
12663                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12664                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12665                if (sdEncKey == null) {
12666                    Slog.e(TAG, "Failed to create encryption keys");
12667                    return null;
12668                }
12669            }
12670            return sdEncKey;
12671        } catch (NoSuchAlgorithmException nsae) {
12672            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12673            return null;
12674        } catch (IOException ioe) {
12675            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12676            return null;
12677        }
12678
12679    }
12680
12681    /* package */static String getTempContainerId() {
12682        int tmpIdx = 1;
12683        String list[] = PackageHelper.getSecureContainerList();
12684        if (list != null) {
12685            for (final String name : list) {
12686                // Ignore null and non-temporary container entries
12687                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12688                    continue;
12689                }
12690
12691                String subStr = name.substring(mTempContainerPrefix.length());
12692                try {
12693                    int cid = Integer.parseInt(subStr);
12694                    if (cid >= tmpIdx) {
12695                        tmpIdx = cid + 1;
12696                    }
12697                } catch (NumberFormatException e) {
12698                }
12699            }
12700        }
12701        return mTempContainerPrefix + tmpIdx;
12702    }
12703
12704    /*
12705     * Update media status on PackageManager.
12706     */
12707    @Override
12708    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12709        int callingUid = Binder.getCallingUid();
12710        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12711            throw new SecurityException("Media status can only be updated by the system");
12712        }
12713        // reader; this apparently protects mMediaMounted, but should probably
12714        // be a different lock in that case.
12715        synchronized (mPackages) {
12716            Log.i(TAG, "Updating external media status from "
12717                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12718                    + (mediaStatus ? "mounted" : "unmounted"));
12719            if (DEBUG_SD_INSTALL)
12720                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12721                        + ", mMediaMounted=" + mMediaMounted);
12722            if (mediaStatus == mMediaMounted) {
12723                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12724                        : 0, -1);
12725                mHandler.sendMessage(msg);
12726                return;
12727            }
12728            mMediaMounted = mediaStatus;
12729        }
12730        // Queue up an async operation since the package installation may take a
12731        // little while.
12732        mHandler.post(new Runnable() {
12733            public void run() {
12734                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12735            }
12736        });
12737    }
12738
12739    /**
12740     * Called by MountService when the initial ASECs to scan are available.
12741     * Should block until all the ASEC containers are finished being scanned.
12742     */
12743    public void scanAvailableAsecs() {
12744        updateExternalMediaStatusInner(true, false, false);
12745        if (mShouldRestoreconData) {
12746            SELinuxMMAC.setRestoreconDone();
12747            mShouldRestoreconData = false;
12748        }
12749    }
12750
12751    /*
12752     * Collect information of applications on external media, map them against
12753     * existing containers and update information based on current mount status.
12754     * Please note that we always have to report status if reportStatus has been
12755     * set to true especially when unloading packages.
12756     */
12757    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12758            boolean externalStorage) {
12759        // Collection of uids
12760        int uidArr[] = null;
12761        // Collection of stale containers
12762        HashSet<String> removeCids = new HashSet<String>();
12763        // Collection of packages on external media with valid containers.
12764        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12765        // Get list of secure containers.
12766        final String list[] = PackageHelper.getSecureContainerList();
12767        if (list == null || list.length == 0) {
12768            Log.i(TAG, "No secure containers on sdcard");
12769        } else {
12770            // Process list of secure containers and categorize them
12771            // as active or stale based on their package internal state.
12772            int uidList[] = new int[list.length];
12773            int num = 0;
12774            // reader
12775            synchronized (mPackages) {
12776                for (String cid : list) {
12777                    if (DEBUG_SD_INSTALL)
12778                        Log.i(TAG, "Processing container " + cid);
12779                    String pkgName = getAsecPackageName(cid);
12780                    if (pkgName == null) {
12781                        if (DEBUG_SD_INSTALL)
12782                            Log.i(TAG, "Container : " + cid + " stale");
12783                        removeCids.add(cid);
12784                        continue;
12785                    }
12786                    if (DEBUG_SD_INSTALL)
12787                        Log.i(TAG, "Looking for pkg : " + pkgName);
12788
12789                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12790                    if (ps == null) {
12791                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12792                        removeCids.add(cid);
12793                        continue;
12794                    }
12795
12796                    /*
12797                     * Skip packages that are not external if we're unmounting
12798                     * external storage.
12799                     */
12800                    if (externalStorage && !isMounted && !isExternal(ps)) {
12801                        continue;
12802                    }
12803
12804                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12805                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12806                    // The package status is changed only if the code path
12807                    // matches between settings and the container id.
12808                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12809                        if (DEBUG_SD_INSTALL) {
12810                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12811                                    + " at code path: " + ps.codePathString);
12812                        }
12813
12814                        // We do have a valid package installed on sdcard
12815                        processCids.put(args, ps.codePathString);
12816                        final int uid = ps.appId;
12817                        if (uid != -1) {
12818                            uidList[num++] = uid;
12819                        }
12820                    } else {
12821                        Log.i(TAG, "Deleting stale container for " + cid);
12822                        removeCids.add(cid);
12823                    }
12824                }
12825            }
12826
12827            if (num > 0) {
12828                // Sort uid list
12829                Arrays.sort(uidList, 0, num);
12830                // Throw away duplicates
12831                uidArr = new int[num];
12832                uidArr[0] = uidList[0];
12833                int di = 0;
12834                for (int i = 1; i < num; i++) {
12835                    if (uidList[i - 1] != uidList[i]) {
12836                        uidArr[di++] = uidList[i];
12837                    }
12838                }
12839            }
12840        }
12841        // Process packages with valid entries.
12842        if (isMounted) {
12843            if (DEBUG_SD_INSTALL)
12844                Log.i(TAG, "Loading packages");
12845            loadMediaPackages(processCids, uidArr, removeCids);
12846            startCleaningPackages();
12847        } else {
12848            if (DEBUG_SD_INSTALL)
12849                Log.i(TAG, "Unloading packages");
12850            unloadMediaPackages(processCids, uidArr, reportStatus);
12851        }
12852    }
12853
12854   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12855           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12856        int size = pkgList.size();
12857        if (size > 0) {
12858            // Send broadcasts here
12859            Bundle extras = new Bundle();
12860            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12861                    .toArray(new String[size]));
12862            if (uidArr != null) {
12863                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12864            }
12865            if (replacing) {
12866                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12867            }
12868            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12869                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12870            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12871        }
12872    }
12873
12874   /*
12875     * Look at potentially valid container ids from processCids If package
12876     * information doesn't match the one on record or package scanning fails,
12877     * the cid is added to list of removeCids. We currently don't delete stale
12878     * containers.
12879     */
12880   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12881            HashSet<String> removeCids) {
12882        ArrayList<String> pkgList = new ArrayList<String>();
12883        Set<AsecInstallArgs> keys = processCids.keySet();
12884        boolean doGc = false;
12885        for (AsecInstallArgs args : keys) {
12886            String codePath = processCids.get(args);
12887            if (DEBUG_SD_INSTALL)
12888                Log.i(TAG, "Loading container : " + args.cid);
12889            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12890            try {
12891                // Make sure there are no container errors first.
12892                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12893                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12894                            + " when installing from sdcard");
12895                    continue;
12896                }
12897                // Check code path here.
12898                if (codePath == null || !codePath.equals(args.getCodePath())) {
12899                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12900                            + " does not match one in settings " + codePath);
12901                    continue;
12902                }
12903                // Parse package
12904                int parseFlags = mDefParseFlags;
12905                if (args.isExternal()) {
12906                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12907                }
12908                if (args.isFwdLocked()) {
12909                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12910                }
12911
12912                doGc = true;
12913                synchronized (mInstallLock) {
12914                    PackageParser.Package pkg = null;
12915                    try {
12916                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12917                    } catch (PackageManagerException e) {
12918                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12919                    }
12920                    // Scan the package
12921                    if (pkg != null) {
12922                        /*
12923                         * TODO why is the lock being held? doPostInstall is
12924                         * called in other places without the lock. This needs
12925                         * to be straightened out.
12926                         */
12927                        // writer
12928                        synchronized (mPackages) {
12929                            retCode = PackageManager.INSTALL_SUCCEEDED;
12930                            pkgList.add(pkg.packageName);
12931                            // Post process args
12932                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12933                                    pkg.applicationInfo.uid);
12934                        }
12935                    } else {
12936                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12937                    }
12938                }
12939
12940            } finally {
12941                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12942                    // Don't destroy container here. Wait till gc clears things
12943                    // up.
12944                    removeCids.add(args.cid);
12945                }
12946            }
12947        }
12948        // writer
12949        synchronized (mPackages) {
12950            // If the platform SDK has changed since the last time we booted,
12951            // we need to re-grant app permission to catch any new ones that
12952            // appear. This is really a hack, and means that apps can in some
12953            // cases get permissions that the user didn't initially explicitly
12954            // allow... it would be nice to have some better way to handle
12955            // this situation.
12956            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12957            if (regrantPermissions)
12958                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12959                        + mSdkVersion + "; regranting permissions for external storage");
12960            mSettings.mExternalSdkPlatform = mSdkVersion;
12961
12962            // Make sure group IDs have been assigned, and any permission
12963            // changes in other apps are accounted for
12964            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12965                    | (regrantPermissions
12966                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12967                            : 0));
12968
12969            mSettings.updateExternalDatabaseVersion();
12970
12971            // can downgrade to reader
12972            // Persist settings
12973            mSettings.writeLPr();
12974        }
12975        // Send a broadcast to let everyone know we are done processing
12976        if (pkgList.size() > 0) {
12977            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12978        }
12979        // Force gc to avoid any stale parser references that we might have.
12980        if (doGc) {
12981            Runtime.getRuntime().gc();
12982        }
12983        // List stale containers and destroy stale temporary containers.
12984        if (removeCids != null) {
12985            for (String cid : removeCids) {
12986                if (cid.startsWith(mTempContainerPrefix)) {
12987                    Log.i(TAG, "Destroying stale temporary container " + cid);
12988                    PackageHelper.destroySdDir(cid);
12989                } else {
12990                    Log.w(TAG, "Container " + cid + " is stale");
12991               }
12992           }
12993        }
12994    }
12995
12996   /*
12997     * Utility method to unload a list of specified containers
12998     */
12999    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13000        // Just unmount all valid containers.
13001        for (AsecInstallArgs arg : cidArgs) {
13002            synchronized (mInstallLock) {
13003                arg.doPostDeleteLI(false);
13004           }
13005       }
13006   }
13007
13008    /*
13009     * Unload packages mounted on external media. This involves deleting package
13010     * data from internal structures, sending broadcasts about diabled packages,
13011     * gc'ing to free up references, unmounting all secure containers
13012     * corresponding to packages on external media, and posting a
13013     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13014     * that we always have to post this message if status has been requested no
13015     * matter what.
13016     */
13017    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
13018            final boolean reportStatus) {
13019        if (DEBUG_SD_INSTALL)
13020            Log.i(TAG, "unloading media packages");
13021        ArrayList<String> pkgList = new ArrayList<String>();
13022        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13023        final Set<AsecInstallArgs> keys = processCids.keySet();
13024        for (AsecInstallArgs args : keys) {
13025            String pkgName = args.getPackageName();
13026            if (DEBUG_SD_INSTALL)
13027                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13028            // Delete package internally
13029            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13030            synchronized (mInstallLock) {
13031                boolean res = deletePackageLI(pkgName, null, false, null, null,
13032                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13033                if (res) {
13034                    pkgList.add(pkgName);
13035                } else {
13036                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13037                    failedList.add(args);
13038                }
13039            }
13040        }
13041
13042        // reader
13043        synchronized (mPackages) {
13044            // We didn't update the settings after removing each package;
13045            // write them now for all packages.
13046            mSettings.writeLPr();
13047        }
13048
13049        // We have to absolutely send UPDATED_MEDIA_STATUS only
13050        // after confirming that all the receivers processed the ordered
13051        // broadcast when packages get disabled, force a gc to clean things up.
13052        // and unload all the containers.
13053        if (pkgList.size() > 0) {
13054            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13055                    new IIntentReceiver.Stub() {
13056                public void performReceive(Intent intent, int resultCode, String data,
13057                        Bundle extras, boolean ordered, boolean sticky,
13058                        int sendingUser) throws RemoteException {
13059                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13060                            reportStatus ? 1 : 0, 1, keys);
13061                    mHandler.sendMessage(msg);
13062                }
13063            });
13064        } else {
13065            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13066                    keys);
13067            mHandler.sendMessage(msg);
13068        }
13069    }
13070
13071    /** Binder call */
13072    @Override
13073    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13074            final int flags) {
13075        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13076        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13077        int returnCode = PackageManager.MOVE_SUCCEEDED;
13078        int currFlags = 0;
13079        int newFlags = 0;
13080        // reader
13081        synchronized (mPackages) {
13082            PackageParser.Package pkg = mPackages.get(packageName);
13083            if (pkg == null) {
13084                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13085            } else {
13086                // Disable moving fwd locked apps and system packages
13087                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13088                    Slog.w(TAG, "Cannot move system application");
13089                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13090                } else if (pkg.mOperationPending) {
13091                    Slog.w(TAG, "Attempt to move package which has pending operations");
13092                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13093                } else {
13094                    // Find install location first
13095                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13096                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13097                        Slog.w(TAG, "Ambigous flags specified for move location.");
13098                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13099                    } else {
13100                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
13101                                : PackageManager.INSTALL_INTERNAL;
13102                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
13103                                : PackageManager.INSTALL_INTERNAL;
13104
13105                        if (newFlags == currFlags) {
13106                            Slog.w(TAG, "No move required. Trying to move to same location");
13107                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13108                        } else {
13109                            if (isForwardLocked(pkg)) {
13110                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13111                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13112                            }
13113                        }
13114                    }
13115                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13116                        pkg.mOperationPending = true;
13117                    }
13118                }
13119            }
13120
13121            /*
13122             * TODO this next block probably shouldn't be inside the lock. We
13123             * can't guarantee these won't change after this is fired off
13124             * anyway.
13125             */
13126            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13127                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
13128                        returnCode);
13129            } else {
13130                Message msg = mHandler.obtainMessage(INIT_COPY);
13131                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13132                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13133                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13134                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13135                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13136                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13137                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13138                msg.obj = mp;
13139                mHandler.sendMessage(msg);
13140            }
13141        }
13142    }
13143
13144    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13145        // Queue up an async operation since the package deletion may take a
13146        // little while.
13147        mHandler.post(new Runnable() {
13148            public void run() {
13149                // TODO fix this; this does nothing.
13150                mHandler.removeCallbacks(this);
13151                int returnCode = currentStatus;
13152                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13153                    int uidArr[] = null;
13154                    ArrayList<String> pkgList = null;
13155                    synchronized (mPackages) {
13156                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13157                        if (pkg == null) {
13158                            Slog.w(TAG, " Package " + mp.packageName
13159                                    + " doesn't exist. Aborting move");
13160                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13161                        } else if (!mp.srcArgs.getCodePath().equals(
13162                                pkg.applicationInfo.getCodePath())) {
13163                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13164                                    + mp.srcArgs.getCodePath() + " to "
13165                                    + pkg.applicationInfo.getCodePath()
13166                                    + " Aborting move and returning error");
13167                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13168                        } else {
13169                            uidArr = new int[] {
13170                                pkg.applicationInfo.uid
13171                            };
13172                            pkgList = new ArrayList<String>();
13173                            pkgList.add(mp.packageName);
13174                        }
13175                    }
13176                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13177                        // Send resources unavailable broadcast
13178                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13179                        // Update package code and resource paths
13180                        synchronized (mInstallLock) {
13181                            synchronized (mPackages) {
13182                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13183                                // Recheck for package again.
13184                                if (pkg == null) {
13185                                    Slog.w(TAG, " Package " + mp.packageName
13186                                            + " doesn't exist. Aborting move");
13187                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13188                                } else if (!mp.srcArgs.getCodePath().equals(
13189                                        pkg.applicationInfo.getCodePath())) {
13190                                    Slog.w(TAG, "Package " + mp.packageName
13191                                            + " code path changed from " + mp.srcArgs.getCodePath()
13192                                            + " to " + pkg.applicationInfo.getCodePath()
13193                                            + " Aborting move and returning error");
13194                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13195                                } else {
13196                                    final String oldCodePath = pkg.codePath;
13197                                    final String newCodePath = mp.targetArgs.getCodePath();
13198                                    final String newResPath = mp.targetArgs.getResourcePath();
13199                                    // TODO: This assumes the new style of installation.
13200                                    // should we look at legacyNativeLibraryPath ?
13201                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13202                                    final File newNativeDir = new File(newNativeRoot);
13203
13204                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13205                                        // TODO(multiArch): Fix this so that it looks at the existing
13206                                        // recorded CPU abis from the package. There's no need for a separate
13207                                        // round of ABI scanning here.
13208                                        NativeLibraryHelper.Handle handle = null;
13209                                        try {
13210                                            handle = NativeLibraryHelper.Handle.create(
13211                                                    new File(newCodePath));
13212                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13213                                                    handle, Build.SUPPORTED_ABIS);
13214                                            if (abi >= 0) {
13215                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13216                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13217                                            }
13218                                        } catch (IOException ioe) {
13219                                            Slog.w(TAG, "Unable to extract native libs for package :"
13220                                                    + mp.packageName, ioe);
13221                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13222                                        } finally {
13223                                            IoUtils.closeQuietly(handle);
13224                                        }
13225                                    }
13226
13227                                    final int[] users = sUserManager.getUserIds();
13228                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13229                                        for (int user : users) {
13230                                            // TODO(multiArch): Fix this so that it links to the
13231                                            // correct directory. We're currently pointing to root. but we
13232                                            // must point to the arch specific subdirectory (if applicable).
13233                                            //
13234                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13235                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13236                                                    newNativeRoot, user) < 0) {
13237                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13238                                            }
13239                                        }
13240                                    }
13241
13242                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13243                                        pkg.codePath = newCodePath;
13244                                        pkg.baseCodePath = newCodePath;
13245                                        // Move dex files around
13246                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13247                                            // Moving of dex files failed. Set
13248                                            // error code and abort move.
13249                                            pkg.codePath = oldCodePath;
13250                                            pkg.baseCodePath = oldCodePath;
13251                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13252                                        }
13253                                    }
13254
13255                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13256                                        pkg.applicationInfo.setCodePath(newCodePath);
13257                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13258                                        pkg.applicationInfo.setSplitCodePaths(null);
13259                                        pkg.applicationInfo.setResourcePath(newResPath);
13260                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13261                                        pkg.applicationInfo.setSplitResourcePaths(null);
13262
13263                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13264                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13265                                        ps.codePathString = ps.codePath.getPath();
13266                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13267                                        ps.resourcePathString = ps.resourcePath.getPath();
13268
13269                                        // Note that we don't have to recalculate the primary and secondary
13270                                        // CPU ABIs because they must already have been calculated during the
13271                                        // initial install of the app.
13272                                        ps.legacyNativeLibraryPathString = null;
13273
13274                                        // Set the application info flag
13275                                        // correctly.
13276                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13277                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13278                                        } else {
13279                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13280                                        }
13281                                        ps.setFlags(pkg.applicationInfo.flags);
13282                                        mAppDirs.remove(oldCodePath);
13283                                        mAppDirs.put(newCodePath, pkg);
13284                                        // Persist settings
13285                                        mSettings.writeLPr();
13286                                    }
13287                                }
13288                            }
13289                        }
13290                        // Send resources available broadcast
13291                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13292                    }
13293                }
13294                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13295                    // Clean up failed installation
13296                    if (mp.targetArgs != null) {
13297                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13298                                -1);
13299                    }
13300                } else {
13301                    // Force a gc to clear things up.
13302                    Runtime.getRuntime().gc();
13303                    // Delete older code
13304                    synchronized (mInstallLock) {
13305                        mp.srcArgs.doPostDeleteLI(true);
13306                    }
13307                }
13308
13309                // Allow more operations on this file if we didn't fail because
13310                // an operation was already pending for this package.
13311                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13312                    synchronized (mPackages) {
13313                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13314                        if (pkg != null) {
13315                            pkg.mOperationPending = false;
13316                       }
13317                   }
13318                }
13319
13320                IPackageMoveObserver observer = mp.observer;
13321                if (observer != null) {
13322                    try {
13323                        observer.packageMoved(mp.packageName, returnCode);
13324                    } catch (RemoteException e) {
13325                        Log.i(TAG, "Observer no longer exists.");
13326                    }
13327                }
13328            }
13329        });
13330    }
13331
13332    @Override
13333    public boolean setInstallLocation(int loc) {
13334        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13335                null);
13336        if (getInstallLocation() == loc) {
13337            return true;
13338        }
13339        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13340                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13341            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13342                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13343            return true;
13344        }
13345        return false;
13346   }
13347
13348    @Override
13349    public int getInstallLocation() {
13350        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13351                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13352                PackageHelper.APP_INSTALL_AUTO);
13353    }
13354
13355    /** Called by UserManagerService */
13356    void cleanUpUserLILPw(int userHandle) {
13357        mDirtyUsers.remove(userHandle);
13358        mSettings.removeUserLPw(userHandle);
13359        mPendingBroadcasts.remove(userHandle);
13360        if (mInstaller != null) {
13361            // Technically, we shouldn't be doing this with the package lock
13362            // held.  However, this is very rare, and there is already so much
13363            // other disk I/O going on, that we'll let it slide for now.
13364            mInstaller.removeUserDataDirs(userHandle);
13365        }
13366        mUserNeedsBadging.delete(userHandle);
13367    }
13368
13369    /** Called by UserManagerService */
13370    void createNewUserLILPw(int userHandle, File path) {
13371        if (mInstaller != null) {
13372            mInstaller.createUserConfig(userHandle);
13373            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13374        }
13375    }
13376
13377    @Override
13378    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13379        mContext.enforceCallingOrSelfPermission(
13380                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13381                "Only package verification agents can read the verifier device identity");
13382
13383        synchronized (mPackages) {
13384            return mSettings.getVerifierDeviceIdentityLPw();
13385        }
13386    }
13387
13388    @Override
13389    public void setPermissionEnforced(String permission, boolean enforced) {
13390        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13391        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13392            synchronized (mPackages) {
13393                if (mSettings.mReadExternalStorageEnforced == null
13394                        || mSettings.mReadExternalStorageEnforced != enforced) {
13395                    mSettings.mReadExternalStorageEnforced = enforced;
13396                    mSettings.writeLPr();
13397                }
13398            }
13399            // kill any non-foreground processes so we restart them and
13400            // grant/revoke the GID.
13401            final IActivityManager am = ActivityManagerNative.getDefault();
13402            if (am != null) {
13403                final long token = Binder.clearCallingIdentity();
13404                try {
13405                    am.killProcessesBelowForeground("setPermissionEnforcement");
13406                } catch (RemoteException e) {
13407                } finally {
13408                    Binder.restoreCallingIdentity(token);
13409                }
13410            }
13411        } else {
13412            throw new IllegalArgumentException("No selective enforcement for " + permission);
13413        }
13414    }
13415
13416    @Override
13417    @Deprecated
13418    public boolean isPermissionEnforced(String permission) {
13419        return true;
13420    }
13421
13422    @Override
13423    public boolean isStorageLow() {
13424        final long token = Binder.clearCallingIdentity();
13425        try {
13426            final DeviceStorageMonitorInternal
13427                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13428            if (dsm != null) {
13429                return dsm.isMemoryLow();
13430            } else {
13431                return false;
13432            }
13433        } finally {
13434            Binder.restoreCallingIdentity(token);
13435        }
13436    }
13437
13438    @Override
13439    public IPackageInstaller getPackageInstaller() {
13440        return mInstallerService;
13441    }
13442
13443    private boolean userNeedsBadging(int userId) {
13444        int index = mUserNeedsBadging.indexOfKey(userId);
13445        if (index < 0) {
13446            final UserInfo userInfo;
13447            final long token = Binder.clearCallingIdentity();
13448            try {
13449                userInfo = sUserManager.getUserInfo(userId);
13450            } finally {
13451                Binder.restoreCallingIdentity(token);
13452            }
13453            final boolean b;
13454            if (userInfo != null && userInfo.isManagedProfile()) {
13455                b = true;
13456            } else {
13457                b = false;
13458            }
13459            mUserNeedsBadging.put(userId, b);
13460            return b;
13461        }
13462        return mUserNeedsBadging.valueAt(index);
13463    }
13464
13465    @Override
13466    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13467        if (packageName == null || alias == null) {
13468            return null;
13469        }
13470        synchronized(mPackages) {
13471            final PackageParser.Package pkg = mPackages.get(packageName);
13472            if (pkg == null) {
13473                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13474                throw new IllegalArgumentException("Unknown package: " + packageName);
13475            }
13476            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13477                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13478                throw new SecurityException("May not access KeySets defined by"
13479                        + " aliases in other applications.");
13480            }
13481            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13482            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13483        }
13484    }
13485
13486    @Override
13487    public KeySetHandle getSigningKeySet(String packageName) {
13488        if (packageName == null) {
13489            return null;
13490        }
13491        synchronized(mPackages) {
13492            final PackageParser.Package pkg = mPackages.get(packageName);
13493            if (pkg == null) {
13494                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13495                throw new IllegalArgumentException("Unknown package: " + packageName);
13496            }
13497            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13498                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13499                throw new SecurityException("May not access signing KeySet of other apps.");
13500            }
13501            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13502            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13503        }
13504    }
13505
13506    @Override
13507    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13508        if (packageName == null || ks == null) {
13509            return false;
13510        }
13511        synchronized(mPackages) {
13512            final PackageParser.Package pkg = mPackages.get(packageName);
13513            if (pkg == null) {
13514                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13515                throw new IllegalArgumentException("Unknown package: " + packageName);
13516            }
13517            if (ks instanceof KeySetHandle) {
13518                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13519                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13520            }
13521            return false;
13522        }
13523    }
13524
13525    @Override
13526    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13527        if (packageName == null || ks == null) {
13528            return false;
13529        }
13530        synchronized(mPackages) {
13531            final PackageParser.Package pkg = mPackages.get(packageName);
13532            if (pkg == null) {
13533                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13534                throw new IllegalArgumentException("Unknown package: " + packageName);
13535            }
13536            if (ks instanceof KeySetHandle) {
13537                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13538                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13539            }
13540            return false;
13541        }
13542    }
13543}
13544