PackageManagerService.java revision fa4533f3a07ebed479d2a0e7af7d6e03d4417d41
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.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.NativeLibraryHelper.ApkHandle;
44import com.android.internal.content.PackageHelper;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastPrintWriter;
47import com.android.internal.util.FastXmlSerializer;
48import com.android.internal.util.XmlUtils;
49import com.android.server.EventLogTags;
50import com.android.server.IntentResolver;
51import com.android.server.LocalServices;
52import com.android.server.ServiceThread;
53import com.android.server.Watchdog;
54import com.android.server.pm.Settings.DatabaseVersion;
55import com.android.server.storage.DeviceStorageMonitorInternal;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
61import android.app.ActivityManager;
62import android.app.ActivityManagerNative;
63import android.app.IActivityManager;
64import android.app.PackageInstallObserver;
65import android.app.admin.IDevicePolicyManager;
66import android.app.backup.IBackupManager;
67import android.content.BroadcastReceiver;
68import android.content.ComponentName;
69import android.content.Context;
70import android.content.IIntentReceiver;
71import android.content.Intent;
72import android.content.IntentFilter;
73import android.content.IntentSender;
74import android.content.IntentSender.SendIntentException;
75import android.content.ServiceConnection;
76import android.content.pm.ActivityInfo;
77import android.content.pm.ApplicationInfo;
78import android.content.pm.ContainerEncryptionParams;
79import android.content.pm.FeatureInfo;
80import android.content.pm.IPackageDataObserver;
81import android.content.pm.IPackageDeleteObserver;
82import android.content.pm.IPackageInstallObserver;
83import android.content.pm.IPackageInstallObserver2;
84import android.content.pm.IPackageInstaller;
85import android.content.pm.IPackageManager;
86import android.content.pm.IPackageMoveObserver;
87import android.content.pm.IPackageStatsObserver;
88import android.content.pm.InstrumentationInfo;
89import android.content.pm.ManifestDigest;
90import android.content.pm.PackageCleanItem;
91import android.content.pm.PackageInfo;
92import android.content.pm.PackageInfoLite;
93import android.content.pm.PackageManager;
94import android.content.pm.PackageParser.ActivityIntentInfo;
95import android.content.pm.PackageParser.PackageParserException;
96import android.content.pm.PackageParser;
97import android.content.pm.PackageStats;
98import android.content.pm.PackageUserState;
99import android.content.pm.ParceledListSlice;
100import android.content.pm.PermissionGroupInfo;
101import android.content.pm.PermissionInfo;
102import android.content.pm.ProviderInfo;
103import android.content.pm.ResolveInfo;
104import android.content.pm.ServiceInfo;
105import android.content.pm.Signature;
106import android.content.pm.VerificationParams;
107import android.content.pm.VerifierDeviceIdentity;
108import android.content.pm.VerifierInfo;
109import android.content.res.Resources;
110import android.hardware.display.DisplayManager;
111import android.net.Uri;
112import android.os.Binder;
113import android.os.Build;
114import android.os.Bundle;
115import android.os.Environment;
116import android.os.Environment.UserEnvironment;
117import android.os.FileObserver;
118import android.os.FileUtils;
119import android.os.Handler;
120import android.os.IBinder;
121import android.os.Looper;
122import android.os.Message;
123import android.os.Parcel;
124import android.os.ParcelFileDescriptor;
125import android.os.Process;
126import android.os.RemoteException;
127import android.os.SELinux;
128import android.os.ServiceManager;
129import android.os.SystemClock;
130import android.os.SystemProperties;
131import android.os.UserHandle;
132import android.os.UserManager;
133import android.security.KeyStore;
134import android.security.SystemKeyStore;
135import android.system.ErrnoException;
136import android.system.Os;
137import android.system.StructStat;
138import android.text.TextUtils;
139import android.util.ArraySet;
140import android.util.AtomicFile;
141import android.util.DisplayMetrics;
142import android.util.EventLog;
143import android.util.Log;
144import android.util.LogPrinter;
145import android.util.PrintStreamPrinter;
146import android.util.Slog;
147import android.util.SparseArray;
148import android.util.SparseBooleanArray;
149import android.util.Xml;
150import android.view.Display;
151
152import java.io.BufferedInputStream;
153import java.io.BufferedOutputStream;
154import java.io.File;
155import java.io.FileDescriptor;
156import java.io.FileInputStream;
157import java.io.FileNotFoundException;
158import java.io.FileOutputStream;
159import java.io.FileReader;
160import java.io.FilenameFilter;
161import java.io.IOException;
162import java.io.InputStream;
163import java.io.PrintWriter;
164import java.nio.charset.StandardCharsets;
165import java.security.NoSuchAlgorithmException;
166import java.security.PublicKey;
167import java.security.cert.CertificateEncodingException;
168import java.security.cert.CertificateException;
169import java.text.SimpleDateFormat;
170import java.util.ArrayList;
171import java.util.Arrays;
172import java.util.Collection;
173import java.util.Collections;
174import java.util.Comparator;
175import java.util.Date;
176import java.util.HashMap;
177import java.util.HashSet;
178import java.util.Iterator;
179import java.util.List;
180import java.util.Map;
181import java.util.Set;
182import java.util.concurrent.atomic.AtomicBoolean;
183import java.util.concurrent.atomic.AtomicLong;
184
185import dalvik.system.DexFile;
186import dalvik.system.StaleDexCacheError;
187import dalvik.system.VMRuntime;
188
189import libcore.io.IoUtils;
190
191/**
192 * Keep track of all those .apks everywhere.
193 *
194 * This is very central to the platform's security; please run the unit
195 * tests whenever making modifications here:
196 *
197mmm frameworks/base/tests/AndroidTests
198adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
199adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
200 *
201 * {@hide}
202 */
203public class PackageManagerService extends IPackageManager.Stub {
204    static final String TAG = "PackageManager";
205    static final boolean DEBUG_SETTINGS = false;
206    static final boolean DEBUG_PREFERRED = false;
207    static final boolean DEBUG_UPGRADE = false;
208    private static final boolean DEBUG_INSTALL = false;
209    private static final boolean DEBUG_REMOVE = false;
210    private static final boolean DEBUG_BROADCASTS = false;
211    private static final boolean DEBUG_SHOW_INFO = false;
212    private static final boolean DEBUG_PACKAGE_INFO = false;
213    private static final boolean DEBUG_INTENT_MATCHING = false;
214    private static final boolean DEBUG_PACKAGE_SCANNING = false;
215    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
216    private static final boolean DEBUG_VERIFY = false;
217    private static final boolean DEBUG_DEXOPT = false;
218
219    private static final int RADIO_UID = Process.PHONE_UID;
220    private static final int LOG_UID = Process.LOG_UID;
221    private static final int NFC_UID = Process.NFC_UID;
222    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
223    private static final int SHELL_UID = Process.SHELL_UID;
224
225    // Cap the size of permission trees that 3rd party apps can define
226    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
227
228    private static final int REMOVE_EVENTS =
229        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
230    private static final int ADD_EVENTS =
231        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
232
233    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
234    // Suffix used during package installation when copying/moving
235    // package apks to install directory.
236    private static final String INSTALL_PACKAGE_SUFFIX = "-";
237
238    static final int SCAN_MONITOR = 1<<0;
239    static final int SCAN_NO_DEX = 1<<1;
240    static final int SCAN_FORCE_DEX = 1<<2;
241    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
242    static final int SCAN_NEW_INSTALL = 1<<4;
243    static final int SCAN_NO_PATHS = 1<<5;
244    static final int SCAN_UPDATE_TIME = 1<<6;
245    static final int SCAN_DEFER_DEX = 1<<7;
246    static final int SCAN_BOOTING = 1<<8;
247    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
248    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
249
250    static final int REMOVE_CHATTY = 1<<16;
251
252    /**
253     * Timeout (in milliseconds) after which the watchdog should declare that
254     * our handler thread is wedged.  The usual default for such things is one
255     * minute but we sometimes do very lengthy I/O operations on this thread,
256     * such as installing multi-gigabyte applications, so ours needs to be longer.
257     */
258    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
259
260    /**
261     * Whether verification is enabled by default.
262     */
263    private static final boolean DEFAULT_VERIFY_ENABLE = true;
264
265    /**
266     * The default maximum time to wait for the verification agent to return in
267     * milliseconds.
268     */
269    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
270
271    /**
272     * The default response for package verification timeout.
273     *
274     * This can be either PackageManager.VERIFICATION_ALLOW or
275     * PackageManager.VERIFICATION_REJECT.
276     */
277    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
278
279    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
280
281    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
282            DEFAULT_CONTAINER_PACKAGE,
283            "com.android.defcontainer.DefaultContainerService");
284
285    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
286
287    private static final String LIB_DIR_NAME = "lib";
288    private static final String LIB64_DIR_NAME = "lib64";
289
290    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
291
292    static final String mTempContainerPrefix = "smdl2tmp";
293
294    private static String sPreferredInstructionSet;
295
296    final ServiceThread mHandlerThread;
297
298    private static final String IDMAP_PREFIX = "/data/resource-cache/";
299    private static final String IDMAP_SUFFIX = "@idmap";
300
301    final PackageHandler mHandler;
302
303    final int mSdkVersion = Build.VERSION.SDK_INT;
304
305    final Context mContext;
306    final boolean mFactoryTest;
307    final boolean mOnlyCore;
308    final DisplayMetrics mMetrics;
309    final int mDefParseFlags;
310    final String[] mSeparateProcesses;
311
312    // This is where all application persistent data goes.
313    final File mAppDataDir;
314
315    // This is where all application persistent data goes for secondary users.
316    final File mUserAppDataDir;
317
318    /** The location for ASEC container files on internal storage. */
319    final String mAsecInternalPath;
320
321    // This is the object monitoring the framework dir.
322    final FileObserver mFrameworkInstallObserver;
323
324    // This is the object monitoring the system app dir.
325    final FileObserver mSystemInstallObserver;
326
327    // This is the object monitoring the privileged system app dir.
328    final FileObserver mPrivilegedInstallObserver;
329
330    // This is the object monitoring the vendor app dir.
331    final FileObserver mVendorInstallObserver;
332
333    // This is the object monitoring the vendor overlay package dir.
334    final FileObserver mVendorOverlayInstallObserver;
335
336    // This is the object monitoring the OEM app dir.
337    final FileObserver mOemInstallObserver;
338
339    // This is the object monitoring mAppInstallDir.
340    final FileObserver mAppInstallObserver;
341
342    // This is the object monitoring mDrmAppPrivateInstallDir.
343    final FileObserver mDrmAppInstallObserver;
344
345    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
346    // LOCK HELD.  Can be called with mInstallLock held.
347    final Installer mInstaller;
348
349    final File mAppInstallDir;
350
351    /**
352     * Directory to which applications installed internally have native
353     * libraries copied.
354     */
355    private File mAppLibInstallDir;
356
357    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
358    // apps.
359    final File mDrmAppPrivateInstallDir;
360
361    final File mAppStagingDir;
362
363    // ----------------------------------------------------------------
364
365    // Lock for state used when installing and doing other long running
366    // operations.  Methods that must be called with this lock held have
367    // the suffix "LI".
368    final Object mInstallLock = new Object();
369
370    // These are the directories in the 3rd party applications installed dir
371    // that we have currently loaded packages from.  Keys are the application's
372    // installed zip file (absolute codePath), and values are Package.
373    final HashMap<String, PackageParser.Package> mAppDirs =
374            new HashMap<String, PackageParser.Package>();
375
376    // Information for the parser to write more useful error messages.
377    int mLastScanError;
378
379    // ----------------------------------------------------------------
380
381    // Keys are String (package name), values are Package.  This also serves
382    // as the lock for the global state.  Methods that must be called with
383    // this lock held have the prefix "LP".
384    final HashMap<String, PackageParser.Package> mPackages =
385            new HashMap<String, PackageParser.Package>();
386
387    // Tracks available target package names -> overlay package paths.
388    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
389        new HashMap<String, HashMap<String, PackageParser.Package>>();
390
391    final Settings mSettings;
392    boolean mRestoredSettings;
393
394    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
395    int[] mGlobalGids;
396
397    // These are the built-in uid -> permission mappings that were read from the
398    // etc/permissions.xml file.
399    final SparseArray<HashSet<String>> mSystemPermissions =
400            new SparseArray<HashSet<String>>();
401
402    static final class SharedLibraryEntry {
403        final String path;
404        final String apk;
405
406        SharedLibraryEntry(String _path, String _apk) {
407            path = _path;
408            apk = _apk;
409        }
410    }
411
412    // These are the built-in shared libraries that were read from the
413    // etc/permissions.xml file.
414    final HashMap<String, SharedLibraryEntry> mSharedLibraries
415            = new HashMap<String, SharedLibraryEntry>();
416
417    // These are the features this devices supports that were read from the
418    // etc/permissions.xml file.
419    final HashMap<String, FeatureInfo> mAvailableFeatures =
420            new HashMap<String, FeatureInfo>();
421
422    // If mac_permissions.xml was found for seinfo labeling.
423    boolean mFoundPolicyFile;
424
425    // If a recursive restorecon of /data/data/<pkg> is needed.
426    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
427
428    // All available activities, for your resolving pleasure.
429    final ActivityIntentResolver mActivities =
430            new ActivityIntentResolver();
431
432    // All available receivers, for your resolving pleasure.
433    final ActivityIntentResolver mReceivers =
434            new ActivityIntentResolver();
435
436    // All available services, for your resolving pleasure.
437    final ServiceIntentResolver mServices = new ServiceIntentResolver();
438
439    // All available providers, for your resolving pleasure.
440    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
441
442    // Mapping from provider base names (first directory in content URI codePath)
443    // to the provider information.
444    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
445            new HashMap<String, PackageParser.Provider>();
446
447    // Mapping from instrumentation class names to info about them.
448    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
449            new HashMap<ComponentName, PackageParser.Instrumentation>();
450
451    // Mapping from permission names to info about them.
452    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
453            new HashMap<String, PackageParser.PermissionGroup>();
454
455    // Packages whose data we have transfered into another package, thus
456    // should no longer exist.
457    final HashSet<String> mTransferedPackages = new HashSet<String>();
458
459    // Broadcast actions that are only available to the system.
460    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
461
462    /** List of packages waiting for verification. */
463    final SparseArray<PackageVerificationState> mPendingVerification
464            = new SparseArray<PackageVerificationState>();
465
466    final PackageInstallerService mInstallerService;
467
468    HashSet<PackageParser.Package> mDeferredDexOpt = null;
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    boolean mSystemReady;
474    boolean mSafeMode;
475    boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new HashMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsHistoricalPackageUsageAvailable = true;
625
626        boolean isHistoricalPackageUsageAvailable() {
627            return mIsHistoricalPackageUsageAvailable;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsHistoricalPackageUsageAvailable = false;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                args.observer.packageInstalled(res.name, res.returnCode);
1081                            } catch (RemoteException e) {
1082                                Slog.i(TAG, "Observer no longer exists.");
1083                            }
1084                        }
1085                        if (args.observer2 != null) {
1086                            try {
1087                                Bundle extras = extrasForInstallResult(res);
1088                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1089                            } catch (RemoteException e) {
1090                                Slog.i(TAG, "Observer no longer exists.");
1091                            }
1092                        }
1093                    } else {
1094                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1095                    }
1096                } break;
1097                case UPDATED_MEDIA_STATUS: {
1098                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1099                    boolean reportStatus = msg.arg1 == 1;
1100                    boolean doGc = msg.arg2 == 1;
1101                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1102                    if (doGc) {
1103                        // Force a gc to clear up stale containers.
1104                        Runtime.getRuntime().gc();
1105                    }
1106                    if (msg.obj != null) {
1107                        @SuppressWarnings("unchecked")
1108                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1109                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1110                        // Unload containers
1111                        unloadAllContainers(args);
1112                    }
1113                    if (reportStatus) {
1114                        try {
1115                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1116                            PackageHelper.getMountService().finishMediaUpdate();
1117                        } catch (RemoteException e) {
1118                            Log.e(TAG, "MountService not running?");
1119                        }
1120                    }
1121                } break;
1122                case WRITE_SETTINGS: {
1123                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124                    synchronized (mPackages) {
1125                        removeMessages(WRITE_SETTINGS);
1126                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1127                        mSettings.writeLPr();
1128                        mDirtyUsers.clear();
1129                    }
1130                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131                } break;
1132                case WRITE_PACKAGE_RESTRICTIONS: {
1133                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134                    synchronized (mPackages) {
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        for (int userId : mDirtyUsers) {
1137                            mSettings.writePackageRestrictionsLPr(userId);
1138                        }
1139                        mDirtyUsers.clear();
1140                    }
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142                } break;
1143                case CHECK_PENDING_VERIFICATION: {
1144                    final int verificationId = msg.arg1;
1145                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1146
1147                    if ((state != null) && !state.timeoutExtended()) {
1148                        final InstallArgs args = state.getInstallArgs();
1149                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of "
1156                                    + args.packageURI.toString());
1157                            state.setVerifierResponse(Binder.getCallingUid(),
1158                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1159                            broadcastPackageVerified(verificationId, args.packageURI,
1160                                    PackageManager.VERIFICATION_ALLOW,
1161                                    state.getInstallArgs().getUser());
1162                            try {
1163                                ret = args.copyApk(mContainerService, true);
1164                            } catch (RemoteException e) {
1165                                Slog.e(TAG, "Could not contact the ContainerService");
1166                            }
1167                        } else {
1168                            broadcastPackageVerified(verificationId, args.packageURI,
1169                                    PackageManager.VERIFICATION_REJECT,
1170                                    state.getInstallArgs().getUser());
1171                        }
1172
1173                        processPendingInstall(args, ret);
1174                        mHandler.sendEmptyMessage(MCS_UNBIND);
1175                    }
1176                    break;
1177                }
1178                case PACKAGE_VERIFIED: {
1179                    final int verificationId = msg.arg1;
1180
1181                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1182                    if (state == null) {
1183                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1184                        break;
1185                    }
1186
1187                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1188
1189                    state.setVerifierResponse(response.callerUid, response.code);
1190
1191                    if (state.isVerificationComplete()) {
1192                        mPendingVerification.remove(verificationId);
1193
1194                        final InstallArgs args = state.getInstallArgs();
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, args.packageURI,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final PackageManagerService main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mMetrics = new DisplayMetrics();
1299        mSettings = new Settings(context);
1300        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1301                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1302        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1303                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1304        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1305                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312
1313        String separateProcesses = SystemProperties.get("debug.separate_processes");
1314        if (separateProcesses != null && separateProcesses.length() > 0) {
1315            if ("*".equals(separateProcesses)) {
1316                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1317                mSeparateProcesses = null;
1318                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1319            } else {
1320                mDefParseFlags = 0;
1321                mSeparateProcesses = separateProcesses.split(",");
1322                Slog.w(TAG, "Running with debug.separate_processes: "
1323                        + separateProcesses);
1324            }
1325        } else {
1326            mDefParseFlags = 0;
1327            mSeparateProcesses = null;
1328        }
1329
1330        mInstaller = installer;
1331
1332        getDefaultDisplayMetrics(context, mMetrics);
1333
1334        synchronized (mInstallLock) {
1335        // writer
1336        synchronized (mPackages) {
1337            mHandlerThread = new ServiceThread(TAG,
1338                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1339            mHandlerThread.start();
1340            mHandler = new PackageHandler(mHandlerThread.getLooper());
1341            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1342
1343            File dataDir = Environment.getDataDirectory();
1344            mAppDataDir = new File(dataDir, "data");
1345            mAppInstallDir = new File(dataDir, "app");
1346            mAppLibInstallDir = new File(dataDir, "app-lib");
1347            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1348            mUserAppDataDir = new File(dataDir, "user");
1349            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1350            mAppStagingDir = new File(dataDir, "app-staging");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Read permissions and features from system
1356            readPermissions(Environment.buildPath(
1357                    Environment.getRootDirectory(), "etc", "permissions"), false);
1358            // Only read features from OEM
1359            readPermissions(Environment.buildPath(
1360                    Environment.getOemDirectory(), "etc", "permissions"), true);
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            String bootClassPath = System.getProperty("java.boot.class.path");
1393            if (bootClassPath != null) {
1394                String[] paths = splitString(bootClassPath, ':');
1395                for (int i=0; i<paths.length; i++) {
1396                    alreadyDexOpted.add(paths[i]);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            boolean didDexOptLibraryOrTool = false;
1403
1404            final List<String> instructionSets = getAllInstructionSets();
1405
1406            /**
1407             * Ensure all external libraries have had dexopt run on them.
1408             */
1409            if (mSharedLibraries.size() > 0) {
1410                // NOTE: For now, we're compiling these system "shared libraries"
1411                // (and framework jars) into all available architectures. It's possible
1412                // to compile them only when we come across an app that uses them (there's
1413                // already logic for that in scanPackageLI) but that adds some complexity.
1414                for (String instructionSet : instructionSets) {
1415                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1416                        final String lib = libEntry.path;
1417                        if (lib == null) {
1418                            continue;
1419                        }
1420
1421                        try {
1422                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1423                                alreadyDexOpted.add(lib);
1424
1425                                // The list of "shared libraries" we have at this point is
1426                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1427                                didDexOptLibraryOrTool = true;
1428                            }
1429                        } catch (FileNotFoundException e) {
1430                            Slog.w(TAG, "Library not found: " + lib);
1431                        } catch (IOException e) {
1432                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1433                                    + e.getMessage());
1434                        }
1435                    }
1436                }
1437            }
1438
1439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1440
1441            // Gross hack for now: we know this file doesn't contain any
1442            // code, so don't dexopt it to avoid the resulting log spew.
1443            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1444
1445            // Gross hack for now: we know this file is only part of
1446            // the boot class path for art, so don't dexopt it to
1447            // avoid the resulting log spew.
1448            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1449
1450            /**
1451             * And there are a number of commands implemented in Java, which
1452             * we currently need to do the dexopt on so that they can be
1453             * run from a non-root shell.
1454             */
1455            String[] frameworkFiles = frameworkDir.list();
1456            if (frameworkFiles != null) {
1457                // TODO: We could compile these only for the most preferred ABI. We should
1458                // first double check that the dex files for these commands are not referenced
1459                // by other system apps.
1460                for (String instructionSet : instructionSets) {
1461                    for (int i=0; i<frameworkFiles.length; i++) {
1462                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1463                        String path = libPath.getPath();
1464                        // Skip the file if we already did it.
1465                        if (alreadyDexOpted.contains(path)) {
1466                            continue;
1467                        }
1468                        // Skip the file if it is not a type we want to dexopt.
1469                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1470                            continue;
1471                        }
1472                        try {
1473                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1474                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1475                                didDexOptLibraryOrTool = true;
1476                            }
1477                        } catch (FileNotFoundException e) {
1478                            Slog.w(TAG, "Jar not found: " + path);
1479                        } catch (IOException e) {
1480                            Slog.w(TAG, "Exception reading jar: " + path, e);
1481                        }
1482                    }
1483                }
1484            }
1485
1486            if (didDexOptLibraryOrTool) {
1487                // If we dexopted a library or tool, then something on the system has
1488                // changed. Consider this significant, and wipe away all other
1489                // existing dexopt files to ensure we don't leave any dangling around.
1490                //
1491                // TODO: This should be revisited because it isn't as good an indicator
1492                // as it used to be. It used to include the boot classpath but at some point
1493                // DexFile.isDexOptNeeded started returning false for the boot
1494                // class path files in all cases. It is very possible in a
1495                // small maintenance release update that the library and tool
1496                // jars may be unchanged but APK could be removed resulting in
1497                // unused dalvik-cache files.
1498                for (String instructionSet : instructionSets) {
1499                    mInstaller.pruneDexCache(instructionSet);
1500                }
1501
1502                // Additionally, delete all dex files from the root directory
1503                // since there shouldn't be any there anyway, unless we're upgrading
1504                // from an older OS version or a build that contained the "old" style
1505                // flat scheme.
1506                mInstaller.pruneDexCache(".");
1507            }
1508
1509            // Collect vendor overlay packages.
1510            // (Do this before scanning any apps.)
1511            // For security and version matching reason, only consider
1512            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1513            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1514            mVendorOverlayInstallObserver = new AppDirObserver(
1515                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1516            mVendorOverlayInstallObserver.startWatching();
1517            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1518                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1519
1520            // Find base frameworks (resource packages without code).
1521            mFrameworkInstallObserver = new AppDirObserver(
1522                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1523            mFrameworkInstallObserver.startWatching();
1524            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1525                    | PackageParser.PARSE_IS_SYSTEM_DIR
1526                    | PackageParser.PARSE_IS_PRIVILEGED,
1527                    scanMode | SCAN_NO_DEX, 0);
1528
1529            // Collected privileged system packages.
1530            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1531            mPrivilegedInstallObserver = new AppDirObserver(
1532                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1533            mPrivilegedInstallObserver.startWatching();
1534                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1535                        | PackageParser.PARSE_IS_SYSTEM_DIR
1536                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1537
1538            // Collect ordinary system packages.
1539            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1540            mSystemInstallObserver = new AppDirObserver(
1541                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1542            mSystemInstallObserver.startWatching();
1543            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1544                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1545
1546            // Collect all vendor packages.
1547            File vendorAppDir = new File("/vendor/app");
1548            try {
1549                vendorAppDir = vendorAppDir.getCanonicalFile();
1550            } catch (IOException e) {
1551                // failed to look up canonical path, continue with original one
1552            }
1553            mVendorInstallObserver = new AppDirObserver(
1554                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1555            mVendorInstallObserver.startWatching();
1556            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1557                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1558
1559            // Collect all OEM packages.
1560            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1561            mOemInstallObserver = new AppDirObserver(
1562                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1563            mOemInstallObserver.startWatching();
1564            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1565                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1566
1567            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1568            mInstaller.moveFiles();
1569
1570            // Prune any system packages that no longer exist.
1571            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1572            if (!mOnlyCore) {
1573                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1574                while (psit.hasNext()) {
1575                    PackageSetting ps = psit.next();
1576
1577                    /*
1578                     * If this is not a system app, it can't be a
1579                     * disable system app.
1580                     */
1581                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1582                        continue;
1583                    }
1584
1585                    /*
1586                     * If the package is scanned, it's not erased.
1587                     */
1588                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1589                    if (scannedPkg != null) {
1590                        /*
1591                         * If the system app is both scanned and in the
1592                         * disabled packages list, then it must have been
1593                         * added via OTA. Remove it from the currently
1594                         * scanned package so the previously user-installed
1595                         * application can be scanned.
1596                         */
1597                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1598                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1599                                    + "; removing system app");
1600                            removePackageLI(ps, true);
1601                        }
1602
1603                        continue;
1604                    }
1605
1606                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1607                        psit.remove();
1608                        String msg = "System package " + ps.name
1609                                + " no longer exists; wiping its data";
1610                        reportSettingsProblem(Log.WARN, msg);
1611                        removeDataDirsLI(ps.name);
1612                    } else {
1613                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1614                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1615                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1616                        }
1617                    }
1618                }
1619            }
1620
1621            //look for any incomplete package installations
1622            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1623            //clean up list
1624            for(int i = 0; i < deletePkgsList.size(); i++) {
1625                //clean up here
1626                cleanupInstallFailedPackage(deletePkgsList.get(i));
1627            }
1628            //delete tmp files
1629            deleteTempPackageFiles();
1630
1631            // Remove any shared userIDs that have no associated packages
1632            mSettings.pruneSharedUsersLPw();
1633
1634            if (!mOnlyCore) {
1635                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1636                        SystemClock.uptimeMillis());
1637                mAppInstallObserver = new AppDirObserver(
1638                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1639                mAppInstallObserver.startWatching();
1640                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1641
1642                mDrmAppInstallObserver = new AppDirObserver(
1643                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1644                mDrmAppInstallObserver.startWatching();
1645                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1646                        scanMode, 0);
1647
1648                /**
1649                 * Remove disable package settings for any updated system
1650                 * apps that were removed via an OTA. If they're not a
1651                 * previously-updated app, remove them completely.
1652                 * Otherwise, just revoke their system-level permissions.
1653                 */
1654                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1655                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1656                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1657
1658                    String msg;
1659                    if (deletedPkg == null) {
1660                        msg = "Updated system package " + deletedAppName
1661                                + " no longer exists; wiping its data";
1662                        removeDataDirsLI(deletedAppName);
1663                    } else {
1664                        msg = "Updated system app + " + deletedAppName
1665                                + " no longer present; removing system privileges for "
1666                                + deletedAppName;
1667
1668                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1669
1670                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1671                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1672                    }
1673                    reportSettingsProblem(Log.WARN, msg);
1674                }
1675            } else {
1676                mAppInstallObserver = null;
1677                mDrmAppInstallObserver = null;
1678            }
1679
1680            // Now that we know all of the shared libraries, update all clients to have
1681            // the correct library paths.
1682            updateAllSharedLibrariesLPw();
1683
1684            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1685                // NOTE: We ignore potential failures here during a system scan (like
1686                // the rest of the commands above) because there's precious little we
1687                // can do about it. A settings error is reported, though.
1688                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1689                        false /* force dexopt */, false /* defer dexopt */);
1690            }
1691
1692            // Now that we know all the packages we are keeping,
1693            // read and update their last usage times.
1694            mPackageUsage.readLP();
1695
1696            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1697                    SystemClock.uptimeMillis());
1698            Slog.i(TAG, "Time to scan packages: "
1699                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1700                    + " seconds");
1701
1702            // If the platform SDK has changed since the last time we booted,
1703            // we need to re-grant app permission to catch any new ones that
1704            // appear.  This is really a hack, and means that apps can in some
1705            // cases get permissions that the user didn't initially explicitly
1706            // allow...  it would be nice to have some better way to handle
1707            // this situation.
1708            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1709                    != mSdkVersion;
1710            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1711                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1712                    + "; regranting permissions for internal storage");
1713            mSettings.mInternalSdkPlatform = mSdkVersion;
1714
1715            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1716                    | (regrantPermissions
1717                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1718                            : 0));
1719
1720            // If this is the first boot, and it is a normal boot, then
1721            // we need to initialize the default preferred apps.
1722            if (!mRestoredSettings && !onlyCore) {
1723                mSettings.readDefaultPreferredAppsLPw(this, 0);
1724            }
1725
1726            // All the changes are done during package scanning.
1727            mSettings.updateInternalDatabaseVersion();
1728
1729            // can downgrade to reader
1730            mSettings.writeLPr();
1731
1732            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1733                    SystemClock.uptimeMillis());
1734
1735
1736            mRequiredVerifierPackage = getRequiredVerifierLPr();
1737        } // synchronized (mPackages)
1738        } // synchronized (mInstallLock)
1739
1740        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1741
1742        // Now after opening every single application zip, make sure they
1743        // are all flushed.  Not really needed, but keeps things nice and
1744        // tidy.
1745        Runtime.getRuntime().gc();
1746    }
1747
1748    @Override
1749    public boolean isFirstBoot() {
1750        return !mRestoredSettings;
1751    }
1752
1753    @Override
1754    public boolean isOnlyCoreApps() {
1755        return mOnlyCore;
1756    }
1757
1758    private String getRequiredVerifierLPr() {
1759        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1760        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1761                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1762
1763        String requiredVerifier = null;
1764
1765        final int N = receivers.size();
1766        for (int i = 0; i < N; i++) {
1767            final ResolveInfo info = receivers.get(i);
1768
1769            if (info.activityInfo == null) {
1770                continue;
1771            }
1772
1773            final String packageName = info.activityInfo.packageName;
1774
1775            final PackageSetting ps = mSettings.mPackages.get(packageName);
1776            if (ps == null) {
1777                continue;
1778            }
1779
1780            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1781            if (!gp.grantedPermissions
1782                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1783                continue;
1784            }
1785
1786            if (requiredVerifier != null) {
1787                throw new RuntimeException("There can be only one required verifier");
1788            }
1789
1790            requiredVerifier = packageName;
1791        }
1792
1793        return requiredVerifier;
1794    }
1795
1796    @Override
1797    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1798            throws RemoteException {
1799        try {
1800            return super.onTransact(code, data, reply, flags);
1801        } catch (RuntimeException e) {
1802            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1803                Slog.wtf(TAG, "Package Manager Crash", e);
1804            }
1805            throw e;
1806        }
1807    }
1808
1809    void cleanupInstallFailedPackage(PackageSetting ps) {
1810        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1811        removeDataDirsLI(ps.name);
1812        if (ps.codePath != null) {
1813            if (!ps.codePath.delete()) {
1814                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1815            }
1816        }
1817        if (ps.resourcePath != null) {
1818            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1819                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1820            }
1821        }
1822        mSettings.removePackageLPw(ps.name);
1823    }
1824
1825    void readPermissions(File libraryDir, boolean onlyFeatures) {
1826        // Read permissions from .../etc/permission directory.
1827        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1828            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1829            return;
1830        }
1831        if (!libraryDir.canRead()) {
1832            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1833            return;
1834        }
1835
1836        // Iterate over the files in the directory and scan .xml files
1837        for (File f : libraryDir.listFiles()) {
1838            // We'll read platform.xml last
1839            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1840                continue;
1841            }
1842
1843            if (!f.getPath().endsWith(".xml")) {
1844                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1845                continue;
1846            }
1847            if (!f.canRead()) {
1848                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1849                continue;
1850            }
1851
1852            readPermissionsFromXml(f, onlyFeatures);
1853        }
1854
1855        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1856        final File permFile = new File(Environment.getRootDirectory(),
1857                "etc/permissions/platform.xml");
1858        readPermissionsFromXml(permFile, onlyFeatures);
1859    }
1860
1861    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1862        FileReader permReader = null;
1863        try {
1864            permReader = new FileReader(permFile);
1865        } catch (FileNotFoundException e) {
1866            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1867            return;
1868        }
1869
1870        try {
1871            XmlPullParser parser = Xml.newPullParser();
1872            parser.setInput(permReader);
1873
1874            XmlUtils.beginDocument(parser, "permissions");
1875
1876            while (true) {
1877                XmlUtils.nextElement(parser);
1878                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1879                    break;
1880                }
1881
1882                String name = parser.getName();
1883                if ("group".equals(name) && !onlyFeatures) {
1884                    String gidStr = parser.getAttributeValue(null, "gid");
1885                    if (gidStr != null) {
1886                        int gid = Process.getGidForName(gidStr);
1887                        mGlobalGids = appendInt(mGlobalGids, gid);
1888                    } else {
1889                        Slog.w(TAG, "<group> without gid at "
1890                                + parser.getPositionDescription());
1891                    }
1892
1893                    XmlUtils.skipCurrentTag(parser);
1894                    continue;
1895                } else if ("permission".equals(name) && !onlyFeatures) {
1896                    String perm = parser.getAttributeValue(null, "name");
1897                    if (perm == null) {
1898                        Slog.w(TAG, "<permission> without name at "
1899                                + parser.getPositionDescription());
1900                        XmlUtils.skipCurrentTag(parser);
1901                        continue;
1902                    }
1903                    perm = perm.intern();
1904                    readPermission(parser, perm);
1905
1906                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1907                    String perm = parser.getAttributeValue(null, "name");
1908                    if (perm == null) {
1909                        Slog.w(TAG, "<assign-permission> without name at "
1910                                + parser.getPositionDescription());
1911                        XmlUtils.skipCurrentTag(parser);
1912                        continue;
1913                    }
1914                    String uidStr = parser.getAttributeValue(null, "uid");
1915                    if (uidStr == null) {
1916                        Slog.w(TAG, "<assign-permission> without uid at "
1917                                + parser.getPositionDescription());
1918                        XmlUtils.skipCurrentTag(parser);
1919                        continue;
1920                    }
1921                    int uid = Process.getUidForName(uidStr);
1922                    if (uid < 0) {
1923                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1924                                + uidStr + "\" at "
1925                                + parser.getPositionDescription());
1926                        XmlUtils.skipCurrentTag(parser);
1927                        continue;
1928                    }
1929                    perm = perm.intern();
1930                    HashSet<String> perms = mSystemPermissions.get(uid);
1931                    if (perms == null) {
1932                        perms = new HashSet<String>();
1933                        mSystemPermissions.put(uid, perms);
1934                    }
1935                    perms.add(perm);
1936                    XmlUtils.skipCurrentTag(parser);
1937
1938                } else if ("library".equals(name) && !onlyFeatures) {
1939                    String lname = parser.getAttributeValue(null, "name");
1940                    String lfile = parser.getAttributeValue(null, "file");
1941                    if (lname == null) {
1942                        Slog.w(TAG, "<library> without name at "
1943                                + parser.getPositionDescription());
1944                    } else if (lfile == null) {
1945                        Slog.w(TAG, "<library> without file at "
1946                                + parser.getPositionDescription());
1947                    } else {
1948                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1949                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1950                    }
1951                    XmlUtils.skipCurrentTag(parser);
1952                    continue;
1953
1954                } else if ("feature".equals(name)) {
1955                    String fname = parser.getAttributeValue(null, "name");
1956                    if (fname == null) {
1957                        Slog.w(TAG, "<feature> without name at "
1958                                + parser.getPositionDescription());
1959                    } else {
1960                        //Log.i(TAG, "Got feature " + fname);
1961                        FeatureInfo fi = new FeatureInfo();
1962                        fi.name = fname;
1963                        mAvailableFeatures.put(fname, fi);
1964                    }
1965                    XmlUtils.skipCurrentTag(parser);
1966                    continue;
1967
1968                } else {
1969                    XmlUtils.skipCurrentTag(parser);
1970                    continue;
1971                }
1972
1973            }
1974            permReader.close();
1975        } catch (XmlPullParserException e) {
1976            Slog.w(TAG, "Got execption parsing permissions.", e);
1977        } catch (IOException e) {
1978            Slog.w(TAG, "Got execption parsing permissions.", e);
1979        }
1980    }
1981
1982    void readPermission(XmlPullParser parser, String name)
1983            throws IOException, XmlPullParserException {
1984
1985        name = name.intern();
1986
1987        BasePermission bp = mSettings.mPermissions.get(name);
1988        if (bp == null) {
1989            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1990            mSettings.mPermissions.put(name, bp);
1991        }
1992        int outerDepth = parser.getDepth();
1993        int type;
1994        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1995               && (type != XmlPullParser.END_TAG
1996                       || parser.getDepth() > outerDepth)) {
1997            if (type == XmlPullParser.END_TAG
1998                    || type == XmlPullParser.TEXT) {
1999                continue;
2000            }
2001
2002            String tagName = parser.getName();
2003            if ("group".equals(tagName)) {
2004                String gidStr = parser.getAttributeValue(null, "gid");
2005                if (gidStr != null) {
2006                    int gid = Process.getGidForName(gidStr);
2007                    bp.gids = appendInt(bp.gids, gid);
2008                } else {
2009                    Slog.w(TAG, "<group> without gid at "
2010                            + parser.getPositionDescription());
2011                }
2012            }
2013            XmlUtils.skipCurrentTag(parser);
2014        }
2015    }
2016
2017    static int[] appendInts(int[] cur, int[] add) {
2018        if (add == null) return cur;
2019        if (cur == null) return add;
2020        final int N = add.length;
2021        for (int i=0; i<N; i++) {
2022            cur = appendInt(cur, add[i]);
2023        }
2024        return cur;
2025    }
2026
2027    static int[] removeInts(int[] cur, int[] rem) {
2028        if (rem == null) return cur;
2029        if (cur == null) return cur;
2030        final int N = rem.length;
2031        for (int i=0; i<N; i++) {
2032            cur = removeInt(cur, rem[i]);
2033        }
2034        return cur;
2035    }
2036
2037    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2038        if (!sUserManager.exists(userId)) return null;
2039        final PackageSetting ps = (PackageSetting) p.mExtras;
2040        if (ps == null) {
2041            return null;
2042        }
2043        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2044        final PackageUserState state = ps.readUserState(userId);
2045        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2046                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2047                state, userId);
2048    }
2049
2050    @Override
2051    public boolean isPackageAvailable(String packageName, int userId) {
2052        if (!sUserManager.exists(userId)) return false;
2053        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2054        synchronized (mPackages) {
2055            PackageParser.Package p = mPackages.get(packageName);
2056            if (p != null) {
2057                final PackageSetting ps = (PackageSetting) p.mExtras;
2058                if (ps != null) {
2059                    final PackageUserState state = ps.readUserState(userId);
2060                    if (state != null) {
2061                        return PackageParser.isAvailable(state);
2062                    }
2063                }
2064            }
2065        }
2066        return false;
2067    }
2068
2069    @Override
2070    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2071        if (!sUserManager.exists(userId)) return null;
2072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2073        // reader
2074        synchronized (mPackages) {
2075            PackageParser.Package p = mPackages.get(packageName);
2076            if (DEBUG_PACKAGE_INFO)
2077                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2078            if (p != null) {
2079                return generatePackageInfo(p, flags, userId);
2080            }
2081            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2082                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2083            }
2084        }
2085        return null;
2086    }
2087
2088    @Override
2089    public String[] currentToCanonicalPackageNames(String[] names) {
2090        String[] out = new String[names.length];
2091        // reader
2092        synchronized (mPackages) {
2093            for (int i=names.length-1; i>=0; i--) {
2094                PackageSetting ps = mSettings.mPackages.get(names[i]);
2095                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2096            }
2097        }
2098        return out;
2099    }
2100
2101    @Override
2102    public String[] canonicalToCurrentPackageNames(String[] names) {
2103        String[] out = new String[names.length];
2104        // reader
2105        synchronized (mPackages) {
2106            for (int i=names.length-1; i>=0; i--) {
2107                String cur = mSettings.mRenamedPackages.get(names[i]);
2108                out[i] = cur != null ? cur : names[i];
2109            }
2110        }
2111        return out;
2112    }
2113
2114    @Override
2115    public int getPackageUid(String packageName, int userId) {
2116        if (!sUserManager.exists(userId)) return -1;
2117        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2118        // reader
2119        synchronized (mPackages) {
2120            PackageParser.Package p = mPackages.get(packageName);
2121            if(p != null) {
2122                return UserHandle.getUid(userId, p.applicationInfo.uid);
2123            }
2124            PackageSetting ps = mSettings.mPackages.get(packageName);
2125            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2126                return -1;
2127            }
2128            p = ps.pkg;
2129            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2130        }
2131    }
2132
2133    @Override
2134    public int[] getPackageGids(String packageName) {
2135        // reader
2136        synchronized (mPackages) {
2137            PackageParser.Package p = mPackages.get(packageName);
2138            if (DEBUG_PACKAGE_INFO)
2139                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2140            if (p != null) {
2141                final PackageSetting ps = (PackageSetting)p.mExtras;
2142                return ps.getGids();
2143            }
2144        }
2145        // stupid thing to indicate an error.
2146        return new int[0];
2147    }
2148
2149    static final PermissionInfo generatePermissionInfo(
2150            BasePermission bp, int flags) {
2151        if (bp.perm != null) {
2152            return PackageParser.generatePermissionInfo(bp.perm, flags);
2153        }
2154        PermissionInfo pi = new PermissionInfo();
2155        pi.name = bp.name;
2156        pi.packageName = bp.sourcePackage;
2157        pi.nonLocalizedLabel = bp.name;
2158        pi.protectionLevel = bp.protectionLevel;
2159        return pi;
2160    }
2161
2162    @Override
2163    public PermissionInfo getPermissionInfo(String name, int flags) {
2164        // reader
2165        synchronized (mPackages) {
2166            final BasePermission p = mSettings.mPermissions.get(name);
2167            if (p != null) {
2168                return generatePermissionInfo(p, flags);
2169            }
2170            return null;
2171        }
2172    }
2173
2174    @Override
2175    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2176        // reader
2177        synchronized (mPackages) {
2178            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2179            for (BasePermission p : mSettings.mPermissions.values()) {
2180                if (group == null) {
2181                    if (p.perm == null || p.perm.info.group == null) {
2182                        out.add(generatePermissionInfo(p, flags));
2183                    }
2184                } else {
2185                    if (p.perm != null && group.equals(p.perm.info.group)) {
2186                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2187                    }
2188                }
2189            }
2190
2191            if (out.size() > 0) {
2192                return out;
2193            }
2194            return mPermissionGroups.containsKey(group) ? out : null;
2195        }
2196    }
2197
2198    @Override
2199    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2200        // reader
2201        synchronized (mPackages) {
2202            return PackageParser.generatePermissionGroupInfo(
2203                    mPermissionGroups.get(name), flags);
2204        }
2205    }
2206
2207    @Override
2208    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2209        // reader
2210        synchronized (mPackages) {
2211            final int N = mPermissionGroups.size();
2212            ArrayList<PermissionGroupInfo> out
2213                    = new ArrayList<PermissionGroupInfo>(N);
2214            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2215                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2216            }
2217            return out;
2218        }
2219    }
2220
2221    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2222            int userId) {
2223        if (!sUserManager.exists(userId)) return null;
2224        PackageSetting ps = mSettings.mPackages.get(packageName);
2225        if (ps != null) {
2226            if (ps.pkg == null) {
2227                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2228                        flags, userId);
2229                if (pInfo != null) {
2230                    return pInfo.applicationInfo;
2231                }
2232                return null;
2233            }
2234            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2235                    ps.readUserState(userId), userId);
2236        }
2237        return null;
2238    }
2239
2240    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2241            int userId) {
2242        if (!sUserManager.exists(userId)) return null;
2243        PackageSetting ps = mSettings.mPackages.get(packageName);
2244        if (ps != null) {
2245            PackageParser.Package pkg = ps.pkg;
2246            if (pkg == null) {
2247                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2248                    return null;
2249                }
2250                // App code is gone, so we aren't worried about split paths
2251                pkg = new PackageParser.Package(packageName);
2252                pkg.applicationInfo.packageName = packageName;
2253                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2254                pkg.applicationInfo.sourceDir = ps.codePathString;
2255                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2256                pkg.applicationInfo.dataDir =
2257                        getDataPathForPackage(packageName, 0).getPath();
2258                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2259                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2260            }
2261            return generatePackageInfo(pkg, flags, userId);
2262        }
2263        return null;
2264    }
2265
2266    @Override
2267    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2268        if (!sUserManager.exists(userId)) return null;
2269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2270        // writer
2271        synchronized (mPackages) {
2272            PackageParser.Package p = mPackages.get(packageName);
2273            if (DEBUG_PACKAGE_INFO) Log.v(
2274                    TAG, "getApplicationInfo " + packageName
2275                    + ": " + p);
2276            if (p != null) {
2277                PackageSetting ps = mSettings.mPackages.get(packageName);
2278                if (ps == null) return null;
2279                // Note: isEnabledLP() does not apply here - always return info
2280                return PackageParser.generateApplicationInfo(
2281                        p, flags, ps.readUserState(userId), userId);
2282            }
2283            if ("android".equals(packageName)||"system".equals(packageName)) {
2284                return mAndroidApplication;
2285            }
2286            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2287                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2288            }
2289        }
2290        return null;
2291    }
2292
2293
2294    @Override
2295    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2296        mContext.enforceCallingOrSelfPermission(
2297                android.Manifest.permission.CLEAR_APP_CACHE, null);
2298        // Queue up an async operation since clearing cache may take a little while.
2299        mHandler.post(new Runnable() {
2300            public void run() {
2301                mHandler.removeCallbacks(this);
2302                int retCode = -1;
2303                synchronized (mInstallLock) {
2304                    retCode = mInstaller.freeCache(freeStorageSize);
2305                    if (retCode < 0) {
2306                        Slog.w(TAG, "Couldn't clear application caches");
2307                    }
2308                }
2309                if (observer != null) {
2310                    try {
2311                        observer.onRemoveCompleted(null, (retCode >= 0));
2312                    } catch (RemoteException e) {
2313                        Slog.w(TAG, "RemoveException when invoking call back");
2314                    }
2315                }
2316            }
2317        });
2318    }
2319
2320    @Override
2321    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2322        mContext.enforceCallingOrSelfPermission(
2323                android.Manifest.permission.CLEAR_APP_CACHE, null);
2324        // Queue up an async operation since clearing cache may take a little while.
2325        mHandler.post(new Runnable() {
2326            public void run() {
2327                mHandler.removeCallbacks(this);
2328                int retCode = -1;
2329                synchronized (mInstallLock) {
2330                    retCode = mInstaller.freeCache(freeStorageSize);
2331                    if (retCode < 0) {
2332                        Slog.w(TAG, "Couldn't clear application caches");
2333                    }
2334                }
2335                if(pi != null) {
2336                    try {
2337                        // Callback via pending intent
2338                        int code = (retCode >= 0) ? 1 : 0;
2339                        pi.sendIntent(null, code, null,
2340                                null, null);
2341                    } catch (SendIntentException e1) {
2342                        Slog.i(TAG, "Failed to send pending intent");
2343                    }
2344                }
2345            }
2346        });
2347    }
2348
2349    void freeStorage(long freeStorageSize) throws IOException {
2350        synchronized (mInstallLock) {
2351            if (mInstaller.freeCache(freeStorageSize) < 0) {
2352                throw new IOException("Failed to free enough space");
2353            }
2354        }
2355    }
2356
2357    @Override
2358    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2359        if (!sUserManager.exists(userId)) return null;
2360        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2361        synchronized (mPackages) {
2362            PackageParser.Activity a = mActivities.mActivities.get(component);
2363
2364            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2365            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2366                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2367                if (ps == null) return null;
2368                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2369                        userId);
2370            }
2371            if (mResolveComponentName.equals(component)) {
2372                return mResolveActivity;
2373            }
2374        }
2375        return null;
2376    }
2377
2378    @Override
2379    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2380            String resolvedType) {
2381        synchronized (mPackages) {
2382            PackageParser.Activity a = mActivities.mActivities.get(component);
2383            if (a == null) {
2384                return false;
2385            }
2386            for (int i=0; i<a.intents.size(); i++) {
2387                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2388                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2389                    return true;
2390                }
2391            }
2392            return false;
2393        }
2394    }
2395
2396    @Override
2397    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2398        if (!sUserManager.exists(userId)) return null;
2399        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2400        synchronized (mPackages) {
2401            PackageParser.Activity a = mReceivers.mActivities.get(component);
2402            if (DEBUG_PACKAGE_INFO) Log.v(
2403                TAG, "getReceiverInfo " + component + ": " + a);
2404            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2405                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2406                if (ps == null) return null;
2407                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2408                        userId);
2409            }
2410        }
2411        return null;
2412    }
2413
2414    @Override
2415    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2416        if (!sUserManager.exists(userId)) return null;
2417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2418        synchronized (mPackages) {
2419            PackageParser.Service s = mServices.mServices.get(component);
2420            if (DEBUG_PACKAGE_INFO) Log.v(
2421                TAG, "getServiceInfo " + component + ": " + s);
2422            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2423                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2424                if (ps == null) return null;
2425                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2426                        userId);
2427            }
2428        }
2429        return null;
2430    }
2431
2432    @Override
2433    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2434        if (!sUserManager.exists(userId)) return null;
2435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2436        synchronized (mPackages) {
2437            PackageParser.Provider p = mProviders.mProviders.get(component);
2438            if (DEBUG_PACKAGE_INFO) Log.v(
2439                TAG, "getProviderInfo " + component + ": " + p);
2440            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2441                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2442                if (ps == null) return null;
2443                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2444                        userId);
2445            }
2446        }
2447        return null;
2448    }
2449
2450    @Override
2451    public String[] getSystemSharedLibraryNames() {
2452        Set<String> libSet;
2453        synchronized (mPackages) {
2454            libSet = mSharedLibraries.keySet();
2455            int size = libSet.size();
2456            if (size > 0) {
2457                String[] libs = new String[size];
2458                libSet.toArray(libs);
2459                return libs;
2460            }
2461        }
2462        return null;
2463    }
2464
2465    @Override
2466    public FeatureInfo[] getSystemAvailableFeatures() {
2467        Collection<FeatureInfo> featSet;
2468        synchronized (mPackages) {
2469            featSet = mAvailableFeatures.values();
2470            int size = featSet.size();
2471            if (size > 0) {
2472                FeatureInfo[] features = new FeatureInfo[size+1];
2473                featSet.toArray(features);
2474                FeatureInfo fi = new FeatureInfo();
2475                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2476                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2477                features[size] = fi;
2478                return features;
2479            }
2480        }
2481        return null;
2482    }
2483
2484    @Override
2485    public boolean hasSystemFeature(String name) {
2486        synchronized (mPackages) {
2487            return mAvailableFeatures.containsKey(name);
2488        }
2489    }
2490
2491    private void checkValidCaller(int uid, int userId) {
2492        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2493            return;
2494
2495        throw new SecurityException("Caller uid=" + uid
2496                + " is not privileged to communicate with user=" + userId);
2497    }
2498
2499    @Override
2500    public int checkPermission(String permName, String pkgName) {
2501        synchronized (mPackages) {
2502            PackageParser.Package p = mPackages.get(pkgName);
2503            if (p != null && p.mExtras != null) {
2504                PackageSetting ps = (PackageSetting)p.mExtras;
2505                if (ps.sharedUser != null) {
2506                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2507                        return PackageManager.PERMISSION_GRANTED;
2508                    }
2509                } else if (ps.grantedPermissions.contains(permName)) {
2510                    return PackageManager.PERMISSION_GRANTED;
2511                }
2512            }
2513        }
2514        return PackageManager.PERMISSION_DENIED;
2515    }
2516
2517    @Override
2518    public int checkUidPermission(String permName, int uid) {
2519        synchronized (mPackages) {
2520            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2521            if (obj != null) {
2522                GrantedPermissions gp = (GrantedPermissions)obj;
2523                if (gp.grantedPermissions.contains(permName)) {
2524                    return PackageManager.PERMISSION_GRANTED;
2525                }
2526            } else {
2527                HashSet<String> perms = mSystemPermissions.get(uid);
2528                if (perms != null && perms.contains(permName)) {
2529                    return PackageManager.PERMISSION_GRANTED;
2530                }
2531            }
2532        }
2533        return PackageManager.PERMISSION_DENIED;
2534    }
2535
2536    /**
2537     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2538     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2539     * @param message the message to log on security exception
2540     */
2541    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2542            String message) {
2543        if (userId < 0) {
2544            throw new IllegalArgumentException("Invalid userId " + userId);
2545        }
2546        if (userId == UserHandle.getUserId(callingUid)) return;
2547        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2548            if (requireFullPermission) {
2549                mContext.enforceCallingOrSelfPermission(
2550                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2551            } else {
2552                try {
2553                    mContext.enforceCallingOrSelfPermission(
2554                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2555                } catch (SecurityException se) {
2556                    mContext.enforceCallingOrSelfPermission(
2557                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2558                }
2559            }
2560        }
2561    }
2562
2563    private BasePermission findPermissionTreeLP(String permName) {
2564        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2565            if (permName.startsWith(bp.name) &&
2566                    permName.length() > bp.name.length() &&
2567                    permName.charAt(bp.name.length()) == '.') {
2568                return bp;
2569            }
2570        }
2571        return null;
2572    }
2573
2574    private BasePermission checkPermissionTreeLP(String permName) {
2575        if (permName != null) {
2576            BasePermission bp = findPermissionTreeLP(permName);
2577            if (bp != null) {
2578                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2579                    return bp;
2580                }
2581                throw new SecurityException("Calling uid "
2582                        + Binder.getCallingUid()
2583                        + " is not allowed to add to permission tree "
2584                        + bp.name + " owned by uid " + bp.uid);
2585            }
2586        }
2587        throw new SecurityException("No permission tree found for " + permName);
2588    }
2589
2590    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2591        if (s1 == null) {
2592            return s2 == null;
2593        }
2594        if (s2 == null) {
2595            return false;
2596        }
2597        if (s1.getClass() != s2.getClass()) {
2598            return false;
2599        }
2600        return s1.equals(s2);
2601    }
2602
2603    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2604        if (pi1.icon != pi2.icon) return false;
2605        if (pi1.logo != pi2.logo) return false;
2606        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2607        if (!compareStrings(pi1.name, pi2.name)) return false;
2608        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2609        // We'll take care of setting this one.
2610        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2611        // These are not currently stored in settings.
2612        //if (!compareStrings(pi1.group, pi2.group)) return false;
2613        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2614        //if (pi1.labelRes != pi2.labelRes) return false;
2615        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2616        return true;
2617    }
2618
2619    int permissionInfoFootprint(PermissionInfo info) {
2620        int size = info.name.length();
2621        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2622        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2623        return size;
2624    }
2625
2626    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2627        int size = 0;
2628        for (BasePermission perm : mSettings.mPermissions.values()) {
2629            if (perm.uid == tree.uid) {
2630                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2631            }
2632        }
2633        return size;
2634    }
2635
2636    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2637        // We calculate the max size of permissions defined by this uid and throw
2638        // if that plus the size of 'info' would exceed our stated maximum.
2639        if (tree.uid != Process.SYSTEM_UID) {
2640            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2641            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2642                throw new SecurityException("Permission tree size cap exceeded");
2643            }
2644        }
2645    }
2646
2647    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2648        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2649            throw new SecurityException("Label must be specified in permission");
2650        }
2651        BasePermission tree = checkPermissionTreeLP(info.name);
2652        BasePermission bp = mSettings.mPermissions.get(info.name);
2653        boolean added = bp == null;
2654        boolean changed = true;
2655        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2656        if (added) {
2657            enforcePermissionCapLocked(info, tree);
2658            bp = new BasePermission(info.name, tree.sourcePackage,
2659                    BasePermission.TYPE_DYNAMIC);
2660        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2661            throw new SecurityException(
2662                    "Not allowed to modify non-dynamic permission "
2663                    + info.name);
2664        } else {
2665            if (bp.protectionLevel == fixedLevel
2666                    && bp.perm.owner.equals(tree.perm.owner)
2667                    && bp.uid == tree.uid
2668                    && comparePermissionInfos(bp.perm.info, info)) {
2669                changed = false;
2670            }
2671        }
2672        bp.protectionLevel = fixedLevel;
2673        info = new PermissionInfo(info);
2674        info.protectionLevel = fixedLevel;
2675        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2676        bp.perm.info.packageName = tree.perm.info.packageName;
2677        bp.uid = tree.uid;
2678        if (added) {
2679            mSettings.mPermissions.put(info.name, bp);
2680        }
2681        if (changed) {
2682            if (!async) {
2683                mSettings.writeLPr();
2684            } else {
2685                scheduleWriteSettingsLocked();
2686            }
2687        }
2688        return added;
2689    }
2690
2691    @Override
2692    public boolean addPermission(PermissionInfo info) {
2693        synchronized (mPackages) {
2694            return addPermissionLocked(info, false);
2695        }
2696    }
2697
2698    @Override
2699    public boolean addPermissionAsync(PermissionInfo info) {
2700        synchronized (mPackages) {
2701            return addPermissionLocked(info, true);
2702        }
2703    }
2704
2705    @Override
2706    public void removePermission(String name) {
2707        synchronized (mPackages) {
2708            checkPermissionTreeLP(name);
2709            BasePermission bp = mSettings.mPermissions.get(name);
2710            if (bp != null) {
2711                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2712                    throw new SecurityException(
2713                            "Not allowed to modify non-dynamic permission "
2714                            + name);
2715                }
2716                mSettings.mPermissions.remove(name);
2717                mSettings.writeLPr();
2718            }
2719        }
2720    }
2721
2722    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2723        int index = pkg.requestedPermissions.indexOf(bp.name);
2724        if (index == -1) {
2725            throw new SecurityException("Package " + pkg.packageName
2726                    + " has not requested permission " + bp.name);
2727        }
2728        boolean isNormal =
2729                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2730                        == PermissionInfo.PROTECTION_NORMAL);
2731        boolean isDangerous =
2732                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2733                        == PermissionInfo.PROTECTION_DANGEROUS);
2734        boolean isDevelopment =
2735                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2736
2737        if (!isNormal && !isDangerous && !isDevelopment) {
2738            throw new SecurityException("Permission " + bp.name
2739                    + " is not a changeable permission type");
2740        }
2741
2742        if (isNormal || isDangerous) {
2743            if (pkg.requestedPermissionsRequired.get(index)) {
2744                throw new SecurityException("Can't change " + bp.name
2745                        + ". It is required by the application");
2746            }
2747        }
2748    }
2749
2750    @Override
2751    public void grantPermission(String packageName, String permissionName) {
2752        mContext.enforceCallingOrSelfPermission(
2753                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2754        synchronized (mPackages) {
2755            final PackageParser.Package pkg = mPackages.get(packageName);
2756            if (pkg == null) {
2757                throw new IllegalArgumentException("Unknown package: " + packageName);
2758            }
2759            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2760            if (bp == null) {
2761                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2762            }
2763
2764            checkGrantRevokePermissions(pkg, bp);
2765
2766            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2767            if (ps == null) {
2768                return;
2769            }
2770            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2771            if (gp.grantedPermissions.add(permissionName)) {
2772                if (ps.haveGids) {
2773                    gp.gids = appendInts(gp.gids, bp.gids);
2774                }
2775                mSettings.writeLPr();
2776            }
2777        }
2778    }
2779
2780    @Override
2781    public void revokePermission(String packageName, String permissionName) {
2782        int changedAppId = -1;
2783
2784        synchronized (mPackages) {
2785            final PackageParser.Package pkg = mPackages.get(packageName);
2786            if (pkg == null) {
2787                throw new IllegalArgumentException("Unknown package: " + packageName);
2788            }
2789            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2790                mContext.enforceCallingOrSelfPermission(
2791                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2792            }
2793            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2794            if (bp == null) {
2795                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2796            }
2797
2798            checkGrantRevokePermissions(pkg, bp);
2799
2800            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2801            if (ps == null) {
2802                return;
2803            }
2804            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2805            if (gp.grantedPermissions.remove(permissionName)) {
2806                gp.grantedPermissions.remove(permissionName);
2807                if (ps.haveGids) {
2808                    gp.gids = removeInts(gp.gids, bp.gids);
2809                }
2810                mSettings.writeLPr();
2811                changedAppId = ps.appId;
2812            }
2813        }
2814
2815        if (changedAppId >= 0) {
2816            // We changed the perm on someone, kill its processes.
2817            IActivityManager am = ActivityManagerNative.getDefault();
2818            if (am != null) {
2819                final int callingUserId = UserHandle.getCallingUserId();
2820                final long ident = Binder.clearCallingIdentity();
2821                try {
2822                    //XXX we should only revoke for the calling user's app permissions,
2823                    // but for now we impact all users.
2824                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2825                    //        "revoke " + permissionName);
2826                    int[] users = sUserManager.getUserIds();
2827                    for (int user : users) {
2828                        am.killUid(UserHandle.getUid(user, changedAppId),
2829                                "revoke " + permissionName);
2830                    }
2831                } catch (RemoteException e) {
2832                } finally {
2833                    Binder.restoreCallingIdentity(ident);
2834                }
2835            }
2836        }
2837    }
2838
2839    @Override
2840    public boolean isProtectedBroadcast(String actionName) {
2841        synchronized (mPackages) {
2842            return mProtectedBroadcasts.contains(actionName);
2843        }
2844    }
2845
2846    @Override
2847    public int checkSignatures(String pkg1, String pkg2) {
2848        synchronized (mPackages) {
2849            final PackageParser.Package p1 = mPackages.get(pkg1);
2850            final PackageParser.Package p2 = mPackages.get(pkg2);
2851            if (p1 == null || p1.mExtras == null
2852                    || p2 == null || p2.mExtras == null) {
2853                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2854            }
2855            return compareSignatures(p1.mSignatures, p2.mSignatures);
2856        }
2857    }
2858
2859    @Override
2860    public int checkUidSignatures(int uid1, int uid2) {
2861        // Map to base uids.
2862        uid1 = UserHandle.getAppId(uid1);
2863        uid2 = UserHandle.getAppId(uid2);
2864        // reader
2865        synchronized (mPackages) {
2866            Signature[] s1;
2867            Signature[] s2;
2868            Object obj = mSettings.getUserIdLPr(uid1);
2869            if (obj != null) {
2870                if (obj instanceof SharedUserSetting) {
2871                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2872                } else if (obj instanceof PackageSetting) {
2873                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2874                } else {
2875                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2876                }
2877            } else {
2878                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2879            }
2880            obj = mSettings.getUserIdLPr(uid2);
2881            if (obj != null) {
2882                if (obj instanceof SharedUserSetting) {
2883                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2884                } else if (obj instanceof PackageSetting) {
2885                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2886                } else {
2887                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2888                }
2889            } else {
2890                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2891            }
2892            return compareSignatures(s1, s2);
2893        }
2894    }
2895
2896    /**
2897     * Compares two sets of signatures. Returns:
2898     * <br />
2899     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2900     * <br />
2901     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2902     * <br />
2903     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2904     * <br />
2905     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2906     * <br />
2907     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2908     */
2909    static int compareSignatures(Signature[] s1, Signature[] s2) {
2910        if (s1 == null) {
2911            return s2 == null
2912                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2913                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2914        }
2915
2916        if (s2 == null) {
2917            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2918        }
2919
2920        if (s1.length != s2.length) {
2921            return PackageManager.SIGNATURE_NO_MATCH;
2922        }
2923
2924        // Since both signature sets are of size 1, we can compare without HashSets.
2925        if (s1.length == 1) {
2926            return s1[0].equals(s2[0]) ?
2927                    PackageManager.SIGNATURE_MATCH :
2928                    PackageManager.SIGNATURE_NO_MATCH;
2929        }
2930
2931        HashSet<Signature> set1 = new HashSet<Signature>();
2932        for (Signature sig : s1) {
2933            set1.add(sig);
2934        }
2935        HashSet<Signature> set2 = new HashSet<Signature>();
2936        for (Signature sig : s2) {
2937            set2.add(sig);
2938        }
2939        // Make sure s2 contains all signatures in s1.
2940        if (set1.equals(set2)) {
2941            return PackageManager.SIGNATURE_MATCH;
2942        }
2943        return PackageManager.SIGNATURE_NO_MATCH;
2944    }
2945
2946    /**
2947     * If the database version for this type of package (internal storage or
2948     * external storage) is less than the version where package signatures
2949     * were updated, return true.
2950     */
2951    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2952        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2953                DatabaseVersion.SIGNATURE_END_ENTITY))
2954                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2955                        DatabaseVersion.SIGNATURE_END_ENTITY));
2956    }
2957
2958    /**
2959     * Used for backward compatibility to make sure any packages with
2960     * certificate chains get upgraded to the new style. {@code existingSigs}
2961     * will be in the old format (since they were stored on disk from before the
2962     * system upgrade) and {@code scannedSigs} will be in the newer format.
2963     */
2964    private int compareSignaturesCompat(PackageSignatures existingSigs,
2965            PackageParser.Package scannedPkg) {
2966        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2967            return PackageManager.SIGNATURE_NO_MATCH;
2968        }
2969
2970        HashSet<Signature> existingSet = new HashSet<Signature>();
2971        for (Signature sig : existingSigs.mSignatures) {
2972            existingSet.add(sig);
2973        }
2974        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2975        for (Signature sig : scannedPkg.mSignatures) {
2976            try {
2977                Signature[] chainSignatures = sig.getChainSignatures();
2978                for (Signature chainSig : chainSignatures) {
2979                    scannedCompatSet.add(chainSig);
2980                }
2981            } catch (CertificateEncodingException e) {
2982                scannedCompatSet.add(sig);
2983            }
2984        }
2985        /*
2986         * Make sure the expanded scanned set contains all signatures in the
2987         * existing one.
2988         */
2989        if (scannedCompatSet.equals(existingSet)) {
2990            // Migrate the old signatures to the new scheme.
2991            existingSigs.assignSignatures(scannedPkg.mSignatures);
2992            // The new KeySets will be re-added later in the scanning process.
2993            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2994            return PackageManager.SIGNATURE_MATCH;
2995        }
2996        return PackageManager.SIGNATURE_NO_MATCH;
2997    }
2998
2999    @Override
3000    public String[] getPackagesForUid(int uid) {
3001        uid = UserHandle.getAppId(uid);
3002        // reader
3003        synchronized (mPackages) {
3004            Object obj = mSettings.getUserIdLPr(uid);
3005            if (obj instanceof SharedUserSetting) {
3006                final SharedUserSetting sus = (SharedUserSetting) obj;
3007                final int N = sus.packages.size();
3008                final String[] res = new String[N];
3009                final Iterator<PackageSetting> it = sus.packages.iterator();
3010                int i = 0;
3011                while (it.hasNext()) {
3012                    res[i++] = it.next().name;
3013                }
3014                return res;
3015            } else if (obj instanceof PackageSetting) {
3016                final PackageSetting ps = (PackageSetting) obj;
3017                return new String[] { ps.name };
3018            }
3019        }
3020        return null;
3021    }
3022
3023    @Override
3024    public String getNameForUid(int uid) {
3025        // reader
3026        synchronized (mPackages) {
3027            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3028            if (obj instanceof SharedUserSetting) {
3029                final SharedUserSetting sus = (SharedUserSetting) obj;
3030                return sus.name + ":" + sus.userId;
3031            } else if (obj instanceof PackageSetting) {
3032                final PackageSetting ps = (PackageSetting) obj;
3033                return ps.name;
3034            }
3035        }
3036        return null;
3037    }
3038
3039    @Override
3040    public int getUidForSharedUser(String sharedUserName) {
3041        if(sharedUserName == null) {
3042            return -1;
3043        }
3044        // reader
3045        synchronized (mPackages) {
3046            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3047            if (suid == null) {
3048                return -1;
3049            }
3050            return suid.userId;
3051        }
3052    }
3053
3054    @Override
3055    public int getFlagsForUid(int uid) {
3056        synchronized (mPackages) {
3057            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3058            if (obj instanceof SharedUserSetting) {
3059                final SharedUserSetting sus = (SharedUserSetting) obj;
3060                return sus.pkgFlags;
3061            } else if (obj instanceof PackageSetting) {
3062                final PackageSetting ps = (PackageSetting) obj;
3063                return ps.pkgFlags;
3064            }
3065        }
3066        return 0;
3067    }
3068
3069    @Override
3070    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3071            int flags, int userId) {
3072        if (!sUserManager.exists(userId)) return null;
3073        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3074        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3075        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3076    }
3077
3078    @Override
3079    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3080            IntentFilter filter, int match, ComponentName activity) {
3081        final int userId = UserHandle.getCallingUserId();
3082        if (DEBUG_PREFERRED) {
3083            Log.v(TAG, "setLastChosenActivity intent=" + intent
3084                + " resolvedType=" + resolvedType
3085                + " flags=" + flags
3086                + " filter=" + filter
3087                + " match=" + match
3088                + " activity=" + activity);
3089            filter.dump(new PrintStreamPrinter(System.out), "    ");
3090        }
3091        intent.setComponent(null);
3092        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3093        // Find any earlier preferred or last chosen entries and nuke them
3094        findPreferredActivity(intent, resolvedType,
3095                flags, query, 0, false, true, false, userId);
3096        // Add the new activity as the last chosen for this filter
3097        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3098    }
3099
3100    @Override
3101    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3102        final int userId = UserHandle.getCallingUserId();
3103        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3104        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3105        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3106                false, false, false, userId);
3107    }
3108
3109    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3110            int flags, List<ResolveInfo> query, int userId) {
3111        if (query != null) {
3112            final int N = query.size();
3113            if (N == 1) {
3114                return query.get(0);
3115            } else if (N > 1) {
3116                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3117                // If there is more than one activity with the same priority,
3118                // then let the user decide between them.
3119                ResolveInfo r0 = query.get(0);
3120                ResolveInfo r1 = query.get(1);
3121                if (DEBUG_INTENT_MATCHING || debug) {
3122                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3123                            + r1.activityInfo.name + "=" + r1.priority);
3124                }
3125                // If the first activity has a higher priority, or a different
3126                // default, then it is always desireable to pick it.
3127                if (r0.priority != r1.priority
3128                        || r0.preferredOrder != r1.preferredOrder
3129                        || r0.isDefault != r1.isDefault) {
3130                    return query.get(0);
3131                }
3132                // If we have saved a preference for a preferred activity for
3133                // this Intent, use that.
3134                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3135                        flags, query, r0.priority, true, false, debug, userId);
3136                if (ri != null) {
3137                    return ri;
3138                }
3139                if (userId != 0) {
3140                    ri = new ResolveInfo(mResolveInfo);
3141                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3142                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3143                            ri.activityInfo.applicationInfo);
3144                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3145                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3146                    return ri;
3147                }
3148                return mResolveInfo;
3149            }
3150        }
3151        return null;
3152    }
3153
3154    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3155            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3156        final int N = query.size();
3157        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3158                .get(userId);
3159        // Get the list of persistent preferred activities that handle the intent
3160        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3161        List<PersistentPreferredActivity> pprefs = ppir != null
3162                ? ppir.queryIntent(intent, resolvedType,
3163                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3164                : null;
3165        if (pprefs != null && pprefs.size() > 0) {
3166            final int M = pprefs.size();
3167            for (int i=0; i<M; i++) {
3168                final PersistentPreferredActivity ppa = pprefs.get(i);
3169                if (DEBUG_PREFERRED || debug) {
3170                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3171                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3172                            + "\n  component=" + ppa.mComponent);
3173                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3174                }
3175                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3176                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3177                if (DEBUG_PREFERRED || debug) {
3178                    Slog.v(TAG, "Found persistent preferred activity:");
3179                    if (ai != null) {
3180                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3181                    } else {
3182                        Slog.v(TAG, "  null");
3183                    }
3184                }
3185                if (ai == null) {
3186                    // This previously registered persistent preferred activity
3187                    // component is no longer known. Ignore it and do NOT remove it.
3188                    continue;
3189                }
3190                for (int j=0; j<N; j++) {
3191                    final ResolveInfo ri = query.get(j);
3192                    if (!ri.activityInfo.applicationInfo.packageName
3193                            .equals(ai.applicationInfo.packageName)) {
3194                        continue;
3195                    }
3196                    if (!ri.activityInfo.name.equals(ai.name)) {
3197                        continue;
3198                    }
3199                    //  Found a persistent preference that can handle the intent.
3200                    if (DEBUG_PREFERRED || debug) {
3201                        Slog.v(TAG, "Returning persistent preferred activity: " +
3202                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3203                    }
3204                    return ri;
3205                }
3206            }
3207        }
3208        return null;
3209    }
3210
3211    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3212            List<ResolveInfo> query, int priority, boolean always,
3213            boolean removeMatches, boolean debug, int userId) {
3214        if (!sUserManager.exists(userId)) return null;
3215        // writer
3216        synchronized (mPackages) {
3217            if (intent.getSelector() != null) {
3218                intent = intent.getSelector();
3219            }
3220            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3221
3222            // Try to find a matching persistent preferred activity.
3223            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3224                    debug, userId);
3225
3226            // If a persistent preferred activity matched, use it.
3227            if (pri != null) {
3228                return pri;
3229            }
3230
3231            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3232            // Get the list of preferred activities that handle the intent
3233            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3234            List<PreferredActivity> prefs = pir != null
3235                    ? pir.queryIntent(intent, resolvedType,
3236                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3237                    : null;
3238            if (prefs != null && prefs.size() > 0) {
3239                // First figure out how good the original match set is.
3240                // We will only allow preferred activities that came
3241                // from the same match quality.
3242                int match = 0;
3243
3244                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3245
3246                final int N = query.size();
3247                for (int j=0; j<N; j++) {
3248                    final ResolveInfo ri = query.get(j);
3249                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3250                            + ": 0x" + Integer.toHexString(match));
3251                    if (ri.match > match) {
3252                        match = ri.match;
3253                    }
3254                }
3255
3256                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3257                        + Integer.toHexString(match));
3258
3259                match &= IntentFilter.MATCH_CATEGORY_MASK;
3260                final int M = prefs.size();
3261                for (int i=0; i<M; i++) {
3262                    final PreferredActivity pa = prefs.get(i);
3263                    if (DEBUG_PREFERRED || debug) {
3264                        Slog.v(TAG, "Checking PreferredActivity ds="
3265                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3266                                + "\n  component=" + pa.mPref.mComponent);
3267                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3268                    }
3269                    if (pa.mPref.mMatch != match) {
3270                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3271                                + Integer.toHexString(pa.mPref.mMatch));
3272                        continue;
3273                    }
3274                    // If it's not an "always" type preferred activity and that's what we're
3275                    // looking for, skip it.
3276                    if (always && !pa.mPref.mAlways) {
3277                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3278                        continue;
3279                    }
3280                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3281                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3282                    if (DEBUG_PREFERRED || debug) {
3283                        Slog.v(TAG, "Found preferred activity:");
3284                        if (ai != null) {
3285                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3286                        } else {
3287                            Slog.v(TAG, "  null");
3288                        }
3289                    }
3290                    if (ai == null) {
3291                        // This previously registered preferred activity
3292                        // component is no longer known.  Most likely an update
3293                        // to the app was installed and in the new version this
3294                        // component no longer exists.  Clean it up by removing
3295                        // it from the preferred activities list, and skip it.
3296                        Slog.w(TAG, "Removing dangling preferred activity: "
3297                                + pa.mPref.mComponent);
3298                        pir.removeFilter(pa);
3299                        continue;
3300                    }
3301                    for (int j=0; j<N; j++) {
3302                        final ResolveInfo ri = query.get(j);
3303                        if (!ri.activityInfo.applicationInfo.packageName
3304                                .equals(ai.applicationInfo.packageName)) {
3305                            continue;
3306                        }
3307                        if (!ri.activityInfo.name.equals(ai.name)) {
3308                            continue;
3309                        }
3310
3311                        if (removeMatches) {
3312                            pir.removeFilter(pa);
3313                            if (DEBUG_PREFERRED) {
3314                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3315                            }
3316                            break;
3317                        }
3318
3319                        // Okay we found a previously set preferred or last chosen app.
3320                        // If the result set is different from when this
3321                        // was created, we need to clear it and re-ask the
3322                        // user their preference, if we're looking for an "always" type entry.
3323                        if (always && !pa.mPref.sameSet(query, priority)) {
3324                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3325                                    + intent + " type " + resolvedType);
3326                            if (DEBUG_PREFERRED) {
3327                                Slog.v(TAG, "Removing preferred activity since set changed "
3328                                        + pa.mPref.mComponent);
3329                            }
3330                            pir.removeFilter(pa);
3331                            // Re-add the filter as a "last chosen" entry (!always)
3332                            PreferredActivity lastChosen = new PreferredActivity(
3333                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3334                            pir.addFilter(lastChosen);
3335                            mSettings.writePackageRestrictionsLPr(userId);
3336                            return null;
3337                        }
3338
3339                        // Yay! Either the set matched or we're looking for the last chosen
3340                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3341                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3342                        mSettings.writePackageRestrictionsLPr(userId);
3343                        return ri;
3344                    }
3345                }
3346            }
3347            mSettings.writePackageRestrictionsLPr(userId);
3348        }
3349        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3350        return null;
3351    }
3352
3353    /*
3354     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3355     */
3356    @Override
3357    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3358            int targetUserId) {
3359        mContext.enforceCallingOrSelfPermission(
3360                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3361        List<CrossProfileIntentFilter> matches =
3362                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3363        if (matches != null) {
3364            int size = matches.size();
3365            for (int i = 0; i < size; i++) {
3366                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3367            }
3368        }
3369
3370        ArrayList<String> packageNames = null;
3371        SparseArray<ArrayList<String>> fromSource =
3372                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3373        if (fromSource != null) {
3374            packageNames = fromSource.get(targetUserId);
3375        }
3376        if (packageNames.contains(intent.getPackage())) {
3377            return true;
3378        }
3379        // We need the package name, so we try to resolve with the loosest flags possible
3380        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3381                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3382        int count = resolveInfos.size();
3383        for (int i = 0; i < count; i++) {
3384            ResolveInfo resolveInfo = resolveInfos.get(i);
3385            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3386                return true;
3387            }
3388        }
3389        return false;
3390    }
3391
3392    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3393            String resolvedType, int userId) {
3394        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3395        if (resolver != null) {
3396            return resolver.queryIntent(intent, resolvedType, false, userId);
3397        }
3398        return null;
3399    }
3400
3401    @Override
3402    public List<ResolveInfo> queryIntentActivities(Intent intent,
3403            String resolvedType, int flags, int userId) {
3404        if (!sUserManager.exists(userId)) return Collections.emptyList();
3405        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3406        ComponentName comp = intent.getComponent();
3407        if (comp == null) {
3408            if (intent.getSelector() != null) {
3409                intent = intent.getSelector();
3410                comp = intent.getComponent();
3411            }
3412        }
3413
3414        if (comp != null) {
3415            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3416            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3417            if (ai != null) {
3418                final ResolveInfo ri = new ResolveInfo();
3419                ri.activityInfo = ai;
3420                list.add(ri);
3421            }
3422            return list;
3423        }
3424
3425        // reader
3426        synchronized (mPackages) {
3427            final String pkgName = intent.getPackage();
3428            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3429            if (pkgName == null) {
3430                ResolveInfo resolveInfo;
3431                if (queryCrossProfile) {
3432                    // Check if the intent needs to be forwarded to another user for this package
3433                    ArrayList<ResolveInfo> crossProfileResult =
3434                            queryIntentActivitiesCrossProfilePackage(
3435                                    intent, resolvedType, flags, userId);
3436                    if (!crossProfileResult.isEmpty()) {
3437                        // Skip the current profile
3438                        return crossProfileResult;
3439                    }
3440                    List<CrossProfileIntentFilter> matchingFilters =
3441                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3442                    // Check for results that need to skip the current profile.
3443                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3444                            resolvedType, flags, userId);
3445                    if (resolveInfo != null) {
3446                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3447                        result.add(resolveInfo);
3448                        return result;
3449                    }
3450                    // Check for cross profile results.
3451                    resolveInfo = queryCrossProfileIntents(
3452                            matchingFilters, intent, resolvedType, flags, userId);
3453                }
3454                // Check for results in the current profile.
3455                List<ResolveInfo> result = mActivities.queryIntent(
3456                        intent, resolvedType, flags, userId);
3457                if (resolveInfo != null) {
3458                    result.add(resolveInfo);
3459                }
3460                return result;
3461            }
3462            final PackageParser.Package pkg = mPackages.get(pkgName);
3463            if (pkg != null) {
3464                if (queryCrossProfile) {
3465                    ArrayList<ResolveInfo> crossProfileResult =
3466                            queryIntentActivitiesCrossProfilePackage(
3467                                    intent, resolvedType, flags, userId, pkg, pkgName);
3468                    if (!crossProfileResult.isEmpty()) {
3469                        // Skip the current profile
3470                        return crossProfileResult;
3471                    }
3472                }
3473                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3474                        pkg.activities, userId);
3475            }
3476            return new ArrayList<ResolveInfo>();
3477        }
3478    }
3479
3480    private ResolveInfo querySkipCurrentProfileIntents(
3481            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3482            int flags, int sourceUserId) {
3483        if (matchingFilters != null) {
3484            int size = matchingFilters.size();
3485            for (int i = 0; i < size; i ++) {
3486                CrossProfileIntentFilter filter = matchingFilters.get(i);
3487                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3488                    // Checking if there are activities in the target user that can handle the
3489                    // intent.
3490                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3491                            flags, sourceUserId);
3492                    if (resolveInfo != null) {
3493                        return resolveInfo;
3494                    }
3495                }
3496            }
3497        }
3498        return null;
3499    }
3500
3501    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3502            Intent intent, String resolvedType, int flags, int userId) {
3503        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3504        SparseArray<ArrayList<String>> sourceForwardingInfo =
3505                mSettings.mCrossProfilePackageInfo.get(userId);
3506        if (sourceForwardingInfo != null) {
3507            int NI = sourceForwardingInfo.size();
3508            for (int i = 0; i < NI; i++) {
3509                int targetUserId = sourceForwardingInfo.keyAt(i);
3510                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3511                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3512                        intent, resolvedType, flags, targetUserId);
3513                int NJ = resolveInfos.size();
3514                for (int j = 0; j < NJ; j++) {
3515                    ResolveInfo resolveInfo = resolveInfos.get(j);
3516                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3517                        matchingResolveInfos.add(createForwardingResolveInfo(
3518                                resolveInfo.filter, userId, targetUserId));
3519                    }
3520                }
3521            }
3522        }
3523        return matchingResolveInfos;
3524    }
3525
3526    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3527            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3528            String packageName) {
3529        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3530        SparseArray<ArrayList<String>> sourceForwardingInfo =
3531                mSettings.mCrossProfilePackageInfo.get(userId);
3532        if (sourceForwardingInfo != null) {
3533            int NI = sourceForwardingInfo.size();
3534            for (int i = 0; i < NI; i++) {
3535                int targetUserId = sourceForwardingInfo.keyAt(i);
3536                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3537                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3538                            intent, resolvedType, flags, pkg.activities, targetUserId);
3539                    int NJ = resolveInfos.size();
3540                    for (int j = 0; j < NJ; j++) {
3541                        ResolveInfo resolveInfo = resolveInfos.get(j);
3542                        matchingResolveInfos.add(createForwardingResolveInfo(
3543                                resolveInfo.filter, userId, targetUserId));
3544                    }
3545                }
3546            }
3547        }
3548        return matchingResolveInfos;
3549    }
3550
3551    // Return matching ResolveInfo if any for skip current profile intent filters.
3552    private ResolveInfo queryCrossProfileIntents(
3553            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3554            int flags, int sourceUserId) {
3555        if (matchingFilters != null) {
3556            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3557            // match the same intent. For performance reasons, it is better not to
3558            // run queryIntent twice for the same userId
3559            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3560            int size = matchingFilters.size();
3561            for (int i = 0; i < size; i++) {
3562                CrossProfileIntentFilter filter = matchingFilters.get(i);
3563                int targetUserId = filter.getTargetUserId();
3564                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3565                        && !alreadyTriedUserIds.get(targetUserId)) {
3566                    // Checking if there are activities in the target user that can handle the
3567                    // intent.
3568                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3569                            flags, sourceUserId);
3570                    if (resolveInfo != null) return resolveInfo;
3571                    alreadyTriedUserIds.put(targetUserId, true);
3572                }
3573            }
3574        }
3575        return null;
3576    }
3577
3578    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3579            String resolvedType, int flags, int sourceUserId) {
3580        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3581                resolvedType, flags, filter.getTargetUserId());
3582        if (resultTargetUser != null) {
3583            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3584        }
3585        return null;
3586    }
3587
3588    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3589            int sourceUserId, int targetUserId) {
3590        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3591        String className;
3592        if (targetUserId == UserHandle.USER_OWNER) {
3593            className = FORWARD_INTENT_TO_USER_OWNER;
3594            forwardingResolveInfo.showTargetUserIcon = true;
3595        } else {
3596            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3597        }
3598        ComponentName forwardingActivityComponentName = new ComponentName(
3599                mAndroidApplication.packageName, className);
3600        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3601                sourceUserId);
3602        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3603        forwardingResolveInfo.priority = 0;
3604        forwardingResolveInfo.preferredOrder = 0;
3605        forwardingResolveInfo.match = 0;
3606        forwardingResolveInfo.isDefault = true;
3607        forwardingResolveInfo.filter = filter;
3608        forwardingResolveInfo.targetUserId = targetUserId;
3609        return forwardingResolveInfo;
3610    }
3611
3612    @Override
3613    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3614            Intent[] specifics, String[] specificTypes, Intent intent,
3615            String resolvedType, int flags, int userId) {
3616        if (!sUserManager.exists(userId)) return Collections.emptyList();
3617        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3618                "query intent activity options");
3619        final String resultsAction = intent.getAction();
3620
3621        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3622                | PackageManager.GET_RESOLVED_FILTER, userId);
3623
3624        if (DEBUG_INTENT_MATCHING) {
3625            Log.v(TAG, "Query " + intent + ": " + results);
3626        }
3627
3628        int specificsPos = 0;
3629        int N;
3630
3631        // todo: note that the algorithm used here is O(N^2).  This
3632        // isn't a problem in our current environment, but if we start running
3633        // into situations where we have more than 5 or 10 matches then this
3634        // should probably be changed to something smarter...
3635
3636        // First we go through and resolve each of the specific items
3637        // that were supplied, taking care of removing any corresponding
3638        // duplicate items in the generic resolve list.
3639        if (specifics != null) {
3640            for (int i=0; i<specifics.length; i++) {
3641                final Intent sintent = specifics[i];
3642                if (sintent == null) {
3643                    continue;
3644                }
3645
3646                if (DEBUG_INTENT_MATCHING) {
3647                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3648                }
3649
3650                String action = sintent.getAction();
3651                if (resultsAction != null && resultsAction.equals(action)) {
3652                    // If this action was explicitly requested, then don't
3653                    // remove things that have it.
3654                    action = null;
3655                }
3656
3657                ResolveInfo ri = null;
3658                ActivityInfo ai = null;
3659
3660                ComponentName comp = sintent.getComponent();
3661                if (comp == null) {
3662                    ri = resolveIntent(
3663                        sintent,
3664                        specificTypes != null ? specificTypes[i] : null,
3665                            flags, userId);
3666                    if (ri == null) {
3667                        continue;
3668                    }
3669                    if (ri == mResolveInfo) {
3670                        // ACK!  Must do something better with this.
3671                    }
3672                    ai = ri.activityInfo;
3673                    comp = new ComponentName(ai.applicationInfo.packageName,
3674                            ai.name);
3675                } else {
3676                    ai = getActivityInfo(comp, flags, userId);
3677                    if (ai == null) {
3678                        continue;
3679                    }
3680                }
3681
3682                // Look for any generic query activities that are duplicates
3683                // of this specific one, and remove them from the results.
3684                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3685                N = results.size();
3686                int j;
3687                for (j=specificsPos; j<N; j++) {
3688                    ResolveInfo sri = results.get(j);
3689                    if ((sri.activityInfo.name.equals(comp.getClassName())
3690                            && sri.activityInfo.applicationInfo.packageName.equals(
3691                                    comp.getPackageName()))
3692                        || (action != null && sri.filter.matchAction(action))) {
3693                        results.remove(j);
3694                        if (DEBUG_INTENT_MATCHING) Log.v(
3695                            TAG, "Removing duplicate item from " + j
3696                            + " due to specific " + specificsPos);
3697                        if (ri == null) {
3698                            ri = sri;
3699                        }
3700                        j--;
3701                        N--;
3702                    }
3703                }
3704
3705                // Add this specific item to its proper place.
3706                if (ri == null) {
3707                    ri = new ResolveInfo();
3708                    ri.activityInfo = ai;
3709                }
3710                results.add(specificsPos, ri);
3711                ri.specificIndex = i;
3712                specificsPos++;
3713            }
3714        }
3715
3716        // Now we go through the remaining generic results and remove any
3717        // duplicate actions that are found here.
3718        N = results.size();
3719        for (int i=specificsPos; i<N-1; i++) {
3720            final ResolveInfo rii = results.get(i);
3721            if (rii.filter == null) {
3722                continue;
3723            }
3724
3725            // Iterate over all of the actions of this result's intent
3726            // filter...  typically this should be just one.
3727            final Iterator<String> it = rii.filter.actionsIterator();
3728            if (it == null) {
3729                continue;
3730            }
3731            while (it.hasNext()) {
3732                final String action = it.next();
3733                if (resultsAction != null && resultsAction.equals(action)) {
3734                    // If this action was explicitly requested, then don't
3735                    // remove things that have it.
3736                    continue;
3737                }
3738                for (int j=i+1; j<N; j++) {
3739                    final ResolveInfo rij = results.get(j);
3740                    if (rij.filter != null && rij.filter.hasAction(action)) {
3741                        results.remove(j);
3742                        if (DEBUG_INTENT_MATCHING) Log.v(
3743                            TAG, "Removing duplicate item from " + j
3744                            + " due to action " + action + " at " + i);
3745                        j--;
3746                        N--;
3747                    }
3748                }
3749            }
3750
3751            // If the caller didn't request filter information, drop it now
3752            // so we don't have to marshall/unmarshall it.
3753            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3754                rii.filter = null;
3755            }
3756        }
3757
3758        // Filter out the caller activity if so requested.
3759        if (caller != null) {
3760            N = results.size();
3761            for (int i=0; i<N; i++) {
3762                ActivityInfo ainfo = results.get(i).activityInfo;
3763                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3764                        && caller.getClassName().equals(ainfo.name)) {
3765                    results.remove(i);
3766                    break;
3767                }
3768            }
3769        }
3770
3771        // If the caller didn't request filter information,
3772        // drop them now so we don't have to
3773        // marshall/unmarshall it.
3774        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3775            N = results.size();
3776            for (int i=0; i<N; i++) {
3777                results.get(i).filter = null;
3778            }
3779        }
3780
3781        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3782        return results;
3783    }
3784
3785    @Override
3786    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3787            int userId) {
3788        if (!sUserManager.exists(userId)) return Collections.emptyList();
3789        ComponentName comp = intent.getComponent();
3790        if (comp == null) {
3791            if (intent.getSelector() != null) {
3792                intent = intent.getSelector();
3793                comp = intent.getComponent();
3794            }
3795        }
3796        if (comp != null) {
3797            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3798            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3799            if (ai != null) {
3800                ResolveInfo ri = new ResolveInfo();
3801                ri.activityInfo = ai;
3802                list.add(ri);
3803            }
3804            return list;
3805        }
3806
3807        // reader
3808        synchronized (mPackages) {
3809            String pkgName = intent.getPackage();
3810            if (pkgName == null) {
3811                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3812            }
3813            final PackageParser.Package pkg = mPackages.get(pkgName);
3814            if (pkg != null) {
3815                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3816                        userId);
3817            }
3818            return null;
3819        }
3820    }
3821
3822    @Override
3823    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3824        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3825        if (!sUserManager.exists(userId)) return null;
3826        if (query != null) {
3827            if (query.size() >= 1) {
3828                // If there is more than one service with the same priority,
3829                // just arbitrarily pick the first one.
3830                return query.get(0);
3831            }
3832        }
3833        return null;
3834    }
3835
3836    @Override
3837    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3838            int userId) {
3839        if (!sUserManager.exists(userId)) return Collections.emptyList();
3840        ComponentName comp = intent.getComponent();
3841        if (comp == null) {
3842            if (intent.getSelector() != null) {
3843                intent = intent.getSelector();
3844                comp = intent.getComponent();
3845            }
3846        }
3847        if (comp != null) {
3848            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3849            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3850            if (si != null) {
3851                final ResolveInfo ri = new ResolveInfo();
3852                ri.serviceInfo = si;
3853                list.add(ri);
3854            }
3855            return list;
3856        }
3857
3858        // reader
3859        synchronized (mPackages) {
3860            String pkgName = intent.getPackage();
3861            if (pkgName == null) {
3862                return mServices.queryIntent(intent, resolvedType, flags, userId);
3863            }
3864            final PackageParser.Package pkg = mPackages.get(pkgName);
3865            if (pkg != null) {
3866                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3867                        userId);
3868            }
3869            return null;
3870        }
3871    }
3872
3873    @Override
3874    public List<ResolveInfo> queryIntentContentProviders(
3875            Intent intent, String resolvedType, int flags, int userId) {
3876        if (!sUserManager.exists(userId)) return Collections.emptyList();
3877        ComponentName comp = intent.getComponent();
3878        if (comp == null) {
3879            if (intent.getSelector() != null) {
3880                intent = intent.getSelector();
3881                comp = intent.getComponent();
3882            }
3883        }
3884        if (comp != null) {
3885            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3886            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3887            if (pi != null) {
3888                final ResolveInfo ri = new ResolveInfo();
3889                ri.providerInfo = pi;
3890                list.add(ri);
3891            }
3892            return list;
3893        }
3894
3895        // reader
3896        synchronized (mPackages) {
3897            String pkgName = intent.getPackage();
3898            if (pkgName == null) {
3899                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3900            }
3901            final PackageParser.Package pkg = mPackages.get(pkgName);
3902            if (pkg != null) {
3903                return mProviders.queryIntentForPackage(
3904                        intent, resolvedType, flags, pkg.providers, userId);
3905            }
3906            return null;
3907        }
3908    }
3909
3910    @Override
3911    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3912        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3913
3914        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3915
3916        // writer
3917        synchronized (mPackages) {
3918            ArrayList<PackageInfo> list;
3919            if (listUninstalled) {
3920                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3921                for (PackageSetting ps : mSettings.mPackages.values()) {
3922                    PackageInfo pi;
3923                    if (ps.pkg != null) {
3924                        pi = generatePackageInfo(ps.pkg, flags, userId);
3925                    } else {
3926                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3927                    }
3928                    if (pi != null) {
3929                        list.add(pi);
3930                    }
3931                }
3932            } else {
3933                list = new ArrayList<PackageInfo>(mPackages.size());
3934                for (PackageParser.Package p : mPackages.values()) {
3935                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3936                    if (pi != null) {
3937                        list.add(pi);
3938                    }
3939                }
3940            }
3941
3942            return new ParceledListSlice<PackageInfo>(list);
3943        }
3944    }
3945
3946    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3947            String[] permissions, boolean[] tmp, int flags, int userId) {
3948        int numMatch = 0;
3949        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3950        for (int i=0; i<permissions.length; i++) {
3951            if (gp.grantedPermissions.contains(permissions[i])) {
3952                tmp[i] = true;
3953                numMatch++;
3954            } else {
3955                tmp[i] = false;
3956            }
3957        }
3958        if (numMatch == 0) {
3959            return;
3960        }
3961        PackageInfo pi;
3962        if (ps.pkg != null) {
3963            pi = generatePackageInfo(ps.pkg, flags, userId);
3964        } else {
3965            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3966        }
3967        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3968            if (numMatch == permissions.length) {
3969                pi.requestedPermissions = permissions;
3970            } else {
3971                pi.requestedPermissions = new String[numMatch];
3972                numMatch = 0;
3973                for (int i=0; i<permissions.length; i++) {
3974                    if (tmp[i]) {
3975                        pi.requestedPermissions[numMatch] = permissions[i];
3976                        numMatch++;
3977                    }
3978                }
3979            }
3980        }
3981        list.add(pi);
3982    }
3983
3984    @Override
3985    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3986            String[] permissions, int flags, int userId) {
3987        if (!sUserManager.exists(userId)) return null;
3988        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3989
3990        // writer
3991        synchronized (mPackages) {
3992            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3993            boolean[] tmpBools = new boolean[permissions.length];
3994            if (listUninstalled) {
3995                for (PackageSetting ps : mSettings.mPackages.values()) {
3996                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3997                }
3998            } else {
3999                for (PackageParser.Package pkg : mPackages.values()) {
4000                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4001                    if (ps != null) {
4002                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4003                                userId);
4004                    }
4005                }
4006            }
4007
4008            return new ParceledListSlice<PackageInfo>(list);
4009        }
4010    }
4011
4012    @Override
4013    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4014        if (!sUserManager.exists(userId)) return null;
4015        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4016
4017        // writer
4018        synchronized (mPackages) {
4019            ArrayList<ApplicationInfo> list;
4020            if (listUninstalled) {
4021                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4022                for (PackageSetting ps : mSettings.mPackages.values()) {
4023                    ApplicationInfo ai;
4024                    if (ps.pkg != null) {
4025                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4026                                ps.readUserState(userId), userId);
4027                    } else {
4028                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4029                    }
4030                    if (ai != null) {
4031                        list.add(ai);
4032                    }
4033                }
4034            } else {
4035                list = new ArrayList<ApplicationInfo>(mPackages.size());
4036                for (PackageParser.Package p : mPackages.values()) {
4037                    if (p.mExtras != null) {
4038                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4039                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4040                        if (ai != null) {
4041                            list.add(ai);
4042                        }
4043                    }
4044                }
4045            }
4046
4047            return new ParceledListSlice<ApplicationInfo>(list);
4048        }
4049    }
4050
4051    public List<ApplicationInfo> getPersistentApplications(int flags) {
4052        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4053
4054        // reader
4055        synchronized (mPackages) {
4056            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4057            final int userId = UserHandle.getCallingUserId();
4058            while (i.hasNext()) {
4059                final PackageParser.Package p = i.next();
4060                if (p.applicationInfo != null
4061                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4062                        && (!mSafeMode || isSystemApp(p))) {
4063                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4064                    if (ps != null) {
4065                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4066                                ps.readUserState(userId), userId);
4067                        if (ai != null) {
4068                            finalList.add(ai);
4069                        }
4070                    }
4071                }
4072            }
4073        }
4074
4075        return finalList;
4076    }
4077
4078    @Override
4079    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4080        if (!sUserManager.exists(userId)) return null;
4081        // reader
4082        synchronized (mPackages) {
4083            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4084            PackageSetting ps = provider != null
4085                    ? mSettings.mPackages.get(provider.owner.packageName)
4086                    : null;
4087            return ps != null
4088                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4089                    && (!mSafeMode || (provider.info.applicationInfo.flags
4090                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4091                    ? PackageParser.generateProviderInfo(provider, flags,
4092                            ps.readUserState(userId), userId)
4093                    : null;
4094        }
4095    }
4096
4097    /**
4098     * @deprecated
4099     */
4100    @Deprecated
4101    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4102        // reader
4103        synchronized (mPackages) {
4104            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4105                    .entrySet().iterator();
4106            final int userId = UserHandle.getCallingUserId();
4107            while (i.hasNext()) {
4108                Map.Entry<String, PackageParser.Provider> entry = i.next();
4109                PackageParser.Provider p = entry.getValue();
4110                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4111
4112                if (ps != null && p.syncable
4113                        && (!mSafeMode || (p.info.applicationInfo.flags
4114                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4115                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4116                            ps.readUserState(userId), userId);
4117                    if (info != null) {
4118                        outNames.add(entry.getKey());
4119                        outInfo.add(info);
4120                    }
4121                }
4122            }
4123        }
4124    }
4125
4126    @Override
4127    public List<ProviderInfo> queryContentProviders(String processName,
4128            int uid, int flags) {
4129        ArrayList<ProviderInfo> finalList = null;
4130        // reader
4131        synchronized (mPackages) {
4132            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4133            final int userId = processName != null ?
4134                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4135            while (i.hasNext()) {
4136                final PackageParser.Provider p = i.next();
4137                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4138                if (ps != null && p.info.authority != null
4139                        && (processName == null
4140                                || (p.info.processName.equals(processName)
4141                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4142                        && mSettings.isEnabledLPr(p.info, flags, userId)
4143                        && (!mSafeMode
4144                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4145                    if (finalList == null) {
4146                        finalList = new ArrayList<ProviderInfo>(3);
4147                    }
4148                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4149                            ps.readUserState(userId), userId);
4150                    if (info != null) {
4151                        finalList.add(info);
4152                    }
4153                }
4154            }
4155        }
4156
4157        if (finalList != null) {
4158            Collections.sort(finalList, mProviderInitOrderSorter);
4159        }
4160
4161        return finalList;
4162    }
4163
4164    @Override
4165    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4166            int flags) {
4167        // reader
4168        synchronized (mPackages) {
4169            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4170            return PackageParser.generateInstrumentationInfo(i, flags);
4171        }
4172    }
4173
4174    @Override
4175    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4176            int flags) {
4177        ArrayList<InstrumentationInfo> finalList =
4178            new ArrayList<InstrumentationInfo>();
4179
4180        // reader
4181        synchronized (mPackages) {
4182            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4183            while (i.hasNext()) {
4184                final PackageParser.Instrumentation p = i.next();
4185                if (targetPackage == null
4186                        || targetPackage.equals(p.info.targetPackage)) {
4187                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4188                            flags);
4189                    if (ii != null) {
4190                        finalList.add(ii);
4191                    }
4192                }
4193            }
4194        }
4195
4196        return finalList;
4197    }
4198
4199    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4200        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4201        if (overlays == null) {
4202            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4203            return;
4204        }
4205        for (PackageParser.Package opkg : overlays.values()) {
4206            // Not much to do if idmap fails: we already logged the error
4207            // and we certainly don't want to abort installation of pkg simply
4208            // because an overlay didn't fit properly. For these reasons,
4209            // ignore the return value of createIdmapForPackagePairLI.
4210            createIdmapForPackagePairLI(pkg, opkg);
4211        }
4212    }
4213
4214    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4215            PackageParser.Package opkg) {
4216        if (!opkg.mTrustedOverlay) {
4217            Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " +
4218                    opkg.codePath + ": overlay not trusted");
4219            return false;
4220        }
4221        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4222        if (overlaySet == null) {
4223            Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " +
4224                    opkg.codePath + " but target package has no known overlays");
4225            return false;
4226        }
4227        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4228        // TODO: generate idmap for split APKs
4229        if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) {
4230            Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath);
4231            return false;
4232        }
4233        PackageParser.Package[] overlayArray =
4234            overlaySet.values().toArray(new PackageParser.Package[0]);
4235        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4236            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4237                return p1.mOverlayPriority - p2.mOverlayPriority;
4238            }
4239        };
4240        Arrays.sort(overlayArray, cmp);
4241
4242        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4243        int i = 0;
4244        for (PackageParser.Package p : overlayArray) {
4245            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4246        }
4247        return true;
4248    }
4249
4250    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4251        String[] files = dir.list();
4252        if (files == null) {
4253            Log.d(TAG, "No files in app dir " + dir);
4254            return;
4255        }
4256
4257        if (DEBUG_PACKAGE_SCANNING) {
4258            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4259                    + " flags=0x" + Integer.toHexString(flags));
4260        }
4261
4262        int i;
4263        for (i=0; i<files.length; i++) {
4264            File file = new File(dir, files[i]);
4265            if (!isPackageFilename(files[i])) {
4266                // Ignore entries which are not apk's
4267                continue;
4268            }
4269            PackageParser.Package pkg = scanPackageLI(file,
4270                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4271            // Don't mess around with apps in system partition.
4272            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4273                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4274                // Delete the apk
4275                Slog.w(TAG, "Cleaning up failed install of " + file);
4276                file.delete();
4277            }
4278        }
4279    }
4280
4281    private static File getSettingsProblemFile() {
4282        File dataDir = Environment.getDataDirectory();
4283        File systemDir = new File(dataDir, "system");
4284        File fname = new File(systemDir, "uiderrors.txt");
4285        return fname;
4286    }
4287
4288    static void reportSettingsProblem(int priority, String msg) {
4289        try {
4290            File fname = getSettingsProblemFile();
4291            FileOutputStream out = new FileOutputStream(fname, true);
4292            PrintWriter pw = new FastPrintWriter(out);
4293            SimpleDateFormat formatter = new SimpleDateFormat();
4294            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4295            pw.println(dateString + ": " + msg);
4296            pw.close();
4297            FileUtils.setPermissions(
4298                    fname.toString(),
4299                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4300                    -1, -1);
4301        } catch (java.io.IOException e) {
4302        }
4303        Slog.println(priority, TAG, msg);
4304    }
4305
4306    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4307            PackageParser.Package pkg, File srcFile, int parseFlags) {
4308        if (ps != null
4309                && ps.codePath.equals(srcFile)
4310                && ps.timeStamp == srcFile.lastModified()
4311                && !isCompatSignatureUpdateNeeded(pkg)) {
4312            if (ps.signatures.mSignatures != null
4313                    && ps.signatures.mSignatures.length != 0) {
4314                // Optimization: reuse the existing cached certificates
4315                // if the package appears to be unchanged.
4316                pkg.mSignatures = ps.signatures.mSignatures;
4317                return true;
4318            }
4319
4320            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4321        } else {
4322            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4323        }
4324
4325        try {
4326            pp.collectCertificates(pkg, parseFlags);
4327            pp.collectManifestDigest(pkg);
4328        } catch (PackageParserException e) {
4329            mLastScanError = e.error;
4330            return false;
4331        }
4332        return true;
4333    }
4334
4335    /*
4336     *  Scan a package and return the newly parsed package.
4337     *  Returns null in case of errors and the error code is stored in mLastScanError
4338     */
4339    private PackageParser.Package scanPackageLI(File scanFile,
4340            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4341        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4342        String scanPath = scanFile.getPath();
4343        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4344        parseFlags |= mDefParseFlags;
4345        PackageParser pp = new PackageParser();
4346        pp.setSeparateProcesses(mSeparateProcesses);
4347        pp.setOnlyCoreApps(mOnlyCore);
4348        pp.setDisplayMetrics(mMetrics);
4349
4350        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4351            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4352        }
4353
4354        final PackageParser.Package pkg;
4355        try {
4356            pkg = pp.parseMonolithicPackage(scanFile, parseFlags);
4357        } catch (PackageParserException e) {
4358            mLastScanError = e.error;
4359            return null;
4360        }
4361
4362        PackageSetting ps = null;
4363        PackageSetting updatedPkg;
4364        // reader
4365        synchronized (mPackages) {
4366            // Look to see if we already know about this package.
4367            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4368            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4369                // This package has been renamed to its original name.  Let's
4370                // use that.
4371                ps = mSettings.peekPackageLPr(oldName);
4372            }
4373            // If there was no original package, see one for the real package name.
4374            if (ps == null) {
4375                ps = mSettings.peekPackageLPr(pkg.packageName);
4376            }
4377            // Check to see if this package could be hiding/updating a system
4378            // package.  Must look for it either under the original or real
4379            // package name depending on our state.
4380            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4381            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4382        }
4383        boolean updatedPkgBetter = false;
4384        // First check if this is a system package that may involve an update
4385        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4386            if (ps != null && !ps.codePath.equals(scanFile)) {
4387                // The path has changed from what was last scanned...  check the
4388                // version of the new path against what we have stored to determine
4389                // what to do.
4390                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4391                if (pkg.mVersionCode < ps.versionCode) {
4392                    // The system package has been updated and the code path does not match
4393                    // Ignore entry. Skip it.
4394                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4395                            + " ignored: updated version " + ps.versionCode
4396                            + " better than this " + pkg.mVersionCode);
4397                    if (!updatedPkg.codePath.equals(scanFile)) {
4398                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4399                                + ps.name + " changing from " + updatedPkg.codePathString
4400                                + " to " + scanFile);
4401                        updatedPkg.codePath = scanFile;
4402                        updatedPkg.codePathString = scanFile.toString();
4403                        // This is the point at which we know that the system-disk APK
4404                        // for this package has moved during a reboot (e.g. due to an OTA),
4405                        // so we need to reevaluate it for privilege policy.
4406                        if (locationIsPrivileged(scanFile)) {
4407                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4408                        }
4409                    }
4410                    updatedPkg.pkg = pkg;
4411                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4412                    return null;
4413                } else {
4414                    // The current app on the system partition is better than
4415                    // what we have updated to on the data partition; switch
4416                    // back to the system partition version.
4417                    // At this point, its safely assumed that package installation for
4418                    // apps in system partition will go through. If not there won't be a working
4419                    // version of the app
4420                    // writer
4421                    synchronized (mPackages) {
4422                        // Just remove the loaded entries from package lists.
4423                        mPackages.remove(ps.name);
4424                    }
4425                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4426                            + "reverting from " + ps.codePathString
4427                            + ": new version " + pkg.mVersionCode
4428                            + " better than installed " + ps.versionCode);
4429
4430                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4431                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4432                            getAppInstructionSetFromSettings(ps));
4433                    synchronized (mInstallLock) {
4434                        args.cleanUpResourcesLI();
4435                    }
4436                    synchronized (mPackages) {
4437                        mSettings.enableSystemPackageLPw(ps.name);
4438                    }
4439                    updatedPkgBetter = true;
4440                }
4441            }
4442        }
4443
4444        if (updatedPkg != null) {
4445            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4446            // initially
4447            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4448
4449            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4450            // flag set initially
4451            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4452                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4453            }
4454        }
4455        // Verify certificates against what was last scanned
4456        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4457            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4458            return null;
4459        }
4460
4461        /*
4462         * A new system app appeared, but we already had a non-system one of the
4463         * same name installed earlier.
4464         */
4465        boolean shouldHideSystemApp = false;
4466        if (updatedPkg == null && ps != null
4467                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4468            /*
4469             * Check to make sure the signatures match first. If they don't,
4470             * wipe the installed application and its data.
4471             */
4472            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4473                    != PackageManager.SIGNATURE_MATCH) {
4474                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4475                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4476                ps = null;
4477            } else {
4478                /*
4479                 * If the newly-added system app is an older version than the
4480                 * already installed version, hide it. It will be scanned later
4481                 * and re-added like an update.
4482                 */
4483                if (pkg.mVersionCode < ps.versionCode) {
4484                    shouldHideSystemApp = true;
4485                } else {
4486                    /*
4487                     * The newly found system app is a newer version that the
4488                     * one previously installed. Simply remove the
4489                     * already-installed application and replace it with our own
4490                     * while keeping the application data.
4491                     */
4492                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4493                            + ps.codePathString + ": new version " + pkg.mVersionCode
4494                            + " better than installed " + ps.versionCode);
4495                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4496                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4497                            getAppInstructionSetFromSettings(ps));
4498                    synchronized (mInstallLock) {
4499                        args.cleanUpResourcesLI();
4500                    }
4501                }
4502            }
4503        }
4504
4505        // The apk is forward locked (not public) if its code and resources
4506        // are kept in different files. (except for app in either system or
4507        // vendor path).
4508        // TODO grab this value from PackageSettings
4509        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4510            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4511                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4512            }
4513        }
4514
4515        final String codePath = pkg.codePath;
4516        final String[] splitCodePaths = pkg.splitCodePaths;
4517
4518        String resPath = null;
4519        String[] splitResPaths = null;
4520        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4521            if (ps != null && ps.resourcePathString != null) {
4522                resPath = ps.resourcePathString;
4523                splitResPaths = deriveSplitResPaths(pkg.splitCodePaths);
4524            } else {
4525                // Should not happen at all. Just log an error.
4526                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4527            }
4528        } else {
4529            resPath = pkg.codePath;
4530            splitResPaths = pkg.splitCodePaths;
4531        }
4532
4533        // Set application objects path explicitly.
4534        pkg.applicationInfo.sourceDir = codePath;
4535        pkg.applicationInfo.publicSourceDir = resPath;
4536        pkg.applicationInfo.splitSourceDirs = splitCodePaths;
4537        pkg.applicationInfo.splitPublicSourceDirs = splitResPaths;
4538
4539        // Note that we invoke the following method only if we are about to unpack an application
4540        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4541                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4542
4543        /*
4544         * If the system app should be overridden by a previously installed
4545         * data, hide the system app now and let the /data/app scan pick it up
4546         * again.
4547         */
4548        if (shouldHideSystemApp) {
4549            synchronized (mPackages) {
4550                /*
4551                 * We have to grant systems permissions before we hide, because
4552                 * grantPermissions will assume the package update is trying to
4553                 * expand its permissions.
4554                 */
4555                grantPermissionsLPw(pkg, true);
4556                mSettings.disableSystemPackageLPw(pkg.packageName);
4557            }
4558        }
4559
4560        return scannedPkg;
4561    }
4562
4563    private static String fixProcessName(String defProcessName,
4564            String processName, int uid) {
4565        if (processName == null) {
4566            return defProcessName;
4567        }
4568        return processName;
4569    }
4570
4571    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4572        if (pkgSetting.signatures.mSignatures != null) {
4573            // Already existing package. Make sure signatures match
4574            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4575                    == PackageManager.SIGNATURE_MATCH;
4576            if (!match) {
4577                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4578                        == PackageManager.SIGNATURE_MATCH;
4579            }
4580            if (!match) {
4581                Slog.e(TAG, "Package " + pkg.packageName
4582                        + " signatures do not match the previously installed version; ignoring!");
4583                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4584                return false;
4585            }
4586        }
4587        // Check for shared user signatures
4588        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4589            // Already existing package. Make sure signatures match
4590            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4591                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4592            if (!match) {
4593                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4594                        == PackageManager.SIGNATURE_MATCH;
4595            }
4596            if (!match) {
4597                Slog.e(TAG, "Package " + pkg.packageName
4598                        + " has no signatures that match those in shared user "
4599                        + pkgSetting.sharedUser.name + "; ignoring!");
4600                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4601                return false;
4602            }
4603        }
4604        return true;
4605    }
4606
4607    /**
4608     * Enforces that only the system UID or root's UID can call a method exposed
4609     * via Binder.
4610     *
4611     * @param message used as message if SecurityException is thrown
4612     * @throws SecurityException if the caller is not system or root
4613     */
4614    private static final void enforceSystemOrRoot(String message) {
4615        final int uid = Binder.getCallingUid();
4616        if (uid != Process.SYSTEM_UID && uid != 0) {
4617            throw new SecurityException(message);
4618        }
4619    }
4620
4621    @Override
4622    public void performBootDexOpt() {
4623        enforceSystemOrRoot("Only the system can request dexopt be performed");
4624
4625        final HashSet<PackageParser.Package> pkgs;
4626        synchronized (mPackages) {
4627            pkgs = mDeferredDexOpt;
4628            mDeferredDexOpt = null;
4629        }
4630
4631        if (pkgs != null) {
4632            // Filter out packages that aren't recently used.
4633            //
4634            // The exception is first boot of a non-eng device, which
4635            // should do a full dexopt.
4636            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4637            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4638                // TODO: add a property to control this?
4639                long dexOptLRUThresholdInMinutes;
4640                if (eng) {
4641                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4642                } else {
4643                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4644                }
4645                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4646
4647                int total = pkgs.size();
4648                int skipped = 0;
4649                long now = System.currentTimeMillis();
4650                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4651                    PackageParser.Package pkg = i.next();
4652                    long then = pkg.mLastPackageUsageTimeInMills;
4653                    if (then + dexOptLRUThresholdInMills < now) {
4654                        if (DEBUG_DEXOPT) {
4655                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4656                                  ((then == 0) ? "never" : new Date(then)));
4657                        }
4658                        i.remove();
4659                        skipped++;
4660                    }
4661                }
4662                if (DEBUG_DEXOPT) {
4663                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4664                }
4665            }
4666
4667            int i = 0;
4668            for (PackageParser.Package pkg : pkgs) {
4669                i++;
4670                if (DEBUG_DEXOPT) {
4671                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4672                          + ": " + pkg.packageName);
4673                }
4674                if (!isFirstBoot()) {
4675                    try {
4676                        ActivityManagerNative.getDefault().showBootMessage(
4677                                mContext.getResources().getString(
4678                                        R.string.android_upgrading_apk,
4679                                        i, pkgs.size()), true);
4680                    } catch (RemoteException e) {
4681                    }
4682                }
4683                PackageParser.Package p = pkg;
4684                synchronized (mInstallLock) {
4685                    if (p.mDexOptNeeded) {
4686                        performDexOptLI(p, false /* force dex */, false /* defer */,
4687                                true /* include dependencies */);
4688                    }
4689                }
4690            }
4691        }
4692    }
4693
4694    @Override
4695    public boolean performDexOpt(String packageName) {
4696        enforceSystemOrRoot("Only the system can request dexopt be performed");
4697        return performDexOpt(packageName, true);
4698    }
4699
4700    public boolean performDexOpt(String packageName, boolean updateUsage) {
4701
4702        PackageParser.Package p;
4703        synchronized (mPackages) {
4704            p = mPackages.get(packageName);
4705            if (p == null) {
4706                return false;
4707            }
4708            if (updateUsage) {
4709                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4710            }
4711            mPackageUsage.write(false);
4712            if (!p.mDexOptNeeded) {
4713                return false;
4714            }
4715        }
4716
4717        synchronized (mInstallLock) {
4718            return performDexOptLI(p, false /* force dex */, false /* defer */,
4719                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4720        }
4721    }
4722
4723    public HashSet<String> getPackagesThatNeedDexOpt() {
4724        HashSet<String> pkgs = null;
4725        synchronized (mPackages) {
4726            for (PackageParser.Package p : mPackages.values()) {
4727                if (DEBUG_DEXOPT) {
4728                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4729                }
4730                if (!p.mDexOptNeeded) {
4731                    continue;
4732                }
4733                if (pkgs == null) {
4734                    pkgs = new HashSet<String>();
4735                }
4736                pkgs.add(p.packageName);
4737            }
4738        }
4739        return pkgs;
4740    }
4741
4742    public void shutdown() {
4743        mPackageUsage.write(true);
4744    }
4745
4746    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4747             boolean forceDex, boolean defer, HashSet<String> done) {
4748        for (int i=0; i<libs.size(); i++) {
4749            PackageParser.Package libPkg;
4750            String libName;
4751            synchronized (mPackages) {
4752                libName = libs.get(i);
4753                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4754                if (lib != null && lib.apk != null) {
4755                    libPkg = mPackages.get(lib.apk);
4756                } else {
4757                    libPkg = null;
4758                }
4759            }
4760            if (libPkg != null && !done.contains(libName)) {
4761                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4762            }
4763        }
4764    }
4765
4766    static final int DEX_OPT_SKIPPED = 0;
4767    static final int DEX_OPT_PERFORMED = 1;
4768    static final int DEX_OPT_DEFERRED = 2;
4769    static final int DEX_OPT_FAILED = -1;
4770
4771    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4772            boolean forceDex, boolean defer, HashSet<String> done) {
4773        final String instructionSet = instructionSetOverride != null ?
4774                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4775
4776        if (done != null) {
4777            done.add(pkg.packageName);
4778            if (pkg.usesLibraries != null) {
4779                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4780            }
4781            if (pkg.usesOptionalLibraries != null) {
4782                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4783            }
4784        }
4785
4786        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4787            final Collection<String> paths = pkg.getAllCodePaths();
4788            for (String path : paths) {
4789                try {
4790                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4791                            pkg.packageName, instructionSet, defer);
4792                    // There are three basic cases here:
4793                    // 1.) we need to dexopt, either because we are forced or it is needed
4794                    // 2.) we are defering a needed dexopt
4795                    // 3.) we are skipping an unneeded dexopt
4796                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4797                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4798                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4799                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4800                                                    pkg.packageName, instructionSet);
4801                        // Note that we ran dexopt, since rerunning will
4802                        // probably just result in an error again.
4803                        pkg.mDexOptNeeded = false;
4804                        if (ret < 0) {
4805                            return DEX_OPT_FAILED;
4806                        }
4807                        return DEX_OPT_PERFORMED;
4808                    }
4809                    if (defer && isDexOptNeededInternal) {
4810                        if (mDeferredDexOpt == null) {
4811                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4812                        }
4813                        mDeferredDexOpt.add(pkg);
4814                        return DEX_OPT_DEFERRED;
4815                    }
4816                    pkg.mDexOptNeeded = false;
4817                    return DEX_OPT_SKIPPED;
4818                } catch (FileNotFoundException e) {
4819                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4820                    return DEX_OPT_FAILED;
4821                } catch (IOException e) {
4822                    Slog.w(TAG, "IOException reading apk: " + path, e);
4823                    return DEX_OPT_FAILED;
4824                } catch (StaleDexCacheError e) {
4825                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4826                    return DEX_OPT_FAILED;
4827                } catch (Exception e) {
4828                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4829                    return DEX_OPT_FAILED;
4830                }
4831            }
4832        }
4833        return DEX_OPT_SKIPPED;
4834    }
4835
4836    private String getAppInstructionSet(ApplicationInfo info) {
4837        String instructionSet = getPreferredInstructionSet();
4838
4839        if (info.cpuAbi != null) {
4840            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4841        }
4842
4843        return instructionSet;
4844    }
4845
4846    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4847        String instructionSet = getPreferredInstructionSet();
4848
4849        if (ps.cpuAbiString != null) {
4850            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4851        }
4852
4853        return instructionSet;
4854    }
4855
4856    private static String getPreferredInstructionSet() {
4857        if (sPreferredInstructionSet == null) {
4858            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4859        }
4860
4861        return sPreferredInstructionSet;
4862    }
4863
4864    private static List<String> getAllInstructionSets() {
4865        final String[] allAbis = Build.SUPPORTED_ABIS;
4866        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4867
4868        for (String abi : allAbis) {
4869            final String instructionSet = VMRuntime.getInstructionSet(abi);
4870            if (!allInstructionSets.contains(instructionSet)) {
4871                allInstructionSets.add(instructionSet);
4872            }
4873        }
4874
4875        return allInstructionSets;
4876    }
4877
4878    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4879            boolean inclDependencies) {
4880        HashSet<String> done;
4881        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4882            done = new HashSet<String>();
4883            done.add(pkg.packageName);
4884        } else {
4885            done = null;
4886        }
4887        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4888    }
4889
4890    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4891        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4892            Slog.w(TAG, "Unable to update from " + oldPkg.name
4893                    + " to " + newPkg.packageName
4894                    + ": old package not in system partition");
4895            return false;
4896        } else if (mPackages.get(oldPkg.name) != null) {
4897            Slog.w(TAG, "Unable to update from " + oldPkg.name
4898                    + " to " + newPkg.packageName
4899                    + ": old package still exists");
4900            return false;
4901        }
4902        return true;
4903    }
4904
4905    File getDataPathForUser(int userId) {
4906        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4907    }
4908
4909    private File getDataPathForPackage(String packageName, int userId) {
4910        /*
4911         * Until we fully support multiple users, return the directory we
4912         * previously would have. The PackageManagerTests will need to be
4913         * revised when this is changed back..
4914         */
4915        if (userId == 0) {
4916            return new File(mAppDataDir, packageName);
4917        } else {
4918            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4919                + File.separator + packageName);
4920        }
4921    }
4922
4923    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4924        int[] users = sUserManager.getUserIds();
4925        int res = mInstaller.install(packageName, uid, uid, seinfo);
4926        if (res < 0) {
4927            return res;
4928        }
4929        for (int user : users) {
4930            if (user != 0) {
4931                res = mInstaller.createUserData(packageName,
4932                        UserHandle.getUid(user, uid), user, seinfo);
4933                if (res < 0) {
4934                    return res;
4935                }
4936            }
4937        }
4938        return res;
4939    }
4940
4941    private int removeDataDirsLI(String packageName) {
4942        int[] users = sUserManager.getUserIds();
4943        int res = 0;
4944        for (int user : users) {
4945            int resInner = mInstaller.remove(packageName, user);
4946            if (resInner < 0) {
4947                res = resInner;
4948            }
4949        }
4950
4951        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4952        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4953        if (!nativeLibraryFile.delete()) {
4954            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4955        }
4956
4957        return res;
4958    }
4959
4960    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4961            PackageParser.Package changingLib) {
4962        if (file.path != null) {
4963            usesLibraryFiles.add(file.path);
4964            return;
4965        }
4966        PackageParser.Package p = mPackages.get(file.apk);
4967        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4968            // If we are doing this while in the middle of updating a library apk,
4969            // then we need to make sure to use that new apk for determining the
4970            // dependencies here.  (We haven't yet finished committing the new apk
4971            // to the package manager state.)
4972            if (p == null || p.packageName.equals(changingLib.packageName)) {
4973                p = changingLib;
4974            }
4975        }
4976        if (p != null) {
4977            usesLibraryFiles.addAll(p.getAllCodePaths());
4978        }
4979    }
4980
4981    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4982            PackageParser.Package changingLib) {
4983        // We might be upgrading from a version of the platform that did not
4984        // provide per-package native library directories for system apps.
4985        // Fix that up here.
4986        if (isSystemApp(pkg)) {
4987            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4988            setInternalAppNativeLibraryPath(pkg, ps);
4989        }
4990
4991        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4992            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4993            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4994            for (int i=0; i<N; i++) {
4995                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4996                if (file == null) {
4997                    Slog.e(TAG, "Package " + pkg.packageName
4998                            + " requires unavailable shared library "
4999                            + pkg.usesLibraries.get(i) + "; failing!");
5000                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
5001                    return false;
5002                }
5003                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5004            }
5005            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5006            for (int i=0; i<N; i++) {
5007                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5008                if (file == null) {
5009                    Slog.w(TAG, "Package " + pkg.packageName
5010                            + " desires unavailable shared library "
5011                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5012                } else {
5013                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5014                }
5015            }
5016            N = usesLibraryFiles.size();
5017            if (N > 0) {
5018                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5019            } else {
5020                pkg.usesLibraryFiles = null;
5021            }
5022        }
5023        return true;
5024    }
5025
5026    private static boolean hasString(List<String> list, List<String> which) {
5027        if (list == null) {
5028            return false;
5029        }
5030        for (int i=list.size()-1; i>=0; i--) {
5031            for (int j=which.size()-1; j>=0; j--) {
5032                if (which.get(j).equals(list.get(i))) {
5033                    return true;
5034                }
5035            }
5036        }
5037        return false;
5038    }
5039
5040    private void updateAllSharedLibrariesLPw() {
5041        for (PackageParser.Package pkg : mPackages.values()) {
5042            updateSharedLibrariesLPw(pkg, null);
5043        }
5044    }
5045
5046    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5047            PackageParser.Package changingPkg) {
5048        ArrayList<PackageParser.Package> res = null;
5049        for (PackageParser.Package pkg : mPackages.values()) {
5050            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5051                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5052                if (res == null) {
5053                    res = new ArrayList<PackageParser.Package>();
5054                }
5055                res.add(pkg);
5056                updateSharedLibrariesLPw(pkg, changingPkg);
5057            }
5058        }
5059        return res;
5060    }
5061
5062    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
5063            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
5064        final File scanFile = new File(pkg.codePath);
5065        if (pkg.applicationInfo.sourceDir == null ||
5066                pkg.applicationInfo.publicSourceDir == null) {
5067            // Bail out. The resource and code paths haven't been set.
5068            Slog.w(TAG, " Code and resource paths haven't been set correctly");
5069            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
5070            return null;
5071        }
5072
5073        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5074            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5075        }
5076
5077        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5078            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5079        }
5080
5081        if (mCustomResolverComponentName != null &&
5082                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5083            setUpCustomResolverActivity(pkg);
5084        }
5085
5086        if (pkg.packageName.equals("android")) {
5087            synchronized (mPackages) {
5088                if (mAndroidApplication != null) {
5089                    Slog.w(TAG, "*************************************************");
5090                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5091                    Slog.w(TAG, " file=" + scanFile);
5092                    Slog.w(TAG, "*************************************************");
5093                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5094                    return null;
5095                }
5096
5097                // Set up information for our fall-back user intent resolution activity.
5098                mPlatformPackage = pkg;
5099                pkg.mVersionCode = mSdkVersion;
5100                mAndroidApplication = pkg.applicationInfo;
5101
5102                if (!mResolverReplaced) {
5103                    mResolveActivity.applicationInfo = mAndroidApplication;
5104                    mResolveActivity.name = ResolverActivity.class.getName();
5105                    mResolveActivity.packageName = mAndroidApplication.packageName;
5106                    mResolveActivity.processName = "system:ui";
5107                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5108                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5109                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5110                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5111                    mResolveActivity.exported = true;
5112                    mResolveActivity.enabled = true;
5113                    mResolveInfo.activityInfo = mResolveActivity;
5114                    mResolveInfo.priority = 0;
5115                    mResolveInfo.preferredOrder = 0;
5116                    mResolveInfo.match = 0;
5117                    mResolveComponentName = new ComponentName(
5118                            mAndroidApplication.packageName, mResolveActivity.name);
5119                }
5120            }
5121        }
5122
5123        if (DEBUG_PACKAGE_SCANNING) {
5124            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5125                Log.d(TAG, "Scanning package " + pkg.packageName);
5126        }
5127
5128        if (mPackages.containsKey(pkg.packageName)
5129                || mSharedLibraries.containsKey(pkg.packageName)) {
5130            Slog.w(TAG, "Application package " + pkg.packageName
5131                    + " already installed.  Skipping duplicate.");
5132            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5133            return null;
5134        }
5135
5136        // Initialize package source and resource directories
5137        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
5138        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
5139
5140        SharedUserSetting suid = null;
5141        PackageSetting pkgSetting = null;
5142
5143        if (!isSystemApp(pkg)) {
5144            // Only system apps can use these features.
5145            pkg.mOriginalPackages = null;
5146            pkg.mRealPackage = null;
5147            pkg.mAdoptPermissions = null;
5148        }
5149
5150        // writer
5151        synchronized (mPackages) {
5152            if (pkg.mSharedUserId != null) {
5153                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5154                if (suid == null) {
5155                    Slog.w(TAG, "Creating application package " + pkg.packageName
5156                            + " for shared user failed");
5157                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5158                    return null;
5159                }
5160                if (DEBUG_PACKAGE_SCANNING) {
5161                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5162                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5163                                + "): packages=" + suid.packages);
5164                }
5165            }
5166
5167            // Check if we are renaming from an original package name.
5168            PackageSetting origPackage = null;
5169            String realName = null;
5170            if (pkg.mOriginalPackages != null) {
5171                // This package may need to be renamed to a previously
5172                // installed name.  Let's check on that...
5173                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5174                if (pkg.mOriginalPackages.contains(renamed)) {
5175                    // This package had originally been installed as the
5176                    // original name, and we have already taken care of
5177                    // transitioning to the new one.  Just update the new
5178                    // one to continue using the old name.
5179                    realName = pkg.mRealPackage;
5180                    if (!pkg.packageName.equals(renamed)) {
5181                        // Callers into this function may have already taken
5182                        // care of renaming the package; only do it here if
5183                        // it is not already done.
5184                        pkg.setPackageName(renamed);
5185                    }
5186
5187                } else {
5188                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5189                        if ((origPackage = mSettings.peekPackageLPr(
5190                                pkg.mOriginalPackages.get(i))) != null) {
5191                            // We do have the package already installed under its
5192                            // original name...  should we use it?
5193                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5194                                // New package is not compatible with original.
5195                                origPackage = null;
5196                                continue;
5197                            } else if (origPackage.sharedUser != null) {
5198                                // Make sure uid is compatible between packages.
5199                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5200                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5201                                            + " to " + pkg.packageName + ": old uid "
5202                                            + origPackage.sharedUser.name
5203                                            + " differs from " + pkg.mSharedUserId);
5204                                    origPackage = null;
5205                                    continue;
5206                                }
5207                            } else {
5208                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5209                                        + pkg.packageName + " to old name " + origPackage.name);
5210                            }
5211                            break;
5212                        }
5213                    }
5214                }
5215            }
5216
5217            if (mTransferedPackages.contains(pkg.packageName)) {
5218                Slog.w(TAG, "Package " + pkg.packageName
5219                        + " was transferred to another, but its .apk remains");
5220            }
5221
5222            // Just create the setting, don't add it yet. For already existing packages
5223            // the PkgSetting exists already and doesn't have to be created.
5224            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5225                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5226                    pkg.applicationInfo.cpuAbi,
5227                    pkg.applicationInfo.flags, user, false);
5228            if (pkgSetting == null) {
5229                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5230                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5231                return null;
5232            }
5233
5234            if (pkgSetting.origPackage != null) {
5235                // If we are first transitioning from an original package,
5236                // fix up the new package's name now.  We need to do this after
5237                // looking up the package under its new name, so getPackageLP
5238                // can take care of fiddling things correctly.
5239                pkg.setPackageName(origPackage.name);
5240
5241                // File a report about this.
5242                String msg = "New package " + pkgSetting.realName
5243                        + " renamed to replace old package " + pkgSetting.name;
5244                reportSettingsProblem(Log.WARN, msg);
5245
5246                // Make a note of it.
5247                mTransferedPackages.add(origPackage.name);
5248
5249                // No longer need to retain this.
5250                pkgSetting.origPackage = null;
5251            }
5252
5253            if (realName != null) {
5254                // Make a note of it.
5255                mTransferedPackages.add(pkg.packageName);
5256            }
5257
5258            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5259                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5260            }
5261
5262            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5263                // Check all shared libraries and map to their actual file path.
5264                // We only do this here for apps not on a system dir, because those
5265                // are the only ones that can fail an install due to this.  We
5266                // will take care of the system apps by updating all of their
5267                // library paths after the scan is done.
5268                if (!updateSharedLibrariesLPw(pkg, null)) {
5269                    return null;
5270                }
5271            }
5272
5273            if (mFoundPolicyFile) {
5274                SELinuxMMAC.assignSeinfoValue(pkg);
5275            }
5276
5277            pkg.applicationInfo.uid = pkgSetting.appId;
5278            pkg.mExtras = pkgSetting;
5279
5280            if (!verifySignaturesLP(pkgSetting, pkg)) {
5281                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5282                    return null;
5283                }
5284                // The signature has changed, but this package is in the system
5285                // image...  let's recover!
5286                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5287                // However...  if this package is part of a shared user, but it
5288                // doesn't match the signature of the shared user, let's fail.
5289                // What this means is that you can't change the signatures
5290                // associated with an overall shared user, which doesn't seem all
5291                // that unreasonable.
5292                if (pkgSetting.sharedUser != null) {
5293                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5294                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5295                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5296                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5297                        return null;
5298                    }
5299                }
5300                // File a report about this.
5301                String msg = "System package " + pkg.packageName
5302                        + " signature changed; retaining data.";
5303                reportSettingsProblem(Log.WARN, msg);
5304            }
5305
5306            // Verify that this new package doesn't have any content providers
5307            // that conflict with existing packages.  Only do this if the
5308            // package isn't already installed, since we don't want to break
5309            // things that are installed.
5310            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5311                final int N = pkg.providers.size();
5312                int i;
5313                for (i=0; i<N; i++) {
5314                    PackageParser.Provider p = pkg.providers.get(i);
5315                    if (p.info.authority != null) {
5316                        String names[] = p.info.authority.split(";");
5317                        for (int j = 0; j < names.length; j++) {
5318                            if (mProvidersByAuthority.containsKey(names[j])) {
5319                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5320                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5321                                        " (in package " + pkg.applicationInfo.packageName +
5322                                        ") is already used by "
5323                                        + ((other != null && other.getComponentName() != null)
5324                                                ? other.getComponentName().getPackageName() : "?"));
5325                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5326                                return null;
5327                            }
5328                        }
5329                    }
5330                }
5331            }
5332
5333            if (pkg.mAdoptPermissions != null) {
5334                // This package wants to adopt ownership of permissions from
5335                // another package.
5336                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5337                    final String origName = pkg.mAdoptPermissions.get(i);
5338                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5339                    if (orig != null) {
5340                        if (verifyPackageUpdateLPr(orig, pkg)) {
5341                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5342                                    + pkg.packageName);
5343                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5344                        }
5345                    }
5346                }
5347            }
5348        }
5349
5350        final String pkgName = pkg.packageName;
5351
5352        final long scanFileTime = scanFile.lastModified();
5353        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5354        pkg.applicationInfo.processName = fixProcessName(
5355                pkg.applicationInfo.packageName,
5356                pkg.applicationInfo.processName,
5357                pkg.applicationInfo.uid);
5358
5359        File dataPath;
5360        if (mPlatformPackage == pkg) {
5361            // The system package is special.
5362            dataPath = new File (Environment.getDataDirectory(), "system");
5363            pkg.applicationInfo.dataDir = dataPath.getPath();
5364        } else {
5365            // This is a normal package, need to make its data directory.
5366            dataPath = getDataPathForPackage(pkg.packageName, 0);
5367
5368            boolean uidError = false;
5369
5370            if (dataPath.exists()) {
5371                int currentUid = 0;
5372                try {
5373                    StructStat stat = Os.stat(dataPath.getPath());
5374                    currentUid = stat.st_uid;
5375                } catch (ErrnoException e) {
5376                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5377                }
5378
5379                // If we have mismatched owners for the data path, we have a problem.
5380                if (currentUid != pkg.applicationInfo.uid) {
5381                    boolean recovered = false;
5382                    if (currentUid == 0) {
5383                        // The directory somehow became owned by root.  Wow.
5384                        // This is probably because the system was stopped while
5385                        // installd was in the middle of messing with its libs
5386                        // directory.  Ask installd to fix that.
5387                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5388                                pkg.applicationInfo.uid);
5389                        if (ret >= 0) {
5390                            recovered = true;
5391                            String msg = "Package " + pkg.packageName
5392                                    + " unexpectedly changed to uid 0; recovered to " +
5393                                    + pkg.applicationInfo.uid;
5394                            reportSettingsProblem(Log.WARN, msg);
5395                        }
5396                    }
5397                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5398                            || (scanMode&SCAN_BOOTING) != 0)) {
5399                        // If this is a system app, we can at least delete its
5400                        // current data so the application will still work.
5401                        int ret = removeDataDirsLI(pkgName);
5402                        if (ret >= 0) {
5403                            // TODO: Kill the processes first
5404                            // Old data gone!
5405                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5406                                    ? "System package " : "Third party package ";
5407                            String msg = prefix + pkg.packageName
5408                                    + " has changed from uid: "
5409                                    + currentUid + " to "
5410                                    + pkg.applicationInfo.uid + "; old data erased";
5411                            reportSettingsProblem(Log.WARN, msg);
5412                            recovered = true;
5413
5414                            // And now re-install the app.
5415                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5416                                                   pkg.applicationInfo.seinfo);
5417                            if (ret == -1) {
5418                                // Ack should not happen!
5419                                msg = prefix + pkg.packageName
5420                                        + " could not have data directory re-created after delete.";
5421                                reportSettingsProblem(Log.WARN, msg);
5422                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5423                                return null;
5424                            }
5425                        }
5426                        if (!recovered) {
5427                            mHasSystemUidErrors = true;
5428                        }
5429                    } else if (!recovered) {
5430                        // If we allow this install to proceed, we will be broken.
5431                        // Abort, abort!
5432                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5433                        return null;
5434                    }
5435                    if (!recovered) {
5436                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5437                            + pkg.applicationInfo.uid + "/fs_"
5438                            + currentUid;
5439                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5440                        String msg = "Package " + pkg.packageName
5441                                + " has mismatched uid: "
5442                                + currentUid + " on disk, "
5443                                + pkg.applicationInfo.uid + " in settings";
5444                        // writer
5445                        synchronized (mPackages) {
5446                            mSettings.mReadMessages.append(msg);
5447                            mSettings.mReadMessages.append('\n');
5448                            uidError = true;
5449                            if (!pkgSetting.uidError) {
5450                                reportSettingsProblem(Log.ERROR, msg);
5451                            }
5452                        }
5453                    }
5454                }
5455                pkg.applicationInfo.dataDir = dataPath.getPath();
5456                if (mShouldRestoreconData) {
5457                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5458                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5459                                pkg.applicationInfo.uid);
5460                }
5461            } else {
5462                if (DEBUG_PACKAGE_SCANNING) {
5463                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5464                        Log.v(TAG, "Want this data dir: " + dataPath);
5465                }
5466                //invoke installer to do the actual installation
5467                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5468                                           pkg.applicationInfo.seinfo);
5469                if (ret < 0) {
5470                    // Error from installer
5471                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5472                    return null;
5473                }
5474
5475                if (dataPath.exists()) {
5476                    pkg.applicationInfo.dataDir = dataPath.getPath();
5477                } else {
5478                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5479                    pkg.applicationInfo.dataDir = null;
5480                }
5481            }
5482
5483            /*
5484             * Set the data dir to the default "/data/data/<package name>/lib"
5485             * if we got here without anyone telling us different (e.g., apps
5486             * stored on SD card have their native libraries stored in the ASEC
5487             * container with the APK).
5488             *
5489             * This happens during an upgrade from a package settings file that
5490             * doesn't have a native library path attribute at all.
5491             */
5492            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5493                if (pkgSetting.nativeLibraryPathString == null) {
5494                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5495                } else {
5496                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5497                }
5498            }
5499            pkgSetting.uidError = uidError;
5500        }
5501
5502        final String path = scanFile.getPath();
5503        /* Note: We don't want to unpack the native binaries for
5504         *        system applications, unless they have been updated
5505         *        (the binaries are already under /system/lib).
5506         *        Also, don't unpack libs for apps on the external card
5507         *        since they should have their libraries in the ASEC
5508         *        container already.
5509         *
5510         *        In other words, we're going to unpack the binaries
5511         *        only for non-system apps and system app upgrades.
5512         */
5513        if (pkg.applicationInfo.nativeLibraryDir != null) {
5514            // TODO: extend to extract native code from split APKs
5515            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5516            try {
5517                // Enable gross and lame hacks for apps that are built with old
5518                // SDK tools. We must scan their APKs for renderscript bitcode and
5519                // not launch them if it's present. Don't bother checking on devices
5520                // that don't have 64 bit support.
5521                String[] abiList = Build.SUPPORTED_ABIS;
5522                boolean hasLegacyRenderscriptBitcode = false;
5523                if (abiOverride != null) {
5524                    abiList = new String[] { abiOverride };
5525                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5526                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5527                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5528                    hasLegacyRenderscriptBitcode = true;
5529                }
5530
5531                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5532                final String dataPathString = dataPath.getCanonicalPath();
5533
5534                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5535                    /*
5536                     * Upgrading from a previous version of the OS sometimes
5537                     * leaves native libraries in the /data/data/<app>/lib
5538                     * directory for system apps even when they shouldn't be.
5539                     * Recent changes in the JNI library search path
5540                     * necessitates we remove those to match previous behavior.
5541                     */
5542                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5543                        Log.i(TAG, "removed obsolete native libraries for system package "
5544                                + path);
5545                    }
5546                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5547                        pkg.applicationInfo.cpuAbi = abiList[0];
5548                        pkgSetting.cpuAbiString = abiList[0];
5549                    } else {
5550                        setInternalAppAbi(pkg, pkgSetting);
5551                    }
5552                } else {
5553                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5554                        /*
5555                        * Update native library dir if it starts with
5556                        * /data/data
5557                        */
5558                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5559                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5560                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5561                        }
5562
5563                        try {
5564                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5565                                    nativeLibraryDir, abiList);
5566                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5567                                Slog.e(TAG, "Unable to copy native libraries");
5568                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5569                                return null;
5570                            }
5571
5572                            // We've successfully copied native libraries across, so we make a
5573                            // note of what ABI we're using
5574                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5575                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5576                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5577                                pkg.applicationInfo.cpuAbi = abiList[0];
5578                            } else {
5579                                pkg.applicationInfo.cpuAbi = null;
5580                            }
5581                        } catch (IOException e) {
5582                            Slog.e(TAG, "Unable to copy native libraries", e);
5583                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5584                            return null;
5585                        }
5586                    } else {
5587                        // We don't have to copy the shared libraries if we're in the ASEC container
5588                        // but we still need to scan the file to figure out what ABI the app needs.
5589                        //
5590                        // TODO: This duplicates work done in the default container service. It's possible
5591                        // to clean this up but we'll need to change the interface between this service
5592                        // and IMediaContainerService (but doing so will spread this logic out, rather
5593                        // than centralizing it).
5594                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5595                        if (abi >= 0) {
5596                            pkg.applicationInfo.cpuAbi = abiList[abi];
5597                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5598                            // Note that (non upgraded) system apps will not have any native
5599                            // libraries bundled in their APK, but we're guaranteed not to be
5600                            // such an app at this point.
5601                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5602                                pkg.applicationInfo.cpuAbi = abiList[0];
5603                            } else {
5604                                pkg.applicationInfo.cpuAbi = null;
5605                            }
5606                        } else {
5607                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5608                            return null;
5609                        }
5610                    }
5611
5612                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5613                    final int[] userIds = sUserManager.getUserIds();
5614                    synchronized (mInstallLock) {
5615                        for (int userId : userIds) {
5616                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5617                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5618                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5619                                        + ")");
5620                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5621                                return null;
5622                            }
5623                        }
5624                    }
5625                }
5626
5627                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5628            } catch (IOException ioe) {
5629                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5630            } finally {
5631                handle.close();
5632            }
5633        }
5634
5635        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5636            // We don't do this here during boot because we can do it all
5637            // at once after scanning all existing packages.
5638            //
5639            // We also do this *before* we perform dexopt on this package, so that
5640            // we can avoid redundant dexopts, and also to make sure we've got the
5641            // code and package path correct.
5642            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5643                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5644                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5645                return null;
5646            }
5647        }
5648
5649        if ((scanMode&SCAN_NO_DEX) == 0) {
5650            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5651                    == DEX_OPT_FAILED) {
5652                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5653                    removeDataDirsLI(pkg.packageName);
5654                }
5655
5656                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5657                return null;
5658            }
5659        }
5660
5661        if (mFactoryTest && pkg.requestedPermissions.contains(
5662                android.Manifest.permission.FACTORY_TEST)) {
5663            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5664        }
5665
5666        ArrayList<PackageParser.Package> clientLibPkgs = null;
5667
5668        // writer
5669        synchronized (mPackages) {
5670            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5671                // Only system apps can add new shared libraries.
5672                if (pkg.libraryNames != null) {
5673                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5674                        String name = pkg.libraryNames.get(i);
5675                        boolean allowed = false;
5676                        if (isUpdatedSystemApp(pkg)) {
5677                            // New library entries can only be added through the
5678                            // system image.  This is important to get rid of a lot
5679                            // of nasty edge cases: for example if we allowed a non-
5680                            // system update of the app to add a library, then uninstalling
5681                            // the update would make the library go away, and assumptions
5682                            // we made such as through app install filtering would now
5683                            // have allowed apps on the device which aren't compatible
5684                            // with it.  Better to just have the restriction here, be
5685                            // conservative, and create many fewer cases that can negatively
5686                            // impact the user experience.
5687                            final PackageSetting sysPs = mSettings
5688                                    .getDisabledSystemPkgLPr(pkg.packageName);
5689                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5690                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5691                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5692                                        allowed = true;
5693                                        allowed = true;
5694                                        break;
5695                                    }
5696                                }
5697                            }
5698                        } else {
5699                            allowed = true;
5700                        }
5701                        if (allowed) {
5702                            if (!mSharedLibraries.containsKey(name)) {
5703                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5704                            } else if (!name.equals(pkg.packageName)) {
5705                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5706                                        + name + " already exists; skipping");
5707                            }
5708                        } else {
5709                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5710                                    + name + " that is not declared on system image; skipping");
5711                        }
5712                    }
5713                    if ((scanMode&SCAN_BOOTING) == 0) {
5714                        // If we are not booting, we need to update any applications
5715                        // that are clients of our shared library.  If we are booting,
5716                        // this will all be done once the scan is complete.
5717                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5718                    }
5719                }
5720            }
5721        }
5722
5723        // We also need to dexopt any apps that are dependent on this library.  Note that
5724        // if these fail, we should abort the install since installing the library will
5725        // result in some apps being broken.
5726        if (clientLibPkgs != null) {
5727            if ((scanMode&SCAN_NO_DEX) == 0) {
5728                for (int i=0; i<clientLibPkgs.size(); i++) {
5729                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5730                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5731                            == DEX_OPT_FAILED) {
5732                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5733                            removeDataDirsLI(pkg.packageName);
5734                        }
5735
5736                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5737                        return null;
5738                    }
5739                }
5740            }
5741        }
5742
5743        // Request the ActivityManager to kill the process(only for existing packages)
5744        // so that we do not end up in a confused state while the user is still using the older
5745        // version of the application while the new one gets installed.
5746        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5747            // If the package lives in an asec, tell everyone that the container is going
5748            // away so they can clean up any references to its resources (which would prevent
5749            // vold from being able to unmount the asec)
5750            if (isForwardLocked(pkg) || isExternal(pkg)) {
5751                if (DEBUG_INSTALL) {
5752                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5753                }
5754                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5755                final ArrayList<String> pkgList = new ArrayList<String>(1);
5756                pkgList.add(pkg.applicationInfo.packageName);
5757                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5758            }
5759
5760            // Post the request that it be killed now that the going-away broadcast is en route
5761            killApplication(pkg.applicationInfo.packageName,
5762                        pkg.applicationInfo.uid, "update pkg");
5763        }
5764
5765        // Also need to kill any apps that are dependent on the library.
5766        if (clientLibPkgs != null) {
5767            for (int i=0; i<clientLibPkgs.size(); i++) {
5768                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5769                killApplication(clientPkg.applicationInfo.packageName,
5770                        clientPkg.applicationInfo.uid, "update lib");
5771            }
5772        }
5773
5774        // writer
5775        synchronized (mPackages) {
5776            // We don't expect installation to fail beyond this point,
5777            if ((scanMode&SCAN_MONITOR) != 0) {
5778                mAppDirs.put(pkg.codePath, pkg);
5779            }
5780            // Add the new setting to mSettings
5781            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5782            // Add the new setting to mPackages
5783            mPackages.put(pkg.applicationInfo.packageName, pkg);
5784            // Make sure we don't accidentally delete its data.
5785            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5786            while (iter.hasNext()) {
5787                PackageCleanItem item = iter.next();
5788                if (pkgName.equals(item.packageName)) {
5789                    iter.remove();
5790                }
5791            }
5792
5793            // Take care of first install / last update times.
5794            if (currentTime != 0) {
5795                if (pkgSetting.firstInstallTime == 0) {
5796                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5797                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5798                    pkgSetting.lastUpdateTime = currentTime;
5799                }
5800            } else if (pkgSetting.firstInstallTime == 0) {
5801                // We need *something*.  Take time time stamp of the file.
5802                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5803            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5804                if (scanFileTime != pkgSetting.timeStamp) {
5805                    // A package on the system image has changed; consider this
5806                    // to be an update.
5807                    pkgSetting.lastUpdateTime = scanFileTime;
5808                }
5809            }
5810
5811            // Add the package's KeySets to the global KeySetManager
5812            KeySetManager ksm = mSettings.mKeySetManager;
5813            try {
5814                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5815                if (pkg.mKeySetMapping != null) {
5816                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5817                            pkg.mKeySetMapping.entrySet()) {
5818                        if (entry.getValue() != null) {
5819                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5820                                entry.getValue(), entry.getKey());
5821                        }
5822                    }
5823                }
5824            } catch (NullPointerException e) {
5825                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5826            } catch (IllegalArgumentException e) {
5827                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5828            }
5829
5830            int N = pkg.providers.size();
5831            StringBuilder r = null;
5832            int i;
5833            for (i=0; i<N; i++) {
5834                PackageParser.Provider p = pkg.providers.get(i);
5835                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5836                        p.info.processName, pkg.applicationInfo.uid);
5837                mProviders.addProvider(p);
5838                p.syncable = p.info.isSyncable;
5839                if (p.info.authority != null) {
5840                    String names[] = p.info.authority.split(";");
5841                    p.info.authority = null;
5842                    for (int j = 0; j < names.length; j++) {
5843                        if (j == 1 && p.syncable) {
5844                            // We only want the first authority for a provider to possibly be
5845                            // syncable, so if we already added this provider using a different
5846                            // authority clear the syncable flag. We copy the provider before
5847                            // changing it because the mProviders object contains a reference
5848                            // to a provider that we don't want to change.
5849                            // Only do this for the second authority since the resulting provider
5850                            // object can be the same for all future authorities for this provider.
5851                            p = new PackageParser.Provider(p);
5852                            p.syncable = false;
5853                        }
5854                        if (!mProvidersByAuthority.containsKey(names[j])) {
5855                            mProvidersByAuthority.put(names[j], p);
5856                            if (p.info.authority == null) {
5857                                p.info.authority = names[j];
5858                            } else {
5859                                p.info.authority = p.info.authority + ";" + names[j];
5860                            }
5861                            if (DEBUG_PACKAGE_SCANNING) {
5862                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5863                                    Log.d(TAG, "Registered content provider: " + names[j]
5864                                            + ", className = " + p.info.name + ", isSyncable = "
5865                                            + p.info.isSyncable);
5866                            }
5867                        } else {
5868                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5869                            Slog.w(TAG, "Skipping provider name " + names[j] +
5870                                    " (in package " + pkg.applicationInfo.packageName +
5871                                    "): name already used by "
5872                                    + ((other != null && other.getComponentName() != null)
5873                                            ? other.getComponentName().getPackageName() : "?"));
5874                        }
5875                    }
5876                }
5877                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5878                    if (r == null) {
5879                        r = new StringBuilder(256);
5880                    } else {
5881                        r.append(' ');
5882                    }
5883                    r.append(p.info.name);
5884                }
5885            }
5886            if (r != null) {
5887                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5888            }
5889
5890            N = pkg.services.size();
5891            r = null;
5892            for (i=0; i<N; i++) {
5893                PackageParser.Service s = pkg.services.get(i);
5894                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5895                        s.info.processName, pkg.applicationInfo.uid);
5896                mServices.addService(s);
5897                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5898                    if (r == null) {
5899                        r = new StringBuilder(256);
5900                    } else {
5901                        r.append(' ');
5902                    }
5903                    r.append(s.info.name);
5904                }
5905            }
5906            if (r != null) {
5907                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5908            }
5909
5910            N = pkg.receivers.size();
5911            r = null;
5912            for (i=0; i<N; i++) {
5913                PackageParser.Activity a = pkg.receivers.get(i);
5914                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5915                        a.info.processName, pkg.applicationInfo.uid);
5916                mReceivers.addActivity(a, "receiver");
5917                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5918                    if (r == null) {
5919                        r = new StringBuilder(256);
5920                    } else {
5921                        r.append(' ');
5922                    }
5923                    r.append(a.info.name);
5924                }
5925            }
5926            if (r != null) {
5927                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5928            }
5929
5930            N = pkg.activities.size();
5931            r = null;
5932            for (i=0; i<N; i++) {
5933                PackageParser.Activity a = pkg.activities.get(i);
5934                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5935                        a.info.processName, pkg.applicationInfo.uid);
5936                mActivities.addActivity(a, "activity");
5937                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5938                    if (r == null) {
5939                        r = new StringBuilder(256);
5940                    } else {
5941                        r.append(' ');
5942                    }
5943                    r.append(a.info.name);
5944                }
5945            }
5946            if (r != null) {
5947                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5948            }
5949
5950            N = pkg.permissionGroups.size();
5951            r = null;
5952            for (i=0; i<N; i++) {
5953                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5954                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5955                if (cur == null) {
5956                    mPermissionGroups.put(pg.info.name, pg);
5957                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5958                        if (r == null) {
5959                            r = new StringBuilder(256);
5960                        } else {
5961                            r.append(' ');
5962                        }
5963                        r.append(pg.info.name);
5964                    }
5965                } else {
5966                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5967                            + pg.info.packageName + " ignored: original from "
5968                            + cur.info.packageName);
5969                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5970                        if (r == null) {
5971                            r = new StringBuilder(256);
5972                        } else {
5973                            r.append(' ');
5974                        }
5975                        r.append("DUP:");
5976                        r.append(pg.info.name);
5977                    }
5978                }
5979            }
5980            if (r != null) {
5981                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5982            }
5983
5984            N = pkg.permissions.size();
5985            r = null;
5986            for (i=0; i<N; i++) {
5987                PackageParser.Permission p = pkg.permissions.get(i);
5988                HashMap<String, BasePermission> permissionMap =
5989                        p.tree ? mSettings.mPermissionTrees
5990                        : mSettings.mPermissions;
5991                p.group = mPermissionGroups.get(p.info.group);
5992                if (p.info.group == null || p.group != null) {
5993                    BasePermission bp = permissionMap.get(p.info.name);
5994                    if (bp == null) {
5995                        bp = new BasePermission(p.info.name, p.info.packageName,
5996                                BasePermission.TYPE_NORMAL);
5997                        permissionMap.put(p.info.name, bp);
5998                    }
5999                    if (bp.perm == null) {
6000                        if (bp.sourcePackage != null
6001                                && !bp.sourcePackage.equals(p.info.packageName)) {
6002                            // If this is a permission that was formerly defined by a non-system
6003                            // app, but is now defined by a system app (following an upgrade),
6004                            // discard the previous declaration and consider the system's to be
6005                            // canonical.
6006                            if (isSystemApp(p.owner)) {
6007                                String msg = "New decl " + p.owner + " of permission  "
6008                                        + p.info.name + " is system";
6009                                reportSettingsProblem(Log.WARN, msg);
6010                                bp.sourcePackage = null;
6011                            }
6012                        }
6013                        if (bp.sourcePackage == null
6014                                || bp.sourcePackage.equals(p.info.packageName)) {
6015                            BasePermission tree = findPermissionTreeLP(p.info.name);
6016                            if (tree == null
6017                                    || tree.sourcePackage.equals(p.info.packageName)) {
6018                                bp.packageSetting = pkgSetting;
6019                                bp.perm = p;
6020                                bp.uid = pkg.applicationInfo.uid;
6021                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6022                                    if (r == null) {
6023                                        r = new StringBuilder(256);
6024                                    } else {
6025                                        r.append(' ');
6026                                    }
6027                                    r.append(p.info.name);
6028                                }
6029                            } else {
6030                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6031                                        + p.info.packageName + " ignored: base tree "
6032                                        + tree.name + " is from package "
6033                                        + tree.sourcePackage);
6034                            }
6035                        } else {
6036                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6037                                    + p.info.packageName + " ignored: original from "
6038                                    + bp.sourcePackage);
6039                        }
6040                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6041                        if (r == null) {
6042                            r = new StringBuilder(256);
6043                        } else {
6044                            r.append(' ');
6045                        }
6046                        r.append("DUP:");
6047                        r.append(p.info.name);
6048                    }
6049                    if (bp.perm == p) {
6050                        bp.protectionLevel = p.info.protectionLevel;
6051                    }
6052                } else {
6053                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6054                            + p.info.packageName + " ignored: no group "
6055                            + p.group);
6056                }
6057            }
6058            if (r != null) {
6059                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6060            }
6061
6062            N = pkg.instrumentation.size();
6063            r = null;
6064            for (i=0; i<N; i++) {
6065                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6066                a.info.packageName = pkg.applicationInfo.packageName;
6067                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6068                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6069                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6070                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6071                a.info.dataDir = pkg.applicationInfo.dataDir;
6072                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6073                mInstrumentation.put(a.getComponentName(), a);
6074                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6075                    if (r == null) {
6076                        r = new StringBuilder(256);
6077                    } else {
6078                        r.append(' ');
6079                    }
6080                    r.append(a.info.name);
6081                }
6082            }
6083            if (r != null) {
6084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6085            }
6086
6087            if (pkg.protectedBroadcasts != null) {
6088                N = pkg.protectedBroadcasts.size();
6089                for (i=0; i<N; i++) {
6090                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6091                }
6092            }
6093
6094            pkgSetting.setTimeStamp(scanFileTime);
6095
6096            // Create idmap files for pairs of (packages, overlay packages).
6097            // Note: "android", ie framework-res.apk, is handled by native layers.
6098            if (pkg.mOverlayTarget != null) {
6099                // This is an overlay package.
6100                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6101                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6102                        mOverlays.put(pkg.mOverlayTarget,
6103                                new HashMap<String, PackageParser.Package>());
6104                    }
6105                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6106                    map.put(pkg.packageName, pkg);
6107                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6108                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6109                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
6110                        return null;
6111                    }
6112                }
6113            } else if (mOverlays.containsKey(pkg.packageName) &&
6114                    !pkg.packageName.equals("android")) {
6115                // This is a regular package, with one or more known overlay packages.
6116                createIdmapsForPackageLI(pkg);
6117            }
6118        }
6119
6120        return pkg;
6121    }
6122
6123    /**
6124     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6125     * i.e, so that all packages can be run inside a single process if required.
6126     *
6127     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6128     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6129     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6130     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6131     * updating a package that belongs to a shared user.
6132     */
6133    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6134            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6135        String requiredInstructionSet = null;
6136        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
6137            requiredInstructionSet = VMRuntime.getInstructionSet(
6138                     scannedPackage.applicationInfo.cpuAbi);
6139        }
6140
6141        PackageSetting requirer = null;
6142        for (PackageSetting ps : packagesForUser) {
6143            // If packagesForUser contains scannedPackage, we skip it. This will happen
6144            // when scannedPackage is an update of an existing package. Without this check,
6145            // we will never be able to change the ABI of any package belonging to a shared
6146            // user, even if it's compatible with other packages.
6147            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6148                if (ps.cpuAbiString == null) {
6149                    continue;
6150                }
6151
6152                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6153                if (requiredInstructionSet != null) {
6154                    if (!instructionSet.equals(requiredInstructionSet)) {
6155                        // We have a mismatch between instruction sets (say arm vs arm64).
6156                        // bail out.
6157                        String errorMessage = "Instruction set mismatch, "
6158                                + ((requirer == null) ? "[caller]" : requirer)
6159                                + " requires " + requiredInstructionSet + " whereas " + ps
6160                                + " requires " + instructionSet;
6161                        Slog.e(TAG, errorMessage);
6162
6163                        reportSettingsProblem(Log.WARN, errorMessage);
6164                        // Give up, don't bother making any other changes to the package settings.
6165                        return false;
6166                    }
6167                } else {
6168                    requiredInstructionSet = instructionSet;
6169                    requirer = ps;
6170                }
6171            }
6172        }
6173
6174        if (requiredInstructionSet != null) {
6175            String adjustedAbi;
6176            if (requirer != null) {
6177                // requirer != null implies that either scannedPackage was null or that scannedPackage
6178                // did not require an ABI, in which case we have to adjust scannedPackage to match
6179                // the ABI of the set (which is the same as requirer's ABI)
6180                adjustedAbi = requirer.cpuAbiString;
6181                if (scannedPackage != null) {
6182                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6183                }
6184            } else {
6185                // requirer == null implies that we're updating all ABIs in the set to
6186                // match scannedPackage.
6187                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6188            }
6189
6190            for (PackageSetting ps : packagesForUser) {
6191                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6192                    if (ps.cpuAbiString != null) {
6193                        continue;
6194                    }
6195
6196                    ps.cpuAbiString = adjustedAbi;
6197                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6198                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6199                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6200
6201                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6202                            ps.cpuAbiString = null;
6203                            ps.pkg.applicationInfo.cpuAbi = null;
6204                            return false;
6205                        } else {
6206                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6207                        }
6208                    }
6209                }
6210            }
6211        }
6212
6213        return true;
6214    }
6215
6216    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6217        synchronized (mPackages) {
6218            mResolverReplaced = true;
6219            // Set up information for custom user intent resolution activity.
6220            mResolveActivity.applicationInfo = pkg.applicationInfo;
6221            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6222            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6223            mResolveActivity.processName = null;
6224            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6225            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6226                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6227            mResolveActivity.theme = 0;
6228            mResolveActivity.exported = true;
6229            mResolveActivity.enabled = true;
6230            mResolveInfo.activityInfo = mResolveActivity;
6231            mResolveInfo.priority = 0;
6232            mResolveInfo.preferredOrder = 0;
6233            mResolveInfo.match = 0;
6234            mResolveComponentName = mCustomResolverComponentName;
6235            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6236                    mResolveComponentName);
6237        }
6238    }
6239
6240    private String calculateApkRoot(final String codePathString) {
6241        final File codePath = new File(codePathString);
6242        final File codeRoot;
6243        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6244            codeRoot = Environment.getRootDirectory();
6245        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6246            codeRoot = Environment.getOemDirectory();
6247        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6248            codeRoot = Environment.getVendorDirectory();
6249        } else {
6250            // Unrecognized code path; take its top real segment as the apk root:
6251            // e.g. /something/app/blah.apk => /something
6252            try {
6253                File f = codePath.getCanonicalFile();
6254                File parent = f.getParentFile();    // non-null because codePath is a file
6255                File tmp;
6256                while ((tmp = parent.getParentFile()) != null) {
6257                    f = parent;
6258                    parent = tmp;
6259                }
6260                codeRoot = f;
6261                Slog.w(TAG, "Unrecognized code path "
6262                        + codePath + " - using " + codeRoot);
6263            } catch (IOException e) {
6264                // Can't canonicalize the lib path -- shenanigans?
6265                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6266                return Environment.getRootDirectory().getPath();
6267            }
6268        }
6269        return codeRoot.getPath();
6270    }
6271
6272    // This is the initial scan-time determination of how to handle a given
6273    // package for purposes of native library location.
6274    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6275            PackageSetting pkgSetting) {
6276        // "bundled" here means system-installed with no overriding update
6277        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6278        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6279        final File libDir;
6280        if (bundledApk) {
6281            // If "/system/lib64/apkname" exists, assume that is the per-package
6282            // native library directory to use; otherwise use "/system/lib/apkname".
6283            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6284            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6285            File packLib64 = new File(lib64, apkName);
6286            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6287        } else {
6288            libDir = mAppLibInstallDir;
6289        }
6290        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6291        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6292        // pkgSetting might be null during rescan following uninstall of updates
6293        // to a bundled app, so accommodate that possibility.  The settings in
6294        // that case will be established later from the parsed package.
6295        if (pkgSetting != null) {
6296            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6297        }
6298    }
6299
6300    // Deduces the required ABI of an upgraded system app.
6301    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6302        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6303        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6304
6305        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6306        // or similar.
6307        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6308        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6309
6310        // Assume that the bundled native libraries always correspond to the
6311        // most preferred 32 or 64 bit ABI.
6312        if (lib64.exists()) {
6313            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6314            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6315        } else if (lib.exists()) {
6316            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6317            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6318        } else {
6319            // This is the case where the app has no native code.
6320            pkg.applicationInfo.cpuAbi = null;
6321            pkgSetting.cpuAbiString = null;
6322        }
6323    }
6324
6325    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6326            final File nativeLibraryDir, String[] abiList) throws IOException {
6327        if (!nativeLibraryDir.isDirectory()) {
6328            nativeLibraryDir.delete();
6329
6330            if (!nativeLibraryDir.mkdir()) {
6331                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6332            }
6333
6334            try {
6335                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6336            } catch (ErrnoException e) {
6337                throw new IOException("Cannot chmod native library directory "
6338                        + nativeLibraryDir.getPath(), e);
6339            }
6340        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6341            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6342        }
6343
6344        /*
6345         * If this is an internal application or our nativeLibraryPath points to
6346         * the app-lib directory, unpack the libraries if necessary.
6347         */
6348        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6349        if (abi >= 0) {
6350            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6351                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6352            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6353                return copyRet;
6354            }
6355        }
6356
6357        return abi;
6358    }
6359
6360    private void killApplication(String pkgName, int appId, String reason) {
6361        // Request the ActivityManager to kill the process(only for existing packages)
6362        // so that we do not end up in a confused state while the user is still using the older
6363        // version of the application while the new one gets installed.
6364        IActivityManager am = ActivityManagerNative.getDefault();
6365        if (am != null) {
6366            try {
6367                am.killApplicationWithAppId(pkgName, appId, reason);
6368            } catch (RemoteException e) {
6369            }
6370        }
6371    }
6372
6373    void removePackageLI(PackageSetting ps, boolean chatty) {
6374        if (DEBUG_INSTALL) {
6375            if (chatty)
6376                Log.d(TAG, "Removing package " + ps.name);
6377        }
6378
6379        // writer
6380        synchronized (mPackages) {
6381            mPackages.remove(ps.name);
6382            if (ps.codePathString != null) {
6383                mAppDirs.remove(ps.codePathString);
6384            }
6385
6386            final PackageParser.Package pkg = ps.pkg;
6387            if (pkg != null) {
6388                cleanPackageDataStructuresLILPw(pkg, chatty);
6389            }
6390        }
6391    }
6392
6393    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6394        if (DEBUG_INSTALL) {
6395            if (chatty)
6396                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6397        }
6398
6399        // writer
6400        synchronized (mPackages) {
6401            mPackages.remove(pkg.applicationInfo.packageName);
6402            if (pkg.codePath != null) {
6403                mAppDirs.remove(pkg.codePath);
6404            }
6405            cleanPackageDataStructuresLILPw(pkg, chatty);
6406        }
6407    }
6408
6409    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6410        int N = pkg.providers.size();
6411        StringBuilder r = null;
6412        int i;
6413        for (i=0; i<N; i++) {
6414            PackageParser.Provider p = pkg.providers.get(i);
6415            mProviders.removeProvider(p);
6416            if (p.info.authority == null) {
6417
6418                /* There was another ContentProvider with this authority when
6419                 * this app was installed so this authority is null,
6420                 * Ignore it as we don't have to unregister the provider.
6421                 */
6422                continue;
6423            }
6424            String names[] = p.info.authority.split(";");
6425            for (int j = 0; j < names.length; j++) {
6426                if (mProvidersByAuthority.get(names[j]) == p) {
6427                    mProvidersByAuthority.remove(names[j]);
6428                    if (DEBUG_REMOVE) {
6429                        if (chatty)
6430                            Log.d(TAG, "Unregistered content provider: " + names[j]
6431                                    + ", className = " + p.info.name + ", isSyncable = "
6432                                    + p.info.isSyncable);
6433                    }
6434                }
6435            }
6436            if (DEBUG_REMOVE && chatty) {
6437                if (r == null) {
6438                    r = new StringBuilder(256);
6439                } else {
6440                    r.append(' ');
6441                }
6442                r.append(p.info.name);
6443            }
6444        }
6445        if (r != null) {
6446            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6447        }
6448
6449        N = pkg.services.size();
6450        r = null;
6451        for (i=0; i<N; i++) {
6452            PackageParser.Service s = pkg.services.get(i);
6453            mServices.removeService(s);
6454            if (chatty) {
6455                if (r == null) {
6456                    r = new StringBuilder(256);
6457                } else {
6458                    r.append(' ');
6459                }
6460                r.append(s.info.name);
6461            }
6462        }
6463        if (r != null) {
6464            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6465        }
6466
6467        N = pkg.receivers.size();
6468        r = null;
6469        for (i=0; i<N; i++) {
6470            PackageParser.Activity a = pkg.receivers.get(i);
6471            mReceivers.removeActivity(a, "receiver");
6472            if (DEBUG_REMOVE && chatty) {
6473                if (r == null) {
6474                    r = new StringBuilder(256);
6475                } else {
6476                    r.append(' ');
6477                }
6478                r.append(a.info.name);
6479            }
6480        }
6481        if (r != null) {
6482            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6483        }
6484
6485        N = pkg.activities.size();
6486        r = null;
6487        for (i=0; i<N; i++) {
6488            PackageParser.Activity a = pkg.activities.get(i);
6489            mActivities.removeActivity(a, "activity");
6490            if (DEBUG_REMOVE && chatty) {
6491                if (r == null) {
6492                    r = new StringBuilder(256);
6493                } else {
6494                    r.append(' ');
6495                }
6496                r.append(a.info.name);
6497            }
6498        }
6499        if (r != null) {
6500            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6501        }
6502
6503        N = pkg.permissions.size();
6504        r = null;
6505        for (i=0; i<N; i++) {
6506            PackageParser.Permission p = pkg.permissions.get(i);
6507            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6508            if (bp == null) {
6509                bp = mSettings.mPermissionTrees.get(p.info.name);
6510            }
6511            if (bp != null && bp.perm == p) {
6512                bp.perm = null;
6513                if (DEBUG_REMOVE && chatty) {
6514                    if (r == null) {
6515                        r = new StringBuilder(256);
6516                    } else {
6517                        r.append(' ');
6518                    }
6519                    r.append(p.info.name);
6520                }
6521            }
6522        }
6523        if (r != null) {
6524            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6525        }
6526
6527        N = pkg.instrumentation.size();
6528        r = null;
6529        for (i=0; i<N; i++) {
6530            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6531            mInstrumentation.remove(a.getComponentName());
6532            if (DEBUG_REMOVE && chatty) {
6533                if (r == null) {
6534                    r = new StringBuilder(256);
6535                } else {
6536                    r.append(' ');
6537                }
6538                r.append(a.info.name);
6539            }
6540        }
6541        if (r != null) {
6542            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6543        }
6544
6545        r = null;
6546        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6547            // Only system apps can hold shared libraries.
6548            if (pkg.libraryNames != null) {
6549                for (i=0; i<pkg.libraryNames.size(); i++) {
6550                    String name = pkg.libraryNames.get(i);
6551                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6552                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6553                        mSharedLibraries.remove(name);
6554                        if (DEBUG_REMOVE && chatty) {
6555                            if (r == null) {
6556                                r = new StringBuilder(256);
6557                            } else {
6558                                r.append(' ');
6559                            }
6560                            r.append(name);
6561                        }
6562                    }
6563                }
6564            }
6565        }
6566        if (r != null) {
6567            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6568        }
6569    }
6570
6571    private static final boolean isPackageFilename(String name) {
6572        return name != null && name.endsWith(".apk");
6573    }
6574
6575    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6576        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6577            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6578                return true;
6579            }
6580        }
6581        return false;
6582    }
6583
6584    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6585    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6586    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6587
6588    private void updatePermissionsLPw(String changingPkg,
6589            PackageParser.Package pkgInfo, int flags) {
6590        // Make sure there are no dangling permission trees.
6591        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6592        while (it.hasNext()) {
6593            final BasePermission bp = it.next();
6594            if (bp.packageSetting == null) {
6595                // We may not yet have parsed the package, so just see if
6596                // we still know about its settings.
6597                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6598            }
6599            if (bp.packageSetting == null) {
6600                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6601                        + " from package " + bp.sourcePackage);
6602                it.remove();
6603            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6604                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6605                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6606                            + " from package " + bp.sourcePackage);
6607                    flags |= UPDATE_PERMISSIONS_ALL;
6608                    it.remove();
6609                }
6610            }
6611        }
6612
6613        // Make sure all dynamic permissions have been assigned to a package,
6614        // and make sure there are no dangling permissions.
6615        it = mSettings.mPermissions.values().iterator();
6616        while (it.hasNext()) {
6617            final BasePermission bp = it.next();
6618            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6619                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6620                        + bp.name + " pkg=" + bp.sourcePackage
6621                        + " info=" + bp.pendingInfo);
6622                if (bp.packageSetting == null && bp.pendingInfo != null) {
6623                    final BasePermission tree = findPermissionTreeLP(bp.name);
6624                    if (tree != null && tree.perm != null) {
6625                        bp.packageSetting = tree.packageSetting;
6626                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6627                                new PermissionInfo(bp.pendingInfo));
6628                        bp.perm.info.packageName = tree.perm.info.packageName;
6629                        bp.perm.info.name = bp.name;
6630                        bp.uid = tree.uid;
6631                    }
6632                }
6633            }
6634            if (bp.packageSetting == null) {
6635                // We may not yet have parsed the package, so just see if
6636                // we still know about its settings.
6637                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6638            }
6639            if (bp.packageSetting == null) {
6640                Slog.w(TAG, "Removing dangling permission: " + bp.name
6641                        + " from package " + bp.sourcePackage);
6642                it.remove();
6643            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6644                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6645                    Slog.i(TAG, "Removing old permission: " + bp.name
6646                            + " from package " + bp.sourcePackage);
6647                    flags |= UPDATE_PERMISSIONS_ALL;
6648                    it.remove();
6649                }
6650            }
6651        }
6652
6653        // Now update the permissions for all packages, in particular
6654        // replace the granted permissions of the system packages.
6655        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6656            for (PackageParser.Package pkg : mPackages.values()) {
6657                if (pkg != pkgInfo) {
6658                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6659                }
6660            }
6661        }
6662
6663        if (pkgInfo != null) {
6664            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6665        }
6666    }
6667
6668    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6669        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6670        if (ps == null) {
6671            return;
6672        }
6673        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6674        HashSet<String> origPermissions = gp.grantedPermissions;
6675        boolean changedPermission = false;
6676
6677        if (replace) {
6678            ps.permissionsFixed = false;
6679            if (gp == ps) {
6680                origPermissions = new HashSet<String>(gp.grantedPermissions);
6681                gp.grantedPermissions.clear();
6682                gp.gids = mGlobalGids;
6683            }
6684        }
6685
6686        if (gp.gids == null) {
6687            gp.gids = mGlobalGids;
6688        }
6689
6690        final int N = pkg.requestedPermissions.size();
6691        for (int i=0; i<N; i++) {
6692            final String name = pkg.requestedPermissions.get(i);
6693            final boolean required = pkg.requestedPermissionsRequired.get(i);
6694            final BasePermission bp = mSettings.mPermissions.get(name);
6695            if (DEBUG_INSTALL) {
6696                if (gp != ps) {
6697                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6698                }
6699            }
6700
6701            if (bp == null || bp.packageSetting == null) {
6702                Slog.w(TAG, "Unknown permission " + name
6703                        + " in package " + pkg.packageName);
6704                continue;
6705            }
6706
6707            final String perm = bp.name;
6708            boolean allowed;
6709            boolean allowedSig = false;
6710            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6711            if (level == PermissionInfo.PROTECTION_NORMAL
6712                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6713                // We grant a normal or dangerous permission if any of the following
6714                // are true:
6715                // 1) The permission is required
6716                // 2) The permission is optional, but was granted in the past
6717                // 3) The permission is optional, but was requested by an
6718                //    app in /system (not /data)
6719                //
6720                // Otherwise, reject the permission.
6721                allowed = (required || origPermissions.contains(perm)
6722                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6723            } else if (bp.packageSetting == null) {
6724                // This permission is invalid; skip it.
6725                allowed = false;
6726            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6727                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6728                if (allowed) {
6729                    allowedSig = true;
6730                }
6731            } else {
6732                allowed = false;
6733            }
6734            if (DEBUG_INSTALL) {
6735                if (gp != ps) {
6736                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6737                }
6738            }
6739            if (allowed) {
6740                if (!isSystemApp(ps) && ps.permissionsFixed) {
6741                    // If this is an existing, non-system package, then
6742                    // we can't add any new permissions to it.
6743                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6744                        // Except...  if this is a permission that was added
6745                        // to the platform (note: need to only do this when
6746                        // updating the platform).
6747                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6748                    }
6749                }
6750                if (allowed) {
6751                    if (!gp.grantedPermissions.contains(perm)) {
6752                        changedPermission = true;
6753                        gp.grantedPermissions.add(perm);
6754                        gp.gids = appendInts(gp.gids, bp.gids);
6755                    } else if (!ps.haveGids) {
6756                        gp.gids = appendInts(gp.gids, bp.gids);
6757                    }
6758                } else {
6759                    Slog.w(TAG, "Not granting permission " + perm
6760                            + " to package " + pkg.packageName
6761                            + " because it was previously installed without");
6762                }
6763            } else {
6764                if (gp.grantedPermissions.remove(perm)) {
6765                    changedPermission = true;
6766                    gp.gids = removeInts(gp.gids, bp.gids);
6767                    Slog.i(TAG, "Un-granting permission " + perm
6768                            + " from package " + pkg.packageName
6769                            + " (protectionLevel=" + bp.protectionLevel
6770                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6771                            + ")");
6772                } else {
6773                    Slog.w(TAG, "Not granting permission " + perm
6774                            + " to package " + pkg.packageName
6775                            + " (protectionLevel=" + bp.protectionLevel
6776                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6777                            + ")");
6778                }
6779            }
6780        }
6781
6782        if ((changedPermission || replace) && !ps.permissionsFixed &&
6783                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6784            // This is the first that we have heard about this package, so the
6785            // permissions we have now selected are fixed until explicitly
6786            // changed.
6787            ps.permissionsFixed = true;
6788        }
6789        ps.haveGids = true;
6790    }
6791
6792    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6793        boolean allowed = false;
6794        final int NP = PackageParser.NEW_PERMISSIONS.length;
6795        for (int ip=0; ip<NP; ip++) {
6796            final PackageParser.NewPermissionInfo npi
6797                    = PackageParser.NEW_PERMISSIONS[ip];
6798            if (npi.name.equals(perm)
6799                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6800                allowed = true;
6801                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6802                        + pkg.packageName);
6803                break;
6804            }
6805        }
6806        return allowed;
6807    }
6808
6809    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6810                                          BasePermission bp, HashSet<String> origPermissions) {
6811        boolean allowed;
6812        allowed = (compareSignatures(
6813                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6814                        == PackageManager.SIGNATURE_MATCH)
6815                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6816                        == PackageManager.SIGNATURE_MATCH);
6817        if (!allowed && (bp.protectionLevel
6818                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6819            if (isSystemApp(pkg)) {
6820                // For updated system applications, a system permission
6821                // is granted only if it had been defined by the original application.
6822                if (isUpdatedSystemApp(pkg)) {
6823                    final PackageSetting sysPs = mSettings
6824                            .getDisabledSystemPkgLPr(pkg.packageName);
6825                    final GrantedPermissions origGp = sysPs.sharedUser != null
6826                            ? sysPs.sharedUser : sysPs;
6827
6828                    if (origGp.grantedPermissions.contains(perm)) {
6829                        // If the original was granted this permission, we take
6830                        // that grant decision as read and propagate it to the
6831                        // update.
6832                        allowed = true;
6833                    } else {
6834                        // The system apk may have been updated with an older
6835                        // version of the one on the data partition, but which
6836                        // granted a new system permission that it didn't have
6837                        // before.  In this case we do want to allow the app to
6838                        // now get the new permission if the ancestral apk is
6839                        // privileged to get it.
6840                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6841                            for (int j=0;
6842                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6843                                if (perm.equals(
6844                                        sysPs.pkg.requestedPermissions.get(j))) {
6845                                    allowed = true;
6846                                    break;
6847                                }
6848                            }
6849                        }
6850                    }
6851                } else {
6852                    allowed = isPrivilegedApp(pkg);
6853                }
6854            }
6855        }
6856        if (!allowed && (bp.protectionLevel
6857                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6858            // For development permissions, a development permission
6859            // is granted only if it was already granted.
6860            allowed = origPermissions.contains(perm);
6861        }
6862        return allowed;
6863    }
6864
6865    final class ActivityIntentResolver
6866            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6867        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6868                boolean defaultOnly, int userId) {
6869            if (!sUserManager.exists(userId)) return null;
6870            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6871            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6872        }
6873
6874        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6875                int userId) {
6876            if (!sUserManager.exists(userId)) return null;
6877            mFlags = flags;
6878            return super.queryIntent(intent, resolvedType,
6879                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6880        }
6881
6882        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6883                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6884            if (!sUserManager.exists(userId)) return null;
6885            if (packageActivities == null) {
6886                return null;
6887            }
6888            mFlags = flags;
6889            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6890            final int N = packageActivities.size();
6891            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6892                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6893
6894            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6895            for (int i = 0; i < N; ++i) {
6896                intentFilters = packageActivities.get(i).intents;
6897                if (intentFilters != null && intentFilters.size() > 0) {
6898                    PackageParser.ActivityIntentInfo[] array =
6899                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6900                    intentFilters.toArray(array);
6901                    listCut.add(array);
6902                }
6903            }
6904            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6905        }
6906
6907        public final void addActivity(PackageParser.Activity a, String type) {
6908            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6909            mActivities.put(a.getComponentName(), a);
6910            if (DEBUG_SHOW_INFO)
6911                Log.v(
6912                TAG, "  " + type + " " +
6913                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6914            if (DEBUG_SHOW_INFO)
6915                Log.v(TAG, "    Class=" + a.info.name);
6916            final int NI = a.intents.size();
6917            for (int j=0; j<NI; j++) {
6918                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6919                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6920                    intent.setPriority(0);
6921                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6922                            + a.className + " with priority > 0, forcing to 0");
6923                }
6924                if (DEBUG_SHOW_INFO) {
6925                    Log.v(TAG, "    IntentFilter:");
6926                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6927                }
6928                if (!intent.debugCheck()) {
6929                    Log.w(TAG, "==> For Activity " + a.info.name);
6930                }
6931                addFilter(intent);
6932            }
6933        }
6934
6935        public final void removeActivity(PackageParser.Activity a, String type) {
6936            mActivities.remove(a.getComponentName());
6937            if (DEBUG_SHOW_INFO) {
6938                Log.v(TAG, "  " + type + " "
6939                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6940                                : a.info.name) + ":");
6941                Log.v(TAG, "    Class=" + a.info.name);
6942            }
6943            final int NI = a.intents.size();
6944            for (int j=0; j<NI; j++) {
6945                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6946                if (DEBUG_SHOW_INFO) {
6947                    Log.v(TAG, "    IntentFilter:");
6948                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6949                }
6950                removeFilter(intent);
6951            }
6952        }
6953
6954        @Override
6955        protected boolean allowFilterResult(
6956                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6957            ActivityInfo filterAi = filter.activity.info;
6958            for (int i=dest.size()-1; i>=0; i--) {
6959                ActivityInfo destAi = dest.get(i).activityInfo;
6960                if (destAi.name == filterAi.name
6961                        && destAi.packageName == filterAi.packageName) {
6962                    return false;
6963                }
6964            }
6965            return true;
6966        }
6967
6968        @Override
6969        protected ActivityIntentInfo[] newArray(int size) {
6970            return new ActivityIntentInfo[size];
6971        }
6972
6973        @Override
6974        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6975            if (!sUserManager.exists(userId)) return true;
6976            PackageParser.Package p = filter.activity.owner;
6977            if (p != null) {
6978                PackageSetting ps = (PackageSetting)p.mExtras;
6979                if (ps != null) {
6980                    // System apps are never considered stopped for purposes of
6981                    // filtering, because there may be no way for the user to
6982                    // actually re-launch them.
6983                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6984                            && ps.getStopped(userId);
6985                }
6986            }
6987            return false;
6988        }
6989
6990        @Override
6991        protected boolean isPackageForFilter(String packageName,
6992                PackageParser.ActivityIntentInfo info) {
6993            return packageName.equals(info.activity.owner.packageName);
6994        }
6995
6996        @Override
6997        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6998                int match, int userId) {
6999            if (!sUserManager.exists(userId)) return null;
7000            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7001                return null;
7002            }
7003            final PackageParser.Activity activity = info.activity;
7004            if (mSafeMode && (activity.info.applicationInfo.flags
7005                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7006                return null;
7007            }
7008            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7009            if (ps == null) {
7010                return null;
7011            }
7012            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7013                    ps.readUserState(userId), userId);
7014            if (ai == null) {
7015                return null;
7016            }
7017            final ResolveInfo res = new ResolveInfo();
7018            res.activityInfo = ai;
7019            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7020                res.filter = info;
7021            }
7022            res.priority = info.getPriority();
7023            res.preferredOrder = activity.owner.mPreferredOrder;
7024            //System.out.println("Result: " + res.activityInfo.className +
7025            //                   " = " + res.priority);
7026            res.match = match;
7027            res.isDefault = info.hasDefault;
7028            res.labelRes = info.labelRes;
7029            res.nonLocalizedLabel = info.nonLocalizedLabel;
7030            res.icon = info.icon;
7031            res.system = isSystemApp(res.activityInfo.applicationInfo);
7032            return res;
7033        }
7034
7035        @Override
7036        protected void sortResults(List<ResolveInfo> results) {
7037            Collections.sort(results, mResolvePrioritySorter);
7038        }
7039
7040        @Override
7041        protected void dumpFilter(PrintWriter out, String prefix,
7042                PackageParser.ActivityIntentInfo filter) {
7043            out.print(prefix); out.print(
7044                    Integer.toHexString(System.identityHashCode(filter.activity)));
7045                    out.print(' ');
7046                    filter.activity.printComponentShortName(out);
7047                    out.print(" filter ");
7048                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7049        }
7050
7051//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7052//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7053//            final List<ResolveInfo> retList = Lists.newArrayList();
7054//            while (i.hasNext()) {
7055//                final ResolveInfo resolveInfo = i.next();
7056//                if (isEnabledLP(resolveInfo.activityInfo)) {
7057//                    retList.add(resolveInfo);
7058//                }
7059//            }
7060//            return retList;
7061//        }
7062
7063        // Keys are String (activity class name), values are Activity.
7064        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7065                = new HashMap<ComponentName, PackageParser.Activity>();
7066        private int mFlags;
7067    }
7068
7069    private final class ServiceIntentResolver
7070            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7071        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7072                boolean defaultOnly, int userId) {
7073            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7074            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7075        }
7076
7077        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7078                int userId) {
7079            if (!sUserManager.exists(userId)) return null;
7080            mFlags = flags;
7081            return super.queryIntent(intent, resolvedType,
7082                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7083        }
7084
7085        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7086                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7087            if (!sUserManager.exists(userId)) return null;
7088            if (packageServices == null) {
7089                return null;
7090            }
7091            mFlags = flags;
7092            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7093            final int N = packageServices.size();
7094            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7095                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7096
7097            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7098            for (int i = 0; i < N; ++i) {
7099                intentFilters = packageServices.get(i).intents;
7100                if (intentFilters != null && intentFilters.size() > 0) {
7101                    PackageParser.ServiceIntentInfo[] array =
7102                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7103                    intentFilters.toArray(array);
7104                    listCut.add(array);
7105                }
7106            }
7107            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7108        }
7109
7110        public final void addService(PackageParser.Service s) {
7111            mServices.put(s.getComponentName(), s);
7112            if (DEBUG_SHOW_INFO) {
7113                Log.v(TAG, "  "
7114                        + (s.info.nonLocalizedLabel != null
7115                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7116                Log.v(TAG, "    Class=" + s.info.name);
7117            }
7118            final int NI = s.intents.size();
7119            int j;
7120            for (j=0; j<NI; j++) {
7121                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7122                if (DEBUG_SHOW_INFO) {
7123                    Log.v(TAG, "    IntentFilter:");
7124                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7125                }
7126                if (!intent.debugCheck()) {
7127                    Log.w(TAG, "==> For Service " + s.info.name);
7128                }
7129                addFilter(intent);
7130            }
7131        }
7132
7133        public final void removeService(PackageParser.Service s) {
7134            mServices.remove(s.getComponentName());
7135            if (DEBUG_SHOW_INFO) {
7136                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7137                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7138                Log.v(TAG, "    Class=" + s.info.name);
7139            }
7140            final int NI = s.intents.size();
7141            int j;
7142            for (j=0; j<NI; j++) {
7143                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7144                if (DEBUG_SHOW_INFO) {
7145                    Log.v(TAG, "    IntentFilter:");
7146                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7147                }
7148                removeFilter(intent);
7149            }
7150        }
7151
7152        @Override
7153        protected boolean allowFilterResult(
7154                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7155            ServiceInfo filterSi = filter.service.info;
7156            for (int i=dest.size()-1; i>=0; i--) {
7157                ServiceInfo destAi = dest.get(i).serviceInfo;
7158                if (destAi.name == filterSi.name
7159                        && destAi.packageName == filterSi.packageName) {
7160                    return false;
7161                }
7162            }
7163            return true;
7164        }
7165
7166        @Override
7167        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7168            return new PackageParser.ServiceIntentInfo[size];
7169        }
7170
7171        @Override
7172        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7173            if (!sUserManager.exists(userId)) return true;
7174            PackageParser.Package p = filter.service.owner;
7175            if (p != null) {
7176                PackageSetting ps = (PackageSetting)p.mExtras;
7177                if (ps != null) {
7178                    // System apps are never considered stopped for purposes of
7179                    // filtering, because there may be no way for the user to
7180                    // actually re-launch them.
7181                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7182                            && ps.getStopped(userId);
7183                }
7184            }
7185            return false;
7186        }
7187
7188        @Override
7189        protected boolean isPackageForFilter(String packageName,
7190                PackageParser.ServiceIntentInfo info) {
7191            return packageName.equals(info.service.owner.packageName);
7192        }
7193
7194        @Override
7195        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7196                int match, int userId) {
7197            if (!sUserManager.exists(userId)) return null;
7198            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7199            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7200                return null;
7201            }
7202            final PackageParser.Service service = info.service;
7203            if (mSafeMode && (service.info.applicationInfo.flags
7204                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7205                return null;
7206            }
7207            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7208            if (ps == null) {
7209                return null;
7210            }
7211            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7212                    ps.readUserState(userId), userId);
7213            if (si == null) {
7214                return null;
7215            }
7216            final ResolveInfo res = new ResolveInfo();
7217            res.serviceInfo = si;
7218            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7219                res.filter = filter;
7220            }
7221            res.priority = info.getPriority();
7222            res.preferredOrder = service.owner.mPreferredOrder;
7223            //System.out.println("Result: " + res.activityInfo.className +
7224            //                   " = " + res.priority);
7225            res.match = match;
7226            res.isDefault = info.hasDefault;
7227            res.labelRes = info.labelRes;
7228            res.nonLocalizedLabel = info.nonLocalizedLabel;
7229            res.icon = info.icon;
7230            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7231            return res;
7232        }
7233
7234        @Override
7235        protected void sortResults(List<ResolveInfo> results) {
7236            Collections.sort(results, mResolvePrioritySorter);
7237        }
7238
7239        @Override
7240        protected void dumpFilter(PrintWriter out, String prefix,
7241                PackageParser.ServiceIntentInfo filter) {
7242            out.print(prefix); out.print(
7243                    Integer.toHexString(System.identityHashCode(filter.service)));
7244                    out.print(' ');
7245                    filter.service.printComponentShortName(out);
7246                    out.print(" filter ");
7247                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7248        }
7249
7250//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7251//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7252//            final List<ResolveInfo> retList = Lists.newArrayList();
7253//            while (i.hasNext()) {
7254//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7255//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7256//                    retList.add(resolveInfo);
7257//                }
7258//            }
7259//            return retList;
7260//        }
7261
7262        // Keys are String (activity class name), values are Activity.
7263        private final HashMap<ComponentName, PackageParser.Service> mServices
7264                = new HashMap<ComponentName, PackageParser.Service>();
7265        private int mFlags;
7266    };
7267
7268    private final class ProviderIntentResolver
7269            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7270        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7271                boolean defaultOnly, int userId) {
7272            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7273            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7274        }
7275
7276        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7277                int userId) {
7278            if (!sUserManager.exists(userId))
7279                return null;
7280            mFlags = flags;
7281            return super.queryIntent(intent, resolvedType,
7282                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7283        }
7284
7285        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7286                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7287            if (!sUserManager.exists(userId))
7288                return null;
7289            if (packageProviders == null) {
7290                return null;
7291            }
7292            mFlags = flags;
7293            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7294            final int N = packageProviders.size();
7295            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7296                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7297
7298            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7299            for (int i = 0; i < N; ++i) {
7300                intentFilters = packageProviders.get(i).intents;
7301                if (intentFilters != null && intentFilters.size() > 0) {
7302                    PackageParser.ProviderIntentInfo[] array =
7303                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7304                    intentFilters.toArray(array);
7305                    listCut.add(array);
7306                }
7307            }
7308            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7309        }
7310
7311        public final void addProvider(PackageParser.Provider p) {
7312            if (mProviders.containsKey(p.getComponentName())) {
7313                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7314                return;
7315            }
7316
7317            mProviders.put(p.getComponentName(), p);
7318            if (DEBUG_SHOW_INFO) {
7319                Log.v(TAG, "  "
7320                        + (p.info.nonLocalizedLabel != null
7321                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7322                Log.v(TAG, "    Class=" + p.info.name);
7323            }
7324            final int NI = p.intents.size();
7325            int j;
7326            for (j = 0; j < NI; j++) {
7327                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7328                if (DEBUG_SHOW_INFO) {
7329                    Log.v(TAG, "    IntentFilter:");
7330                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7331                }
7332                if (!intent.debugCheck()) {
7333                    Log.w(TAG, "==> For Provider " + p.info.name);
7334                }
7335                addFilter(intent);
7336            }
7337        }
7338
7339        public final void removeProvider(PackageParser.Provider p) {
7340            mProviders.remove(p.getComponentName());
7341            if (DEBUG_SHOW_INFO) {
7342                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7343                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7344                Log.v(TAG, "    Class=" + p.info.name);
7345            }
7346            final int NI = p.intents.size();
7347            int j;
7348            for (j = 0; j < NI; j++) {
7349                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7350                if (DEBUG_SHOW_INFO) {
7351                    Log.v(TAG, "    IntentFilter:");
7352                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7353                }
7354                removeFilter(intent);
7355            }
7356        }
7357
7358        @Override
7359        protected boolean allowFilterResult(
7360                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7361            ProviderInfo filterPi = filter.provider.info;
7362            for (int i = dest.size() - 1; i >= 0; i--) {
7363                ProviderInfo destPi = dest.get(i).providerInfo;
7364                if (destPi.name == filterPi.name
7365                        && destPi.packageName == filterPi.packageName) {
7366                    return false;
7367                }
7368            }
7369            return true;
7370        }
7371
7372        @Override
7373        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7374            return new PackageParser.ProviderIntentInfo[size];
7375        }
7376
7377        @Override
7378        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7379            if (!sUserManager.exists(userId))
7380                return true;
7381            PackageParser.Package p = filter.provider.owner;
7382            if (p != null) {
7383                PackageSetting ps = (PackageSetting) p.mExtras;
7384                if (ps != null) {
7385                    // System apps are never considered stopped for purposes of
7386                    // filtering, because there may be no way for the user to
7387                    // actually re-launch them.
7388                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7389                            && ps.getStopped(userId);
7390                }
7391            }
7392            return false;
7393        }
7394
7395        @Override
7396        protected boolean isPackageForFilter(String packageName,
7397                PackageParser.ProviderIntentInfo info) {
7398            return packageName.equals(info.provider.owner.packageName);
7399        }
7400
7401        @Override
7402        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7403                int match, int userId) {
7404            if (!sUserManager.exists(userId))
7405                return null;
7406            final PackageParser.ProviderIntentInfo info = filter;
7407            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7408                return null;
7409            }
7410            final PackageParser.Provider provider = info.provider;
7411            if (mSafeMode && (provider.info.applicationInfo.flags
7412                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7413                return null;
7414            }
7415            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7416            if (ps == null) {
7417                return null;
7418            }
7419            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7420                    ps.readUserState(userId), userId);
7421            if (pi == null) {
7422                return null;
7423            }
7424            final ResolveInfo res = new ResolveInfo();
7425            res.providerInfo = pi;
7426            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7427                res.filter = filter;
7428            }
7429            res.priority = info.getPriority();
7430            res.preferredOrder = provider.owner.mPreferredOrder;
7431            res.match = match;
7432            res.isDefault = info.hasDefault;
7433            res.labelRes = info.labelRes;
7434            res.nonLocalizedLabel = info.nonLocalizedLabel;
7435            res.icon = info.icon;
7436            res.system = isSystemApp(res.providerInfo.applicationInfo);
7437            return res;
7438        }
7439
7440        @Override
7441        protected void sortResults(List<ResolveInfo> results) {
7442            Collections.sort(results, mResolvePrioritySorter);
7443        }
7444
7445        @Override
7446        protected void dumpFilter(PrintWriter out, String prefix,
7447                PackageParser.ProviderIntentInfo filter) {
7448            out.print(prefix);
7449            out.print(
7450                    Integer.toHexString(System.identityHashCode(filter.provider)));
7451            out.print(' ');
7452            filter.provider.printComponentShortName(out);
7453            out.print(" filter ");
7454            out.println(Integer.toHexString(System.identityHashCode(filter)));
7455        }
7456
7457        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7458                = new HashMap<ComponentName, PackageParser.Provider>();
7459        private int mFlags;
7460    };
7461
7462    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7463            new Comparator<ResolveInfo>() {
7464        public int compare(ResolveInfo r1, ResolveInfo r2) {
7465            int v1 = r1.priority;
7466            int v2 = r2.priority;
7467            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7468            if (v1 != v2) {
7469                return (v1 > v2) ? -1 : 1;
7470            }
7471            v1 = r1.preferredOrder;
7472            v2 = r2.preferredOrder;
7473            if (v1 != v2) {
7474                return (v1 > v2) ? -1 : 1;
7475            }
7476            if (r1.isDefault != r2.isDefault) {
7477                return r1.isDefault ? -1 : 1;
7478            }
7479            v1 = r1.match;
7480            v2 = r2.match;
7481            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7482            if (v1 != v2) {
7483                return (v1 > v2) ? -1 : 1;
7484            }
7485            if (r1.system != r2.system) {
7486                return r1.system ? -1 : 1;
7487            }
7488            return 0;
7489        }
7490    };
7491
7492    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7493            new Comparator<ProviderInfo>() {
7494        public int compare(ProviderInfo p1, ProviderInfo p2) {
7495            final int v1 = p1.initOrder;
7496            final int v2 = p2.initOrder;
7497            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7498        }
7499    };
7500
7501    static final void sendPackageBroadcast(String action, String pkg,
7502            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7503            int[] userIds) {
7504        IActivityManager am = ActivityManagerNative.getDefault();
7505        if (am != null) {
7506            try {
7507                if (userIds == null) {
7508                    userIds = am.getRunningUserIds();
7509                }
7510                for (int id : userIds) {
7511                    final Intent intent = new Intent(action,
7512                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7513                    if (extras != null) {
7514                        intent.putExtras(extras);
7515                    }
7516                    if (targetPkg != null) {
7517                        intent.setPackage(targetPkg);
7518                    }
7519                    // Modify the UID when posting to other users
7520                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7521                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7522                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7523                        intent.putExtra(Intent.EXTRA_UID, uid);
7524                    }
7525                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7526                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7527                    if (DEBUG_BROADCASTS) {
7528                        RuntimeException here = new RuntimeException("here");
7529                        here.fillInStackTrace();
7530                        Slog.d(TAG, "Sending to user " + id + ": "
7531                                + intent.toShortString(false, true, false, false)
7532                                + " " + intent.getExtras(), here);
7533                    }
7534                    am.broadcastIntent(null, intent, null, finishedReceiver,
7535                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7536                            finishedReceiver != null, false, id);
7537                }
7538            } catch (RemoteException ex) {
7539            }
7540        }
7541    }
7542
7543    /**
7544     * Check if the external storage media is available. This is true if there
7545     * is a mounted external storage medium or if the external storage is
7546     * emulated.
7547     */
7548    private boolean isExternalMediaAvailable() {
7549        return mMediaMounted || Environment.isExternalStorageEmulated();
7550    }
7551
7552    @Override
7553    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7554        // writer
7555        synchronized (mPackages) {
7556            if (!isExternalMediaAvailable()) {
7557                // If the external storage is no longer mounted at this point,
7558                // the caller may not have been able to delete all of this
7559                // packages files and can not delete any more.  Bail.
7560                return null;
7561            }
7562            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7563            if (lastPackage != null) {
7564                pkgs.remove(lastPackage);
7565            }
7566            if (pkgs.size() > 0) {
7567                return pkgs.get(0);
7568            }
7569        }
7570        return null;
7571    }
7572
7573    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7574        if (false) {
7575            RuntimeException here = new RuntimeException("here");
7576            here.fillInStackTrace();
7577            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7578                    + " andCode=" + andCode, here);
7579        }
7580        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7581                userId, andCode ? 1 : 0, packageName));
7582    }
7583
7584    void startCleaningPackages() {
7585        // reader
7586        synchronized (mPackages) {
7587            if (!isExternalMediaAvailable()) {
7588                return;
7589            }
7590            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7591                return;
7592            }
7593        }
7594        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7595        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7596        IActivityManager am = ActivityManagerNative.getDefault();
7597        if (am != null) {
7598            try {
7599                am.startService(null, intent, null, UserHandle.USER_OWNER);
7600            } catch (RemoteException e) {
7601            }
7602        }
7603    }
7604
7605    private final class AppDirObserver extends FileObserver {
7606        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7607            super(path, mask);
7608            mRootDir = path;
7609            mIsRom = isrom;
7610            mIsPrivileged = isPrivileged;
7611        }
7612
7613        public void onEvent(int event, String path) {
7614            String removedPackage = null;
7615            int removedAppId = -1;
7616            int[] removedUsers = null;
7617            String addedPackage = null;
7618            int addedAppId = -1;
7619            int[] addedUsers = null;
7620
7621            // TODO post a message to the handler to obtain serial ordering
7622            synchronized (mInstallLock) {
7623                String fullPathStr = null;
7624                File fullPath = null;
7625                if (path != null) {
7626                    fullPath = new File(mRootDir, path);
7627                    fullPathStr = fullPath.getPath();
7628                }
7629
7630                if (DEBUG_APP_DIR_OBSERVER)
7631                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7632
7633                if (!isPackageFilename(path)) {
7634                    if (DEBUG_APP_DIR_OBSERVER)
7635                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7636                    return;
7637                }
7638
7639                // Ignore packages that are being installed or
7640                // have just been installed.
7641                if (ignoreCodePath(fullPathStr)) {
7642                    return;
7643                }
7644                PackageParser.Package p = null;
7645                PackageSetting ps = null;
7646                // reader
7647                synchronized (mPackages) {
7648                    p = mAppDirs.get(fullPathStr);
7649                    if (p != null) {
7650                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7651                        if (ps != null) {
7652                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7653                        } else {
7654                            removedUsers = sUserManager.getUserIds();
7655                        }
7656                    }
7657                    addedUsers = sUserManager.getUserIds();
7658                }
7659                if ((event&REMOVE_EVENTS) != 0) {
7660                    if (ps != null) {
7661                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7662                        removePackageLI(ps, true);
7663                        removedPackage = ps.name;
7664                        removedAppId = ps.appId;
7665                    }
7666                }
7667
7668                if ((event&ADD_EVENTS) != 0) {
7669                    if (p == null) {
7670                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7671                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7672                        if (mIsRom) {
7673                            flags |= PackageParser.PARSE_IS_SYSTEM
7674                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7675                            if (mIsPrivileged) {
7676                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7677                            }
7678                        }
7679                        p = scanPackageLI(fullPath, flags,
7680                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7681                                System.currentTimeMillis(), UserHandle.ALL, null);
7682                        if (p != null) {
7683                            /*
7684                             * TODO this seems dangerous as the package may have
7685                             * changed since we last acquired the mPackages
7686                             * lock.
7687                             */
7688                            // writer
7689                            synchronized (mPackages) {
7690                                updatePermissionsLPw(p.packageName, p,
7691                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7692                            }
7693                            addedPackage = p.applicationInfo.packageName;
7694                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7695                        }
7696                    }
7697                }
7698
7699                // reader
7700                synchronized (mPackages) {
7701                    mSettings.writeLPr();
7702                }
7703            }
7704
7705            if (removedPackage != null) {
7706                Bundle extras = new Bundle(1);
7707                extras.putInt(Intent.EXTRA_UID, removedAppId);
7708                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7709                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7710                        extras, null, null, removedUsers);
7711            }
7712            if (addedPackage != null) {
7713                Bundle extras = new Bundle(1);
7714                extras.putInt(Intent.EXTRA_UID, addedAppId);
7715                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7716                        extras, null, null, addedUsers);
7717            }
7718        }
7719
7720        private final String mRootDir;
7721        private final boolean mIsRom;
7722        private final boolean mIsPrivileged;
7723    }
7724
7725    /*
7726     * The old-style observer methods all just trampoline to the newer signature with
7727     * expanded install observer API.  The older API continues to work but does not
7728     * supply the additional details of the Observer2 API.
7729     */
7730
7731    /* Called when a downloaded package installation has been confirmed by the user */
7732    public void installPackage(
7733            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7734        installPackageEtc(packageURI, observer, null, flags, null);
7735    }
7736
7737    /* Called when a downloaded package installation has been confirmed by the user */
7738    @Override
7739    public void installPackage(
7740            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7741            final String installerPackageName) {
7742        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7743                installerPackageName, null, null, null);
7744    }
7745
7746    @Override
7747    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7748            int flags, String installerPackageName, Uri verificationURI,
7749            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7750        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7751                VerificationParams.NO_UID, manifestDigest);
7752        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7753                installerPackageName, verificationParams, encryptionParams);
7754    }
7755
7756    @Override
7757    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7758            IPackageInstallObserver observer, int flags, String installerPackageName,
7759            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7760        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7761                installerPackageName, verificationParams, encryptionParams);
7762    }
7763
7764    /*
7765     * And here are the "live" versions that take both observer arguments
7766     */
7767    public void installPackageEtc(
7768            final Uri packageURI, final IPackageInstallObserver observer,
7769            IPackageInstallObserver2 observer2, final int flags) {
7770        installPackageEtc(packageURI, observer, observer2, flags, null);
7771    }
7772
7773    public void installPackageEtc(
7774            final Uri packageURI, final IPackageInstallObserver observer,
7775            final IPackageInstallObserver2 observer2, final int flags,
7776            final String installerPackageName) {
7777        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7778                installerPackageName, null, null, null);
7779    }
7780
7781    @Override
7782    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7783            IPackageInstallObserver2 observer2,
7784            int flags, String installerPackageName, Uri verificationURI,
7785            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7786        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7787                VerificationParams.NO_UID, manifestDigest);
7788        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7789                installerPackageName, verificationParams, encryptionParams);
7790    }
7791
7792    /*
7793     * All of the installPackage...*() methods redirect to this one for the master implementation
7794     */
7795    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7796            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7797            int flags, String installerPackageName,
7798            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7799        if (observer == null && observer2 == null) {
7800            throw new IllegalArgumentException("No install observer supplied");
7801        }
7802        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7803                flags, installerPackageName, verificationParams, encryptionParams, null);
7804    }
7805
7806    @Override
7807    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7808            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7809            int flags, String installerPackageName,
7810            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7811            String packageAbiOverride) {
7812        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7813                null);
7814
7815        final int uid = Binder.getCallingUid();
7816        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7817            try {
7818                if (observer != null) {
7819                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7820                }
7821                if (observer2 != null) {
7822                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7823                }
7824            } catch (RemoteException re) {
7825            }
7826            return;
7827        }
7828
7829        UserHandle user;
7830        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7831            user = UserHandle.ALL;
7832        } else {
7833            user = new UserHandle(UserHandle.getUserId(uid));
7834        }
7835
7836        final int filteredFlags;
7837
7838        if (uid == Process.SHELL_UID || uid == 0) {
7839            if (DEBUG_INSTALL) {
7840                Slog.v(TAG, "Install from ADB");
7841            }
7842            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7843        } else {
7844            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7845        }
7846
7847        verificationParams.setInstallerUid(uid);
7848
7849        final Message msg = mHandler.obtainMessage(INIT_COPY);
7850        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7851                installerPackageName, verificationParams, encryptionParams, user,
7852                packageAbiOverride);
7853        mHandler.sendMessage(msg);
7854    }
7855
7856    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7857        Bundle extras = new Bundle(1);
7858        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7859
7860        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7861                packageName, extras, null, null, new int[] {userId});
7862        try {
7863            IActivityManager am = ActivityManagerNative.getDefault();
7864            final boolean isSystem =
7865                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7866            if (isSystem && am.isUserRunning(userId, false)) {
7867                // The just-installed/enabled app is bundled on the system, so presumed
7868                // to be able to run automatically without needing an explicit launch.
7869                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7870                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7871                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7872                        .setPackage(packageName);
7873                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7874                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7875            }
7876        } catch (RemoteException e) {
7877            // shouldn't happen
7878            Slog.w(TAG, "Unable to bootstrap installed package", e);
7879        }
7880    }
7881
7882    @Override
7883    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7884            int userId) {
7885        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7886        PackageSetting pkgSetting;
7887        final int uid = Binder.getCallingUid();
7888        if (UserHandle.getUserId(uid) != userId) {
7889            mContext.enforceCallingOrSelfPermission(
7890                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7891                    "setApplicationBlockedSetting for user " + userId);
7892        }
7893
7894        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7895            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7896            return false;
7897        }
7898
7899        long callingId = Binder.clearCallingIdentity();
7900        try {
7901            boolean sendAdded = false;
7902            boolean sendRemoved = false;
7903            // writer
7904            synchronized (mPackages) {
7905                pkgSetting = mSettings.mPackages.get(packageName);
7906                if (pkgSetting == null) {
7907                    return false;
7908                }
7909                if (pkgSetting.getBlocked(userId) != blocked) {
7910                    pkgSetting.setBlocked(blocked, userId);
7911                    mSettings.writePackageRestrictionsLPr(userId);
7912                    if (blocked) {
7913                        sendRemoved = true;
7914                    } else {
7915                        sendAdded = true;
7916                    }
7917                }
7918            }
7919            if (sendAdded) {
7920                sendPackageAddedForUser(packageName, pkgSetting, userId);
7921                return true;
7922            }
7923            if (sendRemoved) {
7924                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7925                        "blocking pkg");
7926                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7927            }
7928        } finally {
7929            Binder.restoreCallingIdentity(callingId);
7930        }
7931        return false;
7932    }
7933
7934    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7935            int userId) {
7936        final PackageRemovedInfo info = new PackageRemovedInfo();
7937        info.removedPackage = packageName;
7938        info.removedUsers = new int[] {userId};
7939        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7940        info.sendBroadcast(false, false, false);
7941    }
7942
7943    /**
7944     * Returns true if application is not found or there was an error. Otherwise it returns
7945     * the blocked state of the package for the given user.
7946     */
7947    @Override
7948    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7950        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7951                "getApplicationBlocked for user " + userId);
7952        PackageSetting pkgSetting;
7953        long callingId = Binder.clearCallingIdentity();
7954        try {
7955            // writer
7956            synchronized (mPackages) {
7957                pkgSetting = mSettings.mPackages.get(packageName);
7958                if (pkgSetting == null) {
7959                    return true;
7960                }
7961                return pkgSetting.getBlocked(userId);
7962            }
7963        } finally {
7964            Binder.restoreCallingIdentity(callingId);
7965        }
7966    }
7967
7968    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7969            int flags) {
7970        // TODO: install stage!
7971        try {
7972            observer.packageInstalled(basePackageName, null,
7973                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7974        } catch (RemoteException ignored) {
7975        }
7976    }
7977
7978    /**
7979     * @hide
7980     */
7981    @Override
7982    public int installExistingPackageAsUser(String packageName, int userId) {
7983        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7984                null);
7985        PackageSetting pkgSetting;
7986        final int uid = Binder.getCallingUid();
7987        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7988        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7989            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7990        }
7991
7992        long callingId = Binder.clearCallingIdentity();
7993        try {
7994            boolean sendAdded = false;
7995            Bundle extras = new Bundle(1);
7996
7997            // writer
7998            synchronized (mPackages) {
7999                pkgSetting = mSettings.mPackages.get(packageName);
8000                if (pkgSetting == null) {
8001                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8002                }
8003                if (!pkgSetting.getInstalled(userId)) {
8004                    pkgSetting.setInstalled(true, userId);
8005                    pkgSetting.setBlocked(false, userId);
8006                    mSettings.writePackageRestrictionsLPr(userId);
8007                    sendAdded = true;
8008                }
8009            }
8010
8011            if (sendAdded) {
8012                sendPackageAddedForUser(packageName, pkgSetting, userId);
8013            }
8014        } finally {
8015            Binder.restoreCallingIdentity(callingId);
8016        }
8017
8018        return PackageManager.INSTALL_SUCCEEDED;
8019    }
8020
8021    boolean isUserRestricted(int userId, String restrictionKey) {
8022        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8023        if (restrictions.getBoolean(restrictionKey, false)) {
8024            Log.w(TAG, "User is restricted: " + restrictionKey);
8025            return true;
8026        }
8027        return false;
8028    }
8029
8030    @Override
8031    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8032        mContext.enforceCallingOrSelfPermission(
8033                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8034                "Only package verification agents can verify applications");
8035
8036        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8037        final PackageVerificationResponse response = new PackageVerificationResponse(
8038                verificationCode, Binder.getCallingUid());
8039        msg.arg1 = id;
8040        msg.obj = response;
8041        mHandler.sendMessage(msg);
8042    }
8043
8044    @Override
8045    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8046            long millisecondsToDelay) {
8047        mContext.enforceCallingOrSelfPermission(
8048                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8049                "Only package verification agents can extend verification timeouts");
8050
8051        final PackageVerificationState state = mPendingVerification.get(id);
8052        final PackageVerificationResponse response = new PackageVerificationResponse(
8053                verificationCodeAtTimeout, Binder.getCallingUid());
8054
8055        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8056            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8057        }
8058        if (millisecondsToDelay < 0) {
8059            millisecondsToDelay = 0;
8060        }
8061        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8062                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8063            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8064        }
8065
8066        if ((state != null) && !state.timeoutExtended()) {
8067            state.extendTimeout();
8068
8069            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8070            msg.arg1 = id;
8071            msg.obj = response;
8072            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8073        }
8074    }
8075
8076    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8077            int verificationCode, UserHandle user) {
8078        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8079        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8080        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8081        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8082        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8083
8084        mContext.sendBroadcastAsUser(intent, user,
8085                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8086    }
8087
8088    private ComponentName matchComponentForVerifier(String packageName,
8089            List<ResolveInfo> receivers) {
8090        ActivityInfo targetReceiver = null;
8091
8092        final int NR = receivers.size();
8093        for (int i = 0; i < NR; i++) {
8094            final ResolveInfo info = receivers.get(i);
8095            if (info.activityInfo == null) {
8096                continue;
8097            }
8098
8099            if (packageName.equals(info.activityInfo.packageName)) {
8100                targetReceiver = info.activityInfo;
8101                break;
8102            }
8103        }
8104
8105        if (targetReceiver == null) {
8106            return null;
8107        }
8108
8109        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8110    }
8111
8112    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8113            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8114        if (pkgInfo.verifiers.length == 0) {
8115            return null;
8116        }
8117
8118        final int N = pkgInfo.verifiers.length;
8119        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8120        for (int i = 0; i < N; i++) {
8121            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8122
8123            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8124                    receivers);
8125            if (comp == null) {
8126                continue;
8127            }
8128
8129            final int verifierUid = getUidForVerifier(verifierInfo);
8130            if (verifierUid == -1) {
8131                continue;
8132            }
8133
8134            if (DEBUG_VERIFY) {
8135                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8136                        + " with the correct signature");
8137            }
8138            sufficientVerifiers.add(comp);
8139            verificationState.addSufficientVerifier(verifierUid);
8140        }
8141
8142        return sufficientVerifiers;
8143    }
8144
8145    private int getUidForVerifier(VerifierInfo verifierInfo) {
8146        synchronized (mPackages) {
8147            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8148            if (pkg == null) {
8149                return -1;
8150            } else if (pkg.mSignatures.length != 1) {
8151                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8152                        + " has more than one signature; ignoring");
8153                return -1;
8154            }
8155
8156            /*
8157             * If the public key of the package's signature does not match
8158             * our expected public key, then this is a different package and
8159             * we should skip.
8160             */
8161
8162            final byte[] expectedPublicKey;
8163            try {
8164                final Signature verifierSig = pkg.mSignatures[0];
8165                final PublicKey publicKey = verifierSig.getPublicKey();
8166                expectedPublicKey = publicKey.getEncoded();
8167            } catch (CertificateException e) {
8168                return -1;
8169            }
8170
8171            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8172
8173            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8174                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8175                        + " does not have the expected public key; ignoring");
8176                return -1;
8177            }
8178
8179            return pkg.applicationInfo.uid;
8180        }
8181    }
8182
8183    @Override
8184    public void finishPackageInstall(int token) {
8185        enforceSystemOrRoot("Only the system is allowed to finish installs");
8186
8187        if (DEBUG_INSTALL) {
8188            Slog.v(TAG, "BM finishing package install for " + token);
8189        }
8190
8191        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8192        mHandler.sendMessage(msg);
8193    }
8194
8195    /**
8196     * Get the verification agent timeout.
8197     *
8198     * @return verification timeout in milliseconds
8199     */
8200    private long getVerificationTimeout() {
8201        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8202                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8203                DEFAULT_VERIFICATION_TIMEOUT);
8204    }
8205
8206    /**
8207     * Get the default verification agent response code.
8208     *
8209     * @return default verification response code
8210     */
8211    private int getDefaultVerificationResponse() {
8212        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8213                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8214                DEFAULT_VERIFICATION_RESPONSE);
8215    }
8216
8217    /**
8218     * Check whether or not package verification has been enabled.
8219     *
8220     * @return true if verification should be performed
8221     */
8222    private boolean isVerificationEnabled(int flags) {
8223        if (!DEFAULT_VERIFY_ENABLE) {
8224            return false;
8225        }
8226
8227        // Check if installing from ADB
8228        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8229            // Do not run verification in a test harness environment
8230            if (ActivityManager.isRunningInTestHarness()) {
8231                return false;
8232            }
8233            // Check if the developer does not want package verification for ADB installs
8234            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8235                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8236                return false;
8237            }
8238        }
8239
8240        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8241                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8242    }
8243
8244    /**
8245     * Get the "allow unknown sources" setting.
8246     *
8247     * @return the current "allow unknown sources" setting
8248     */
8249    private int getUnknownSourcesSettings() {
8250        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8251                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8252                -1);
8253    }
8254
8255    @Override
8256    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8257        final int uid = Binder.getCallingUid();
8258        // writer
8259        synchronized (mPackages) {
8260            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8261            if (targetPackageSetting == null) {
8262                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8263            }
8264
8265            PackageSetting installerPackageSetting;
8266            if (installerPackageName != null) {
8267                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8268                if (installerPackageSetting == null) {
8269                    throw new IllegalArgumentException("Unknown installer package: "
8270                            + installerPackageName);
8271                }
8272            } else {
8273                installerPackageSetting = null;
8274            }
8275
8276            Signature[] callerSignature;
8277            Object obj = mSettings.getUserIdLPr(uid);
8278            if (obj != null) {
8279                if (obj instanceof SharedUserSetting) {
8280                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8281                } else if (obj instanceof PackageSetting) {
8282                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8283                } else {
8284                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8285                }
8286            } else {
8287                throw new SecurityException("Unknown calling uid " + uid);
8288            }
8289
8290            // Verify: can't set installerPackageName to a package that is
8291            // not signed with the same cert as the caller.
8292            if (installerPackageSetting != null) {
8293                if (compareSignatures(callerSignature,
8294                        installerPackageSetting.signatures.mSignatures)
8295                        != PackageManager.SIGNATURE_MATCH) {
8296                    throw new SecurityException(
8297                            "Caller does not have same cert as new installer package "
8298                            + installerPackageName);
8299                }
8300            }
8301
8302            // Verify: if target already has an installer package, it must
8303            // be signed with the same cert as the caller.
8304            if (targetPackageSetting.installerPackageName != null) {
8305                PackageSetting setting = mSettings.mPackages.get(
8306                        targetPackageSetting.installerPackageName);
8307                // If the currently set package isn't valid, then it's always
8308                // okay to change it.
8309                if (setting != null) {
8310                    if (compareSignatures(callerSignature,
8311                            setting.signatures.mSignatures)
8312                            != PackageManager.SIGNATURE_MATCH) {
8313                        throw new SecurityException(
8314                                "Caller does not have same cert as old installer package "
8315                                + targetPackageSetting.installerPackageName);
8316                    }
8317                }
8318            }
8319
8320            // Okay!
8321            targetPackageSetting.installerPackageName = installerPackageName;
8322            scheduleWriteSettingsLocked();
8323        }
8324    }
8325
8326    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8327        // Queue up an async operation since the package installation may take a little while.
8328        mHandler.post(new Runnable() {
8329            public void run() {
8330                mHandler.removeCallbacks(this);
8331                 // Result object to be returned
8332                PackageInstalledInfo res = new PackageInstalledInfo();
8333                res.returnCode = currentStatus;
8334                res.uid = -1;
8335                res.pkg = null;
8336                res.removedInfo = new PackageRemovedInfo();
8337                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8338                    args.doPreInstall(res.returnCode);
8339                    synchronized (mInstallLock) {
8340                        installPackageLI(args, true, res);
8341                    }
8342                    args.doPostInstall(res.returnCode, res.uid);
8343                }
8344
8345                // A restore should be performed at this point if (a) the install
8346                // succeeded, (b) the operation is not an update, and (c) the new
8347                // package has a backupAgent defined.
8348                final boolean update = res.removedInfo.removedPackage != null;
8349                boolean doRestore = (!update
8350                        && res.pkg != null
8351                        && res.pkg.applicationInfo.backupAgentName != null);
8352
8353                // Set up the post-install work request bookkeeping.  This will be used
8354                // and cleaned up by the post-install event handling regardless of whether
8355                // there's a restore pass performed.  Token values are >= 1.
8356                int token;
8357                if (mNextInstallToken < 0) mNextInstallToken = 1;
8358                token = mNextInstallToken++;
8359
8360                PostInstallData data = new PostInstallData(args, res);
8361                mRunningInstalls.put(token, data);
8362                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8363
8364                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8365                    // Pass responsibility to the Backup Manager.  It will perform a
8366                    // restore if appropriate, then pass responsibility back to the
8367                    // Package Manager to run the post-install observer callbacks
8368                    // and broadcasts.
8369                    IBackupManager bm = IBackupManager.Stub.asInterface(
8370                            ServiceManager.getService(Context.BACKUP_SERVICE));
8371                    if (bm != null) {
8372                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8373                                + " to BM for possible restore");
8374                        try {
8375                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8376                        } catch (RemoteException e) {
8377                            // can't happen; the backup manager is local
8378                        } catch (Exception e) {
8379                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8380                            doRestore = false;
8381                        }
8382                    } else {
8383                        Slog.e(TAG, "Backup Manager not found!");
8384                        doRestore = false;
8385                    }
8386                }
8387
8388                if (!doRestore) {
8389                    // No restore possible, or the Backup Manager was mysteriously not
8390                    // available -- just fire the post-install work request directly.
8391                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8392                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8393                    mHandler.sendMessage(msg);
8394                }
8395            }
8396        });
8397    }
8398
8399    private abstract class HandlerParams {
8400        private static final int MAX_RETRIES = 4;
8401
8402        /**
8403         * Number of times startCopy() has been attempted and had a non-fatal
8404         * error.
8405         */
8406        private int mRetries = 0;
8407
8408        /** User handle for the user requesting the information or installation. */
8409        private final UserHandle mUser;
8410
8411        HandlerParams(UserHandle user) {
8412            mUser = user;
8413        }
8414
8415        UserHandle getUser() {
8416            return mUser;
8417        }
8418
8419        final boolean startCopy() {
8420            boolean res;
8421            try {
8422                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8423
8424                if (++mRetries > MAX_RETRIES) {
8425                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8426                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8427                    handleServiceError();
8428                    return false;
8429                } else {
8430                    handleStartCopy();
8431                    res = true;
8432                }
8433            } catch (RemoteException e) {
8434                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8435                mHandler.sendEmptyMessage(MCS_RECONNECT);
8436                res = false;
8437            }
8438            handleReturnCode();
8439            return res;
8440        }
8441
8442        final void serviceError() {
8443            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8444            handleServiceError();
8445            handleReturnCode();
8446        }
8447
8448        abstract void handleStartCopy() throws RemoteException;
8449        abstract void handleServiceError();
8450        abstract void handleReturnCode();
8451    }
8452
8453    class MeasureParams extends HandlerParams {
8454        private final PackageStats mStats;
8455        private boolean mSuccess;
8456
8457        private final IPackageStatsObserver mObserver;
8458
8459        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8460            super(new UserHandle(stats.userHandle));
8461            mObserver = observer;
8462            mStats = stats;
8463        }
8464
8465        @Override
8466        public String toString() {
8467            return "MeasureParams{"
8468                + Integer.toHexString(System.identityHashCode(this))
8469                + " " + mStats.packageName + "}";
8470        }
8471
8472        @Override
8473        void handleStartCopy() throws RemoteException {
8474            synchronized (mInstallLock) {
8475                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8476            }
8477
8478            if (mSuccess) {
8479                final boolean mounted;
8480                if (Environment.isExternalStorageEmulated()) {
8481                    mounted = true;
8482                } else {
8483                    final String status = Environment.getExternalStorageState();
8484                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8485                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8486                }
8487
8488                if (mounted) {
8489                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8490
8491                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8492                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8493
8494                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8495                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8496
8497                    // Always subtract cache size, since it's a subdirectory
8498                    mStats.externalDataSize -= mStats.externalCacheSize;
8499
8500                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8501                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8502
8503                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8504                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8505                }
8506            }
8507        }
8508
8509        @Override
8510        void handleReturnCode() {
8511            if (mObserver != null) {
8512                try {
8513                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8514                } catch (RemoteException e) {
8515                    Slog.i(TAG, "Observer no longer exists.");
8516                }
8517            }
8518        }
8519
8520        @Override
8521        void handleServiceError() {
8522            Slog.e(TAG, "Could not measure application " + mStats.packageName
8523                            + " external storage");
8524        }
8525    }
8526
8527    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8528            throws RemoteException {
8529        long result = 0;
8530        for (File path : paths) {
8531            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8532        }
8533        return result;
8534    }
8535
8536    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8537        for (File path : paths) {
8538            try {
8539                mcs.clearDirectory(path.getAbsolutePath());
8540            } catch (RemoteException e) {
8541            }
8542        }
8543    }
8544
8545    class InstallParams extends HandlerParams {
8546        final IPackageInstallObserver observer;
8547        final IPackageInstallObserver2 observer2;
8548        int flags;
8549
8550        private final Uri mPackageURI;
8551        final String installerPackageName;
8552        final VerificationParams verificationParams;
8553        private InstallArgs mArgs;
8554        private int mRet;
8555        private File mTempPackage;
8556        final ContainerEncryptionParams encryptionParams;
8557        final String packageAbiOverride;
8558        final String packageInstructionSetOverride;
8559
8560        InstallParams(Uri packageURI,
8561                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8562                int flags, String installerPackageName, VerificationParams verificationParams,
8563                ContainerEncryptionParams encryptionParams, UserHandle user,
8564                String packageAbiOverride) {
8565            super(user);
8566            this.mPackageURI = packageURI;
8567            this.flags = flags;
8568            this.observer = observer;
8569            this.observer2 = observer2;
8570            this.installerPackageName = installerPackageName;
8571            this.verificationParams = verificationParams;
8572            this.encryptionParams = encryptionParams;
8573            this.packageAbiOverride = packageAbiOverride;
8574            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8575                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8576        }
8577
8578        @Override
8579        public String toString() {
8580            return "InstallParams{"
8581                + Integer.toHexString(System.identityHashCode(this))
8582                + " " + mPackageURI + "}";
8583        }
8584
8585        public ManifestDigest getManifestDigest() {
8586            if (verificationParams == null) {
8587                return null;
8588            }
8589            return verificationParams.getManifestDigest();
8590        }
8591
8592        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8593            String packageName = pkgLite.packageName;
8594            int installLocation = pkgLite.installLocation;
8595            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8596            // reader
8597            synchronized (mPackages) {
8598                PackageParser.Package pkg = mPackages.get(packageName);
8599                if (pkg != null) {
8600                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8601                        // Check for downgrading.
8602                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8603                            if (pkgLite.versionCode < pkg.mVersionCode) {
8604                                Slog.w(TAG, "Can't install update of " + packageName
8605                                        + " update version " + pkgLite.versionCode
8606                                        + " is older than installed version "
8607                                        + pkg.mVersionCode);
8608                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8609                            }
8610                        }
8611                        // Check for updated system application.
8612                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8613                            if (onSd) {
8614                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8615                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8616                            }
8617                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8618                        } else {
8619                            if (onSd) {
8620                                // Install flag overrides everything.
8621                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8622                            }
8623                            // If current upgrade specifies particular preference
8624                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8625                                // Application explicitly specified internal.
8626                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8627                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8628                                // App explictly prefers external. Let policy decide
8629                            } else {
8630                                // Prefer previous location
8631                                if (isExternal(pkg)) {
8632                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8633                                }
8634                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8635                            }
8636                        }
8637                    } else {
8638                        // Invalid install. Return error code
8639                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8640                    }
8641                }
8642            }
8643            // All the special cases have been taken care of.
8644            // Return result based on recommended install location.
8645            if (onSd) {
8646                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8647            }
8648            return pkgLite.recommendedInstallLocation;
8649        }
8650
8651        private long getMemoryLowThreshold() {
8652            final DeviceStorageMonitorInternal
8653                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8654            if (dsm == null) {
8655                return 0L;
8656            }
8657            return dsm.getMemoryLowThreshold();
8658        }
8659
8660        /*
8661         * Invoke remote method to get package information and install
8662         * location values. Override install location based on default
8663         * policy if needed and then create install arguments based
8664         * on the install location.
8665         */
8666        public void handleStartCopy() throws RemoteException {
8667            int ret = PackageManager.INSTALL_SUCCEEDED;
8668            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8669            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8670            PackageInfoLite pkgLite = null;
8671
8672            if (onInt && onSd) {
8673                // Check if both bits are set.
8674                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8675                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8676            } else {
8677                final long lowThreshold = getMemoryLowThreshold();
8678                if (lowThreshold == 0L) {
8679                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8680                }
8681
8682                try {
8683                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8684                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8685
8686                    final File packageFile;
8687                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8688                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8689                        if (mTempPackage != null) {
8690                            ParcelFileDescriptor out;
8691                            try {
8692                                out = ParcelFileDescriptor.open(mTempPackage,
8693                                        ParcelFileDescriptor.MODE_READ_WRITE);
8694                            } catch (FileNotFoundException e) {
8695                                out = null;
8696                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8697                            }
8698
8699                            // Make a temporary file for decryption.
8700                            ret = mContainerService
8701                                    .copyResource(mPackageURI, encryptionParams, out);
8702                            IoUtils.closeQuietly(out);
8703
8704                            packageFile = mTempPackage;
8705
8706                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8707                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8708                                            | FileUtils.S_IROTH,
8709                                    -1, -1);
8710                        } else {
8711                            packageFile = null;
8712                        }
8713                    } else {
8714                        packageFile = new File(mPackageURI.getPath());
8715                    }
8716
8717                    if (packageFile != null) {
8718                        // Remote call to find out default install location
8719                        final String packageFilePath = packageFile.getAbsolutePath();
8720                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8721                                lowThreshold, packageAbiOverride);
8722
8723                        /*
8724                         * If we have too little free space, try to free cache
8725                         * before giving up.
8726                         */
8727                        if (pkgLite.recommendedInstallLocation
8728                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8729                            final long size = mContainerService.calculateInstalledSize(
8730                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8731                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8732                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8733                                        flags, lowThreshold, packageAbiOverride);
8734                            }
8735                            /*
8736                             * The cache free must have deleted the file we
8737                             * downloaded to install.
8738                             *
8739                             * TODO: fix the "freeCache" call to not delete
8740                             *       the file we care about.
8741                             */
8742                            if (pkgLite.recommendedInstallLocation
8743                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8744                                pkgLite.recommendedInstallLocation
8745                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8746                            }
8747                        }
8748                    }
8749                } finally {
8750                    mContext.revokeUriPermission(mPackageURI,
8751                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8752                }
8753            }
8754
8755            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8756                int loc = pkgLite.recommendedInstallLocation;
8757                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8758                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8759                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8760                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8761                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8762                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8763                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8764                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8765                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8766                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8767                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8768                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8769                } else {
8770                    // Override with defaults if needed.
8771                    loc = installLocationPolicy(pkgLite, flags);
8772                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8773                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8774                    } else if (!onSd && !onInt) {
8775                        // Override install location with flags
8776                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8777                            // Set the flag to install on external media.
8778                            flags |= PackageManager.INSTALL_EXTERNAL;
8779                            flags &= ~PackageManager.INSTALL_INTERNAL;
8780                        } else {
8781                            // Make sure the flag for installing on external
8782                            // media is unset
8783                            flags |= PackageManager.INSTALL_INTERNAL;
8784                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8785                        }
8786                    }
8787                }
8788            }
8789
8790            final InstallArgs args = createInstallArgs(this);
8791            mArgs = args;
8792
8793            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8794                 /*
8795                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8796                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8797                 */
8798                int userIdentifier = getUser().getIdentifier();
8799                if (userIdentifier == UserHandle.USER_ALL
8800                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8801                    userIdentifier = UserHandle.USER_OWNER;
8802                }
8803
8804                /*
8805                 * Determine if we have any installed package verifiers. If we
8806                 * do, then we'll defer to them to verify the packages.
8807                 */
8808                final int requiredUid = mRequiredVerifierPackage == null ? -1
8809                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8810                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8811                    final Intent verification = new Intent(
8812                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8813                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8814                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8815
8816                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8817                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8818                            0 /* TODO: Which userId? */);
8819
8820                    if (DEBUG_VERIFY) {
8821                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8822                                + verification.toString() + " with " + pkgLite.verifiers.length
8823                                + " optional verifiers");
8824                    }
8825
8826                    final int verificationId = mPendingVerificationToken++;
8827
8828                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8829
8830                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8831                            installerPackageName);
8832
8833                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8834
8835                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8836                            pkgLite.packageName);
8837
8838                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8839                            pkgLite.versionCode);
8840
8841                    if (verificationParams != null) {
8842                        if (verificationParams.getVerificationURI() != null) {
8843                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8844                                 verificationParams.getVerificationURI());
8845                        }
8846                        if (verificationParams.getOriginatingURI() != null) {
8847                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8848                                  verificationParams.getOriginatingURI());
8849                        }
8850                        if (verificationParams.getReferrer() != null) {
8851                            verification.putExtra(Intent.EXTRA_REFERRER,
8852                                  verificationParams.getReferrer());
8853                        }
8854                        if (verificationParams.getOriginatingUid() >= 0) {
8855                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8856                                  verificationParams.getOriginatingUid());
8857                        }
8858                        if (verificationParams.getInstallerUid() >= 0) {
8859                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8860                                  verificationParams.getInstallerUid());
8861                        }
8862                    }
8863
8864                    final PackageVerificationState verificationState = new PackageVerificationState(
8865                            requiredUid, args);
8866
8867                    mPendingVerification.append(verificationId, verificationState);
8868
8869                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8870                            receivers, verificationState);
8871
8872                    /*
8873                     * If any sufficient verifiers were listed in the package
8874                     * manifest, attempt to ask them.
8875                     */
8876                    if (sufficientVerifiers != null) {
8877                        final int N = sufficientVerifiers.size();
8878                        if (N == 0) {
8879                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8880                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8881                        } else {
8882                            for (int i = 0; i < N; i++) {
8883                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8884
8885                                final Intent sufficientIntent = new Intent(verification);
8886                                sufficientIntent.setComponent(verifierComponent);
8887
8888                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8889                            }
8890                        }
8891                    }
8892
8893                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8894                            mRequiredVerifierPackage, receivers);
8895                    if (ret == PackageManager.INSTALL_SUCCEEDED
8896                            && mRequiredVerifierPackage != null) {
8897                        /*
8898                         * Send the intent to the required verification agent,
8899                         * but only start the verification timeout after the
8900                         * target BroadcastReceivers have run.
8901                         */
8902                        verification.setComponent(requiredVerifierComponent);
8903                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8904                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8905                                new BroadcastReceiver() {
8906                                    @Override
8907                                    public void onReceive(Context context, Intent intent) {
8908                                        final Message msg = mHandler
8909                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8910                                        msg.arg1 = verificationId;
8911                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8912                                    }
8913                                }, null, 0, null, null);
8914
8915                        /*
8916                         * We don't want the copy to proceed until verification
8917                         * succeeds, so null out this field.
8918                         */
8919                        mArgs = null;
8920                    }
8921                } else {
8922                    /*
8923                     * No package verification is enabled, so immediately start
8924                     * the remote call to initiate copy using temporary file.
8925                     */
8926                    ret = args.copyApk(mContainerService, true);
8927                }
8928            }
8929
8930            mRet = ret;
8931        }
8932
8933        @Override
8934        void handleReturnCode() {
8935            // If mArgs is null, then MCS couldn't be reached. When it
8936            // reconnects, it will try again to install. At that point, this
8937            // will succeed.
8938            if (mArgs != null) {
8939                processPendingInstall(mArgs, mRet);
8940
8941                if (mTempPackage != null) {
8942                    if (!mTempPackage.delete()) {
8943                        Slog.w(TAG, "Couldn't delete temporary file: " +
8944                                mTempPackage.getAbsolutePath());
8945                    }
8946                }
8947            }
8948        }
8949
8950        @Override
8951        void handleServiceError() {
8952            mArgs = createInstallArgs(this);
8953            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8954        }
8955
8956        public boolean isForwardLocked() {
8957            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8958        }
8959
8960        public Uri getPackageUri() {
8961            if (mTempPackage != null) {
8962                return Uri.fromFile(mTempPackage);
8963            } else {
8964                return mPackageURI;
8965            }
8966        }
8967    }
8968
8969    /*
8970     * Utility class used in movePackage api.
8971     * srcArgs and targetArgs are not set for invalid flags and make
8972     * sure to do null checks when invoking methods on them.
8973     * We probably want to return ErrorPrams for both failed installs
8974     * and moves.
8975     */
8976    class MoveParams extends HandlerParams {
8977        final IPackageMoveObserver observer;
8978        final int flags;
8979        final String packageName;
8980        final InstallArgs srcArgs;
8981        final InstallArgs targetArgs;
8982        int uid;
8983        int mRet;
8984
8985        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8986                String packageName, String dataDir, String instructionSet,
8987                int uid, UserHandle user) {
8988            super(user);
8989            this.srcArgs = srcArgs;
8990            this.observer = observer;
8991            this.flags = flags;
8992            this.packageName = packageName;
8993            this.uid = uid;
8994            if (srcArgs != null) {
8995                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8996                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8997            } else {
8998                targetArgs = null;
8999            }
9000        }
9001
9002        @Override
9003        public String toString() {
9004            return "MoveParams{"
9005                + Integer.toHexString(System.identityHashCode(this))
9006                + " " + packageName + "}";
9007        }
9008
9009        public void handleStartCopy() throws RemoteException {
9010            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9011            // Check for storage space on target medium
9012            if (!targetArgs.checkFreeStorage(mContainerService)) {
9013                Log.w(TAG, "Insufficient storage to install");
9014                return;
9015            }
9016
9017            mRet = srcArgs.doPreCopy();
9018            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9019                return;
9020            }
9021
9022            mRet = targetArgs.copyApk(mContainerService, false);
9023            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9024                srcArgs.doPostCopy(uid);
9025                return;
9026            }
9027
9028            mRet = srcArgs.doPostCopy(uid);
9029            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9030                return;
9031            }
9032
9033            mRet = targetArgs.doPreInstall(mRet);
9034            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9035                return;
9036            }
9037
9038            if (DEBUG_SD_INSTALL) {
9039                StringBuilder builder = new StringBuilder();
9040                if (srcArgs != null) {
9041                    builder.append("src: ");
9042                    builder.append(srcArgs.getCodePath());
9043                }
9044                if (targetArgs != null) {
9045                    builder.append(" target : ");
9046                    builder.append(targetArgs.getCodePath());
9047                }
9048                Log.i(TAG, builder.toString());
9049            }
9050        }
9051
9052        @Override
9053        void handleReturnCode() {
9054            targetArgs.doPostInstall(mRet, uid);
9055            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9056            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9057                currentStatus = PackageManager.MOVE_SUCCEEDED;
9058            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9059                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9060            }
9061            processPendingMove(this, currentStatus);
9062        }
9063
9064        @Override
9065        void handleServiceError() {
9066            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9067        }
9068    }
9069
9070    /**
9071     * Used during creation of InstallArgs
9072     *
9073     * @param flags package installation flags
9074     * @return true if should be installed on external storage
9075     */
9076    private static boolean installOnSd(int flags) {
9077        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9078            return false;
9079        }
9080        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9081            return true;
9082        }
9083        return false;
9084    }
9085
9086    /**
9087     * Used during creation of InstallArgs
9088     *
9089     * @param flags package installation flags
9090     * @return true if should be installed as forward locked
9091     */
9092    private static boolean installForwardLocked(int flags) {
9093        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9094    }
9095
9096    private InstallArgs createInstallArgs(InstallParams params) {
9097        if (installOnSd(params.flags) || params.isForwardLocked()) {
9098            return new AsecInstallArgs(params);
9099        } else {
9100            return new FileInstallArgs(params);
9101        }
9102    }
9103
9104    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
9105            String nativeLibraryPath, String instructionSet) {
9106        final boolean isInAsec;
9107        if (installOnSd(flags)) {
9108            /* Apps on SD card are always in ASEC containers. */
9109            isInAsec = true;
9110        } else if (installForwardLocked(flags)
9111                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9112            /*
9113             * Forward-locked apps are only in ASEC containers if they're the
9114             * new style
9115             */
9116            isInAsec = true;
9117        } else {
9118            isInAsec = false;
9119        }
9120
9121        if (isInAsec) {
9122            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9123                    instructionSet, installOnSd(flags), installForwardLocked(flags));
9124        } else {
9125            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9126                    instructionSet);
9127        }
9128    }
9129
9130    // Used by package mover
9131    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
9132            String instructionSet) {
9133        if (installOnSd(flags) || installForwardLocked(flags)) {
9134            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
9135                    + AsecInstallArgs.RES_FILE_NAME);
9136            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
9137                    installForwardLocked(flags));
9138        } else {
9139            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
9140        }
9141    }
9142
9143    static abstract class InstallArgs {
9144        final IPackageInstallObserver observer;
9145        final IPackageInstallObserver2 observer2;
9146        // Always refers to PackageManager flags only
9147        final int flags;
9148        final Uri packageURI;
9149        final String installerPackageName;
9150        final ManifestDigest manifestDigest;
9151        final UserHandle user;
9152        final String instructionSet;
9153        final String abiOverride;
9154
9155        InstallArgs(Uri packageURI,
9156                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
9157                int flags, String installerPackageName, ManifestDigest manifestDigest,
9158                UserHandle user, String instructionSet, String abiOverride) {
9159            this.packageURI = packageURI;
9160            this.flags = flags;
9161            this.observer = observer;
9162            this.observer2 = observer2;
9163            this.installerPackageName = installerPackageName;
9164            this.manifestDigest = manifestDigest;
9165            this.user = user;
9166            this.instructionSet = instructionSet;
9167            this.abiOverride = abiOverride;
9168        }
9169
9170        abstract void createCopyFile();
9171        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9172        abstract int doPreInstall(int status);
9173        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9174
9175        abstract int doPostInstall(int status, int uid);
9176        abstract String getCodePath();
9177        abstract String getResourcePath();
9178        abstract String getNativeLibraryPath();
9179        // Need installer lock especially for dex file removal.
9180        abstract void cleanUpResourcesLI();
9181        abstract boolean doPostDeleteLI(boolean delete);
9182        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9183
9184        String[] getSplitCodePaths() {
9185            return null;
9186        }
9187
9188        /**
9189         * Called before the source arguments are copied. This is used mostly
9190         * for MoveParams when it needs to read the source file to put it in the
9191         * destination.
9192         */
9193        int doPreCopy() {
9194            return PackageManager.INSTALL_SUCCEEDED;
9195        }
9196
9197        /**
9198         * Called after the source arguments are copied. This is used mostly for
9199         * MoveParams when it needs to read the source file to put it in the
9200         * destination.
9201         *
9202         * @return
9203         */
9204        int doPostCopy(int uid) {
9205            return PackageManager.INSTALL_SUCCEEDED;
9206        }
9207
9208        protected boolean isFwdLocked() {
9209            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9210        }
9211
9212        UserHandle getUser() {
9213            return user;
9214        }
9215    }
9216
9217    class FileInstallArgs extends InstallArgs {
9218        File installDir;
9219        String codeFileName;
9220        String resourceFileName;
9221        String libraryPath;
9222        boolean created = false;
9223
9224        FileInstallArgs(InstallParams params) {
9225            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9226                    params.installerPackageName, params.getManifestDigest(),
9227                    params.getUser(), params.packageInstructionSetOverride,
9228                    params.packageAbiOverride);
9229        }
9230
9231        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9232                String instructionSet) {
9233            super(null, null, null, 0, null, null, null, instructionSet, null);
9234            File codeFile = new File(fullCodePath);
9235            installDir = codeFile.getParentFile();
9236            codeFileName = fullCodePath;
9237            resourceFileName = fullResourcePath;
9238            libraryPath = nativeLibraryPath;
9239        }
9240
9241        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9242            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9243            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9244            String apkName = getNextCodePath(null, pkgName, ".apk");
9245            codeFileName = new File(installDir, apkName + ".apk").getPath();
9246            resourceFileName = getResourcePathFromCodePath();
9247            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9248        }
9249
9250        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9251            final long lowThreshold;
9252
9253            final DeviceStorageMonitorInternal
9254                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9255            if (dsm == null) {
9256                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9257                lowThreshold = 0L;
9258            } else {
9259                if (dsm.isMemoryLow()) {
9260                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9261                    return false;
9262                }
9263
9264                lowThreshold = dsm.getMemoryLowThreshold();
9265            }
9266
9267            try {
9268                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9269                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9270                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9271            } finally {
9272                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9273            }
9274        }
9275
9276        void createCopyFile() {
9277            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9278            codeFileName = createTempPackageFile(installDir).getPath();
9279            resourceFileName = getResourcePathFromCodePath();
9280            libraryPath = getLibraryPathFromCodePath();
9281            created = true;
9282        }
9283
9284        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9285            if (temp) {
9286                // Generate temp file name
9287                createCopyFile();
9288            }
9289            // Get a ParcelFileDescriptor to write to the output file
9290            File codeFile = new File(codeFileName);
9291            if (!created) {
9292                try {
9293                    codeFile.createNewFile();
9294                    // Set permissions
9295                    if (!setPermissions()) {
9296                        // Failed setting permissions.
9297                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9298                    }
9299                } catch (IOException e) {
9300                   Slog.w(TAG, "Failed to create file " + codeFile);
9301                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9302                }
9303            }
9304            ParcelFileDescriptor out = null;
9305            try {
9306                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9307            } catch (FileNotFoundException e) {
9308                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9309                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9310            }
9311            // Copy the resource now
9312            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9313            try {
9314                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9315                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9316                ret = imcs.copyResource(packageURI, null, out);
9317            } finally {
9318                IoUtils.closeQuietly(out);
9319                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9320            }
9321
9322            if (isFwdLocked()) {
9323                final File destResourceFile = new File(getResourcePath());
9324
9325                // Copy the public files
9326                try {
9327                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9328                } catch (IOException e) {
9329                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9330                            + " forward-locked app.");
9331                    destResourceFile.delete();
9332                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9333                }
9334            }
9335
9336            final File nativeLibraryFile = new File(getNativeLibraryPath());
9337            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9338            if (nativeLibraryFile.exists()) {
9339                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9340                nativeLibraryFile.delete();
9341            }
9342
9343            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9344            String[] abiList = (abiOverride != null) ?
9345                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9346            try {
9347                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9348                        abiOverride == null &&
9349                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9350                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9351                }
9352
9353                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9354                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9355                    return copyRet;
9356                }
9357            } catch (IOException e) {
9358                Slog.e(TAG, "Copying native libraries failed", e);
9359                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9360            } finally {
9361                handle.close();
9362            }
9363
9364            return ret;
9365        }
9366
9367        int doPreInstall(int status) {
9368            if (status != PackageManager.INSTALL_SUCCEEDED) {
9369                cleanUp();
9370            }
9371            return status;
9372        }
9373
9374        boolean doRename(int status, final String pkgName, String oldCodePath) {
9375            if (status != PackageManager.INSTALL_SUCCEEDED) {
9376                cleanUp();
9377                return false;
9378            } else {
9379                final File oldCodeFile = new File(getCodePath());
9380                final File oldResourceFile = new File(getResourcePath());
9381                final File oldLibraryFile = new File(getNativeLibraryPath());
9382
9383                // Rename APK file based on packageName
9384                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9385                final File newCodeFile = new File(installDir, apkName + ".apk");
9386                if (!oldCodeFile.renameTo(newCodeFile)) {
9387                    return false;
9388                }
9389                codeFileName = newCodeFile.getPath();
9390
9391                // Rename public resource file if it's forward-locked.
9392                final File newResFile = new File(getResourcePathFromCodePath());
9393                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9394                    return false;
9395                }
9396                resourceFileName = newResFile.getPath();
9397
9398                // Rename library path
9399                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9400                if (newLibraryFile.exists()) {
9401                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9402                    newLibraryFile.delete();
9403                }
9404                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9405                    Slog.e(TAG, "Cannot rename native library directory "
9406                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9407                    return false;
9408                }
9409                libraryPath = newLibraryFile.getPath();
9410
9411                // Attempt to set permissions
9412                if (!setPermissions()) {
9413                    return false;
9414                }
9415
9416                if (!SELinux.restorecon(newCodeFile)) {
9417                    return false;
9418                }
9419
9420                return true;
9421            }
9422        }
9423
9424        int doPostInstall(int status, int uid) {
9425            if (status != PackageManager.INSTALL_SUCCEEDED) {
9426                cleanUp();
9427            }
9428            return status;
9429        }
9430
9431        private String getResourcePathFromCodePath() {
9432            final String codePath = getCodePath();
9433            if (isFwdLocked()) {
9434                final StringBuilder sb = new StringBuilder();
9435
9436                sb.append(mAppInstallDir.getPath());
9437                sb.append('/');
9438                sb.append(getApkName(codePath));
9439                sb.append(".zip");
9440
9441                /*
9442                 * If our APK is a temporary file, mark the resource as a
9443                 * temporary file as well so it can be cleaned up after
9444                 * catastrophic failure.
9445                 */
9446                if (codePath.endsWith(".tmp")) {
9447                    sb.append(".tmp");
9448                }
9449
9450                return sb.toString();
9451            } else {
9452                return codePath;
9453            }
9454        }
9455
9456        private String getLibraryPathFromCodePath() {
9457            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9458        }
9459
9460        @Override
9461        String getCodePath() {
9462            return codeFileName;
9463        }
9464
9465        @Override
9466        String getResourcePath() {
9467            return resourceFileName;
9468        }
9469
9470        @Override
9471        String getNativeLibraryPath() {
9472            if (libraryPath == null) {
9473                libraryPath = getLibraryPathFromCodePath();
9474            }
9475            return libraryPath;
9476        }
9477
9478        private boolean cleanUp() {
9479            boolean ret = true;
9480            String sourceDir = getCodePath();
9481            String publicSourceDir = getResourcePath();
9482            if (sourceDir != null) {
9483                File sourceFile = new File(sourceDir);
9484                if (!sourceFile.exists()) {
9485                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9486                    ret = false;
9487                }
9488                // Delete application's code and resources
9489                sourceFile.delete();
9490            }
9491            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9492                final File publicSourceFile = new File(publicSourceDir);
9493                if (!publicSourceFile.exists()) {
9494                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9495                }
9496                if (publicSourceFile.exists()) {
9497                    publicSourceFile.delete();
9498                }
9499            }
9500
9501            if (libraryPath != null) {
9502                File nativeLibraryFile = new File(libraryPath);
9503                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9504                if (!nativeLibraryFile.delete()) {
9505                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9506                }
9507            }
9508
9509            return ret;
9510        }
9511
9512        void cleanUpResourcesLI() {
9513            String sourceDir = getCodePath();
9514            if (cleanUp()) {
9515                if (instructionSet == null) {
9516                    throw new IllegalStateException("instructionSet == null");
9517                }
9518                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9519                if (retCode < 0) {
9520                    Slog.w(TAG, "Couldn't remove dex file for package: "
9521                            +  " at location "
9522                            + sourceDir + ", retcode=" + retCode);
9523                    // we don't consider this to be a failure of the core package deletion
9524                }
9525            }
9526        }
9527
9528        private boolean setPermissions() {
9529            // TODO Do this in a more elegant way later on. for now just a hack
9530            if (!isFwdLocked()) {
9531                final int filePermissions =
9532                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9533                    |FileUtils.S_IROTH;
9534                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9535                if (retCode != 0) {
9536                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9537                            getCodePath()
9538                            + ". The return code was: " + retCode);
9539                    // TODO Define new internal error
9540                    return false;
9541                }
9542                return true;
9543            }
9544            return true;
9545        }
9546
9547        boolean doPostDeleteLI(boolean delete) {
9548            // XXX err, shouldn't we respect the delete flag?
9549            cleanUpResourcesLI();
9550            return true;
9551        }
9552    }
9553
9554    private boolean isAsecExternal(String cid) {
9555        final String asecPath = PackageHelper.getSdFilesystem(cid);
9556        return !asecPath.startsWith(mAsecInternalPath);
9557    }
9558
9559    /**
9560     * Extract the MountService "container ID" from the full code path of an
9561     * .apk.
9562     */
9563    static String cidFromCodePath(String fullCodePath) {
9564        int eidx = fullCodePath.lastIndexOf("/");
9565        String subStr1 = fullCodePath.substring(0, eidx);
9566        int sidx = subStr1.lastIndexOf("/");
9567        return subStr1.substring(sidx+1, eidx);
9568    }
9569
9570    class AsecInstallArgs extends InstallArgs {
9571        static final String RES_FILE_NAME = "pkg.apk";
9572        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9573
9574        String cid;
9575        String packagePath;
9576        String resourcePath;
9577        String libraryPath;
9578
9579        AsecInstallArgs(InstallParams params) {
9580            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9581                    params.installerPackageName, params.getManifestDigest(),
9582                    params.getUser(), params.packageInstructionSetOverride,
9583                    params.packageAbiOverride);
9584        }
9585
9586        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9587                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9588            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9589                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9590                    null, null, null, instructionSet, null);
9591            // Extract cid from fullCodePath
9592            int eidx = fullCodePath.lastIndexOf("/");
9593            String subStr1 = fullCodePath.substring(0, eidx);
9594            int sidx = subStr1.lastIndexOf("/");
9595            cid = subStr1.substring(sidx+1, eidx);
9596            setCachePath(subStr1);
9597        }
9598
9599        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9600            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9601                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9602                    null, null, null, instructionSet, null);
9603            this.cid = cid;
9604            setCachePath(PackageHelper.getSdDir(cid));
9605        }
9606
9607        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9608                boolean isExternal, boolean isForwardLocked) {
9609            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9610                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9611                    null, null, null, instructionSet, null);
9612            this.cid = cid;
9613        }
9614
9615        void createCopyFile() {
9616            cid = getTempContainerId();
9617        }
9618
9619        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9620            try {
9621                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9622                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9623                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9624            } finally {
9625                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9626            }
9627        }
9628
9629        private final boolean isExternal() {
9630            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9631        }
9632
9633        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9634            if (temp) {
9635                createCopyFile();
9636            } else {
9637                /*
9638                 * Pre-emptively destroy the container since it's destroyed if
9639                 * copying fails due to it existing anyway.
9640                 */
9641                PackageHelper.destroySdDir(cid);
9642            }
9643
9644            final String newCachePath;
9645            try {
9646                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9647                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9648                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9649                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9650                        abiOverride);
9651            } finally {
9652                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9653            }
9654
9655            if (newCachePath != null) {
9656                setCachePath(newCachePath);
9657                return PackageManager.INSTALL_SUCCEEDED;
9658            } else {
9659                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9660            }
9661        }
9662
9663        @Override
9664        String getCodePath() {
9665            return packagePath;
9666        }
9667
9668        @Override
9669        String getResourcePath() {
9670            return resourcePath;
9671        }
9672
9673        @Override
9674        String getNativeLibraryPath() {
9675            return libraryPath;
9676        }
9677
9678        int doPreInstall(int status) {
9679            if (status != PackageManager.INSTALL_SUCCEEDED) {
9680                // Destroy container
9681                PackageHelper.destroySdDir(cid);
9682            } else {
9683                boolean mounted = PackageHelper.isContainerMounted(cid);
9684                if (!mounted) {
9685                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9686                            Process.SYSTEM_UID);
9687                    if (newCachePath != null) {
9688                        setCachePath(newCachePath);
9689                    } else {
9690                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9691                    }
9692                }
9693            }
9694            return status;
9695        }
9696
9697        boolean doRename(int status, final String pkgName,
9698                String oldCodePath) {
9699            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9700            String newCachePath = null;
9701            if (PackageHelper.isContainerMounted(cid)) {
9702                // Unmount the container
9703                if (!PackageHelper.unMountSdDir(cid)) {
9704                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9705                    return false;
9706                }
9707            }
9708            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9709                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9710                        " which might be stale. Will try to clean up.");
9711                // Clean up the stale container and proceed to recreate.
9712                if (!PackageHelper.destroySdDir(newCacheId)) {
9713                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9714                    return false;
9715                }
9716                // Successfully cleaned up stale container. Try to rename again.
9717                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9718                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9719                            + " inspite of cleaning it up.");
9720                    return false;
9721                }
9722            }
9723            if (!PackageHelper.isContainerMounted(newCacheId)) {
9724                Slog.w(TAG, "Mounting container " + newCacheId);
9725                newCachePath = PackageHelper.mountSdDir(newCacheId,
9726                        getEncryptKey(), Process.SYSTEM_UID);
9727            } else {
9728                newCachePath = PackageHelper.getSdDir(newCacheId);
9729            }
9730            if (newCachePath == null) {
9731                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9732                return false;
9733            }
9734            Log.i(TAG, "Succesfully renamed " + cid +
9735                    " to " + newCacheId +
9736                    " at new path: " + newCachePath);
9737            cid = newCacheId;
9738            setCachePath(newCachePath);
9739            return true;
9740        }
9741
9742        private void setCachePath(String newCachePath) {
9743            File cachePath = new File(newCachePath);
9744            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9745            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9746
9747            if (isFwdLocked()) {
9748                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9749            } else {
9750                resourcePath = packagePath;
9751            }
9752        }
9753
9754        int doPostInstall(int status, int uid) {
9755            if (status != PackageManager.INSTALL_SUCCEEDED) {
9756                cleanUp();
9757            } else {
9758                final int groupOwner;
9759                final String protectedFile;
9760                if (isFwdLocked()) {
9761                    groupOwner = UserHandle.getSharedAppGid(uid);
9762                    protectedFile = RES_FILE_NAME;
9763                } else {
9764                    groupOwner = -1;
9765                    protectedFile = null;
9766                }
9767
9768                if (uid < Process.FIRST_APPLICATION_UID
9769                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9770                    Slog.e(TAG, "Failed to finalize " + cid);
9771                    PackageHelper.destroySdDir(cid);
9772                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9773                }
9774
9775                boolean mounted = PackageHelper.isContainerMounted(cid);
9776                if (!mounted) {
9777                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9778                }
9779            }
9780            return status;
9781        }
9782
9783        private void cleanUp() {
9784            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9785
9786            // Destroy secure container
9787            PackageHelper.destroySdDir(cid);
9788        }
9789
9790        void cleanUpResourcesLI() {
9791            String sourceFile = getCodePath();
9792            // Remove dex file
9793            if (instructionSet == null) {
9794                throw new IllegalStateException("instructionSet == null");
9795            }
9796            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9797            if (retCode < 0) {
9798                Slog.w(TAG, "Couldn't remove dex file for package: "
9799                        + " at location "
9800                        + sourceFile.toString() + ", retcode=" + retCode);
9801                // we don't consider this to be a failure of the core package deletion
9802            }
9803            cleanUp();
9804        }
9805
9806        boolean matchContainer(String app) {
9807            if (cid.startsWith(app)) {
9808                return true;
9809            }
9810            return false;
9811        }
9812
9813        String getPackageName() {
9814            return getAsecPackageName(cid);
9815        }
9816
9817        boolean doPostDeleteLI(boolean delete) {
9818            boolean ret = false;
9819            boolean mounted = PackageHelper.isContainerMounted(cid);
9820            if (mounted) {
9821                // Unmount first
9822                ret = PackageHelper.unMountSdDir(cid);
9823            }
9824            if (ret && delete) {
9825                cleanUpResourcesLI();
9826            }
9827            return ret;
9828        }
9829
9830        @Override
9831        int doPreCopy() {
9832            if (isFwdLocked()) {
9833                if (!PackageHelper.fixSdPermissions(cid,
9834                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9835                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9836                }
9837            }
9838
9839            return PackageManager.INSTALL_SUCCEEDED;
9840        }
9841
9842        @Override
9843        int doPostCopy(int uid) {
9844            if (isFwdLocked()) {
9845                if (uid < Process.FIRST_APPLICATION_UID
9846                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9847                                RES_FILE_NAME)) {
9848                    Slog.e(TAG, "Failed to finalize " + cid);
9849                    PackageHelper.destroySdDir(cid);
9850                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9851                }
9852            }
9853
9854            return PackageManager.INSTALL_SUCCEEDED;
9855        }
9856    }
9857
9858    static String getAsecPackageName(String packageCid) {
9859        int idx = packageCid.lastIndexOf("-");
9860        if (idx == -1) {
9861            return packageCid;
9862        }
9863        return packageCid.substring(0, idx);
9864    }
9865
9866    // Utility method used to create code paths based on package name and available index.
9867    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9868        String idxStr = "";
9869        int idx = 1;
9870        // Fall back to default value of idx=1 if prefix is not
9871        // part of oldCodePath
9872        if (oldCodePath != null) {
9873            String subStr = oldCodePath;
9874            // Drop the suffix right away
9875            if (subStr.endsWith(suffix)) {
9876                subStr = subStr.substring(0, subStr.length() - suffix.length());
9877            }
9878            // If oldCodePath already contains prefix find out the
9879            // ending index to either increment or decrement.
9880            int sidx = subStr.lastIndexOf(prefix);
9881            if (sidx != -1) {
9882                subStr = subStr.substring(sidx + prefix.length());
9883                if (subStr != null) {
9884                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9885                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9886                    }
9887                    try {
9888                        idx = Integer.parseInt(subStr);
9889                        if (idx <= 1) {
9890                            idx++;
9891                        } else {
9892                            idx--;
9893                        }
9894                    } catch(NumberFormatException e) {
9895                    }
9896                }
9897            }
9898        }
9899        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9900        return prefix + idxStr;
9901    }
9902
9903    // Utility method used to ignore ADD/REMOVE events
9904    // by directory observer.
9905    private static boolean ignoreCodePath(String fullPathStr) {
9906        String apkName = getApkName(fullPathStr);
9907        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9908        if (idx != -1 && ((idx+1) < apkName.length())) {
9909            // Make sure the package ends with a numeral
9910            String version = apkName.substring(idx+1);
9911            try {
9912                Integer.parseInt(version);
9913                return true;
9914            } catch (NumberFormatException e) {}
9915        }
9916        return false;
9917    }
9918
9919    // Utility method that returns the relative package path with respect
9920    // to the installation directory. Like say for /data/data/com.test-1.apk
9921    // string com.test-1 is returned.
9922    static String getApkName(String codePath) {
9923        if (codePath == null) {
9924            return null;
9925        }
9926        int sidx = codePath.lastIndexOf("/");
9927        int eidx = codePath.lastIndexOf(".");
9928        if (eidx == -1) {
9929            eidx = codePath.length();
9930        } else if (eidx == 0) {
9931            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9932            return null;
9933        }
9934        return codePath.substring(sidx+1, eidx);
9935    }
9936
9937    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9938        String[] splitResPaths = null;
9939        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9940            splitResPaths = new String[splitCodePaths.length];
9941            for (int i = 0; i < splitCodePaths.length; i++) {
9942                final String splitCodePath = splitCodePaths[i];
9943                final String resName = getApkName(splitCodePath) + ".zip";
9944                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9945                        resName).getAbsolutePath();
9946            }
9947        }
9948        return splitResPaths;
9949    }
9950
9951    class PackageInstalledInfo {
9952        String name;
9953        int uid;
9954        // The set of users that originally had this package installed.
9955        int[] origUsers;
9956        // The set of users that now have this package installed.
9957        int[] newUsers;
9958        PackageParser.Package pkg;
9959        int returnCode;
9960        PackageRemovedInfo removedInfo;
9961
9962        // In some error cases we want to convey more info back to the observer
9963        String origPackage;
9964        String origPermission;
9965    }
9966
9967    /*
9968     * Install a non-existing package.
9969     */
9970    private void installNewPackageLI(PackageParser.Package pkg,
9971            int parseFlags, int scanMode, UserHandle user,
9972            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9973        // Remember this for later, in case we need to rollback this install
9974        String pkgName = pkg.packageName;
9975
9976        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9977        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9978        synchronized(mPackages) {
9979            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9980                // A package with the same name is already installed, though
9981                // it has been renamed to an older name.  The package we
9982                // are trying to install should be installed as an update to
9983                // the existing one, but that has not been requested, so bail.
9984                Slog.w(TAG, "Attempt to re-install " + pkgName
9985                        + " without first uninstalling package running as "
9986                        + mSettings.mRenamedPackages.get(pkgName));
9987                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9988                return;
9989            }
9990            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9991                // Don't allow installation over an existing package with the same name.
9992                Slog.w(TAG, "Attempt to re-install " + pkgName
9993                        + " without first uninstalling.");
9994                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9995                return;
9996            }
9997        }
9998        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9999        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
10000                System.currentTimeMillis(), user, abiOverride);
10001        if (newPackage == null) {
10002            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10003            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10004                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10005            }
10006        } else {
10007            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10008            // delete the partially installed application. the data directory will have to be
10009            // restored if it was already existing
10010            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10011                // remove package from internal structures.  Note that we want deletePackageX to
10012                // delete the package data and cache directories that it created in
10013                // scanPackageLocked, unless those directories existed before we even tried to
10014                // install.
10015                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10016                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10017                                res.removedInfo, true);
10018            }
10019        }
10020    }
10021
10022    private void replacePackageLI(PackageParser.Package pkg,
10023            int parseFlags, int scanMode, UserHandle user,
10024            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10025
10026        PackageParser.Package oldPackage;
10027        String pkgName = pkg.packageName;
10028        int[] allUsers;
10029        boolean[] perUserInstalled;
10030
10031        // First find the old package info and check signatures
10032        synchronized(mPackages) {
10033            oldPackage = mPackages.get(pkgName);
10034            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10035            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10036                    != PackageManager.SIGNATURE_MATCH) {
10037                Slog.w(TAG, "New package has a different signature: " + pkgName);
10038                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
10039                return;
10040            }
10041
10042            // In case of rollback, remember per-user/profile install state
10043            PackageSetting ps = mSettings.mPackages.get(pkgName);
10044            allUsers = sUserManager.getUserIds();
10045            perUserInstalled = new boolean[allUsers.length];
10046            for (int i = 0; i < allUsers.length; i++) {
10047                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10048            }
10049        }
10050        boolean sysPkg = (isSystemApp(oldPackage));
10051        if (sysPkg) {
10052            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10053                    user, allUsers, perUserInstalled, installerPackageName, res,
10054                    abiOverride);
10055        } else {
10056            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10057                    user, allUsers, perUserInstalled, installerPackageName, res,
10058                    abiOverride);
10059        }
10060    }
10061
10062    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10063            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10064            int[] allUsers, boolean[] perUserInstalled,
10065            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10066        PackageParser.Package newPackage = null;
10067        String pkgName = deletedPackage.packageName;
10068        boolean deletedPkg = true;
10069        boolean updatedSettings = false;
10070
10071        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10072                + deletedPackage);
10073        long origUpdateTime;
10074        if (pkg.mExtras != null) {
10075            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10076        } else {
10077            origUpdateTime = 0;
10078        }
10079
10080        // First delete the existing package while retaining the data directory
10081        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10082                res.removedInfo, true)) {
10083            // If the existing package wasn't successfully deleted
10084            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10085            deletedPkg = false;
10086        } else {
10087            // Successfully deleted the old package. Now proceed with re-installation
10088            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10089            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
10090                    System.currentTimeMillis(), user, abiOverride);
10091            if (newPackage == null) {
10092                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10093                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10094                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10095                }
10096            } else {
10097                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10098                updatedSettings = true;
10099            }
10100        }
10101
10102        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10103            // remove package from internal structures.  Note that we want deletePackageX to
10104            // delete the package data and cache directories that it created in
10105            // scanPackageLocked, unless those directories existed before we even tried to
10106            // install.
10107            if(updatedSettings) {
10108                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10109                deletePackageLI(
10110                        pkgName, null, true, allUsers, perUserInstalled,
10111                        PackageManager.DELETE_KEEP_DATA,
10112                                res.removedInfo, true);
10113            }
10114            // Since we failed to install the new package we need to restore the old
10115            // package that we deleted.
10116            if (deletedPkg) {
10117                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10118                File restoreFile = new File(deletedPackage.codePath);
10119                // Parse old package
10120                boolean oldOnSd = isExternal(deletedPackage);
10121                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10122                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10123                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10124                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10125                        | SCAN_UPDATE_TIME;
10126                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
10127                        origUpdateTime, null, null) == null) {
10128                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
10129                    return;
10130                }
10131                // Restore of old package succeeded. Update permissions.
10132                // writer
10133                synchronized (mPackages) {
10134                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10135                            UPDATE_PERMISSIONS_ALL);
10136                    // can downgrade to reader
10137                    mSettings.writeLPr();
10138                }
10139                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10140            }
10141        }
10142    }
10143
10144    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10145            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10146            int[] allUsers, boolean[] perUserInstalled,
10147            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10148        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10149                + ", old=" + deletedPackage);
10150        PackageParser.Package newPackage = null;
10151        boolean updatedSettings = false;
10152        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10153                PackageParser.PARSE_IS_SYSTEM;
10154        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10155            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10156        }
10157        String packageName = deletedPackage.packageName;
10158        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10159        if (packageName == null) {
10160            Slog.w(TAG, "Attempt to delete null packageName.");
10161            return;
10162        }
10163        PackageParser.Package oldPkg;
10164        PackageSetting oldPkgSetting;
10165        // reader
10166        synchronized (mPackages) {
10167            oldPkg = mPackages.get(packageName);
10168            oldPkgSetting = mSettings.mPackages.get(packageName);
10169            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10170                    (oldPkgSetting == null)) {
10171                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10172                return;
10173            }
10174        }
10175
10176        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10177
10178        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10179        res.removedInfo.removedPackage = packageName;
10180        // Remove existing system package
10181        removePackageLI(oldPkgSetting, true);
10182        // writer
10183        synchronized (mPackages) {
10184            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10185                // We didn't need to disable the .apk as a current system package,
10186                // which means we are replacing another update that is already
10187                // installed.  We need to make sure to delete the older one's .apk.
10188                res.removedInfo.args = createInstallArgs(0,
10189                        deletedPackage.applicationInfo.sourceDir,
10190                        deletedPackage.applicationInfo.publicSourceDir,
10191                        deletedPackage.applicationInfo.nativeLibraryDir,
10192                        getAppInstructionSet(deletedPackage.applicationInfo));
10193            } else {
10194                res.removedInfo.args = null;
10195            }
10196        }
10197
10198        // Successfully disabled the old package. Now proceed with re-installation
10199        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10200        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10201        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10202        if (newPackage == null) {
10203            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10204            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10205                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10206            }
10207        } else {
10208            if (newPackage.mExtras != null) {
10209                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10210                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10211                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10212
10213                // is the update attempting to change shared user? that isn't going to work...
10214                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10215                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10216                            + " to " + newPkgSetting.sharedUser);
10217                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10218                    updatedSettings = true;
10219                }
10220            }
10221
10222            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10223                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10224                updatedSettings = true;
10225            }
10226        }
10227
10228        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10229            // Re installation failed. Restore old information
10230            // Remove new pkg information
10231            if (newPackage != null) {
10232                removeInstalledPackageLI(newPackage, true);
10233            }
10234            // Add back the old system package
10235            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
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 instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10253            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10254                                             instructionSet);
10255            if (retCode != 0) {
10256                /*
10257                 * Programs may be lazily run through dexopt, so the
10258                 * source may not exist. However, something seems to
10259                 * have gone wrong, so note that dexopt needs to be
10260                 * run again and remove the source file. In addition,
10261                 * remove the target to make sure there isn't a stale
10262                 * file from a previous version of the package.
10263                 */
10264                newPackage.mDexOptNeeded = true;
10265                mInstaller.rmdex(oldCodePath, instructionSet);
10266                mInstaller.rmdex(newPackage.codePath, instructionSet);
10267            }
10268        }
10269        return PackageManager.INSTALL_SUCCEEDED;
10270    }
10271
10272    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10273            int[] allUsers, boolean[] perUserInstalled,
10274            PackageInstalledInfo res) {
10275        String pkgName = newPackage.packageName;
10276        synchronized (mPackages) {
10277            //write settings. the installStatus will be incomplete at this stage.
10278            //note that the new package setting would have already been
10279            //added to mPackages. It hasn't been persisted yet.
10280            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10281            mSettings.writeLPr();
10282        }
10283
10284        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10285
10286        synchronized (mPackages) {
10287            updatePermissionsLPw(newPackage.packageName, newPackage,
10288                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10289                            ? UPDATE_PERMISSIONS_ALL : 0));
10290            // For system-bundled packages, we assume that installing an upgraded version
10291            // of the package implies that the user actually wants to run that new code,
10292            // so we enable the package.
10293            if (isSystemApp(newPackage)) {
10294                // NB: implicit assumption that system package upgrades apply to all users
10295                if (DEBUG_INSTALL) {
10296                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10297                }
10298                PackageSetting ps = mSettings.mPackages.get(pkgName);
10299                if (ps != null) {
10300                    if (res.origUsers != null) {
10301                        for (int userHandle : res.origUsers) {
10302                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10303                                    userHandle, installerPackageName);
10304                        }
10305                    }
10306                    // Also convey the prior install/uninstall state
10307                    if (allUsers != null && perUserInstalled != null) {
10308                        for (int i = 0; i < allUsers.length; i++) {
10309                            if (DEBUG_INSTALL) {
10310                                Slog.d(TAG, "    user " + allUsers[i]
10311                                        + " => " + perUserInstalled[i]);
10312                            }
10313                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10314                        }
10315                        // these install state changes will be persisted in the
10316                        // upcoming call to mSettings.writeLPr().
10317                    }
10318                }
10319            }
10320            res.name = pkgName;
10321            res.uid = newPackage.applicationInfo.uid;
10322            res.pkg = newPackage;
10323            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10324            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10325            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10326            //to update install status
10327            mSettings.writeLPr();
10328        }
10329    }
10330
10331    private void installPackageLI(InstallArgs args,
10332            boolean newInstall, PackageInstalledInfo res) {
10333        int pFlags = args.flags;
10334        String installerPackageName = args.installerPackageName;
10335        File tmpPackageFile = new File(args.getCodePath());
10336        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10337        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10338        boolean replace = false;
10339        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10340                | (newInstall ? SCAN_NEW_INSTALL : 0);
10341        // Result object to be returned
10342        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10343
10344        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10345        // Retrieve PackageSettings and parse package
10346        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10347                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10348                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10349        PackageParser pp = new PackageParser();
10350        pp.setSeparateProcesses(mSeparateProcesses);
10351        pp.setDisplayMetrics(mMetrics);
10352
10353        final PackageParser.Package pkg;
10354        try {
10355            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10356        } catch (PackageParserException e) {
10357            res.returnCode = e.error;
10358            return;
10359        }
10360
10361        String pkgName = res.name = pkg.packageName;
10362        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10363            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10364                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10365                return;
10366            }
10367        }
10368
10369        try {
10370            pp.collectCertificates(pkg, parseFlags);
10371            pp.collectManifestDigest(pkg);
10372        } catch (PackageParserException e) {
10373            res.returnCode = e.error;
10374            return;
10375        }
10376
10377        /* If the installer passed in a manifest digest, compare it now. */
10378        if (args.manifestDigest != null) {
10379            if (DEBUG_INSTALL) {
10380                final String parsedManifest = pkg.manifestDigest == null ? "null"
10381                        : pkg.manifestDigest.toString();
10382                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10383                        + parsedManifest);
10384            }
10385
10386            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10387                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10388                return;
10389            }
10390        } else if (DEBUG_INSTALL) {
10391            final String parsedManifest = pkg.manifestDigest == null
10392                    ? "null" : pkg.manifestDigest.toString();
10393            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10394        }
10395
10396        // Get rid of all references to package scan path via parser.
10397        pp = null;
10398        String oldCodePath = null;
10399        boolean systemApp = false;
10400        synchronized (mPackages) {
10401            // Check whether the newly-scanned package wants to define an already-defined perm
10402            int N = pkg.permissions.size();
10403            for (int i = N-1; i >= 0; i--) {
10404                PackageParser.Permission perm = pkg.permissions.get(i);
10405                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10406                if (bp != null) {
10407                    // If the defining package is signed with our cert, it's okay.  This
10408                    // also includes the "updating the same package" case, of course.
10409                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10410                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10411                        // If the owning package is the system itself, we log but allow
10412                        // install to proceed; we fail the install on all other permission
10413                        // redefinitions.
10414                        if (!bp.sourcePackage.equals("android")) {
10415                            Slog.w(TAG, "Package " + pkg.packageName
10416                                    + " attempting to redeclare permission " + perm.info.name
10417                                    + " already owned by " + bp.sourcePackage);
10418                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10419                            res.origPermission = perm.info.name;
10420                            res.origPackage = bp.sourcePackage;
10421                            return;
10422                        } else {
10423                            Slog.w(TAG, "Package " + pkg.packageName
10424                                    + " attempting to redeclare system permission "
10425                                    + perm.info.name + "; ignoring new declaration");
10426                            pkg.permissions.remove(i);
10427                        }
10428                    }
10429                }
10430            }
10431
10432            // Check if installing already existing package
10433            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10434                String oldName = mSettings.mRenamedPackages.get(pkgName);
10435                if (pkg.mOriginalPackages != null
10436                        && pkg.mOriginalPackages.contains(oldName)
10437                        && mPackages.containsKey(oldName)) {
10438                    // This package is derived from an original package,
10439                    // and this device has been updating from that original
10440                    // name.  We must continue using the original name, so
10441                    // rename the new package here.
10442                    pkg.setPackageName(oldName);
10443                    pkgName = pkg.packageName;
10444                    replace = true;
10445                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10446                            + oldName + " pkgName=" + pkgName);
10447                } else if (mPackages.containsKey(pkgName)) {
10448                    // This package, under its official name, already exists
10449                    // on the device; we should replace it.
10450                    replace = true;
10451                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10452                }
10453            }
10454            PackageSetting ps = mSettings.mPackages.get(pkgName);
10455            if (ps != null) {
10456                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10457                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10458                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10459                    systemApp = (ps.pkg.applicationInfo.flags &
10460                            ApplicationInfo.FLAG_SYSTEM) != 0;
10461                }
10462                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10463            }
10464        }
10465
10466        if (systemApp && onSd) {
10467            // Disable updates to system apps on sdcard
10468            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10469            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10470            return;
10471        }
10472
10473        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10474            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10475            return;
10476        }
10477        // Set application objects path explicitly after the rename
10478        pkg.codePath = args.getCodePath();
10479        pkg.applicationInfo.sourceDir = args.getCodePath();
10480        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10481        pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths();
10482        pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths(
10483                pkg.applicationInfo.splitSourceDirs);
10484        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10485        if (replace) {
10486            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10487                    installerPackageName, res, args.abiOverride);
10488        } else {
10489            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10490                    installerPackageName, res, args.abiOverride);
10491        }
10492        synchronized (mPackages) {
10493            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10494            if (ps != null) {
10495                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10496            }
10497        }
10498    }
10499
10500    private static boolean isForwardLocked(PackageParser.Package pkg) {
10501        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10502    }
10503
10504
10505    private boolean isForwardLocked(PackageSetting ps) {
10506        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10507    }
10508
10509    private static boolean isExternal(PackageParser.Package pkg) {
10510        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10511    }
10512
10513    private static boolean isExternal(PackageSetting ps) {
10514        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10515    }
10516
10517    private static boolean isSystemApp(PackageParser.Package pkg) {
10518        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10519    }
10520
10521    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10522        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10523    }
10524
10525    private static boolean isSystemApp(ApplicationInfo info) {
10526        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10527    }
10528
10529    private static boolean isSystemApp(PackageSetting ps) {
10530        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10531    }
10532
10533    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10534        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10535    }
10536
10537    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10538        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10539    }
10540
10541    private int packageFlagsToInstallFlags(PackageSetting ps) {
10542        int installFlags = 0;
10543        if (isExternal(ps)) {
10544            installFlags |= PackageManager.INSTALL_EXTERNAL;
10545        }
10546        if (isForwardLocked(ps)) {
10547            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10548        }
10549        return installFlags;
10550    }
10551
10552    private void deleteTempPackageFiles() {
10553        final FilenameFilter filter = new FilenameFilter() {
10554            public boolean accept(File dir, String name) {
10555                return name.startsWith("vmdl") && name.endsWith(".tmp");
10556            }
10557        };
10558        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10559        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10560    }
10561
10562    private static final void deleteTempPackageFilesInDirectory(File directory,
10563            FilenameFilter filter) {
10564        final String[] tmpFilesList = directory.list(filter);
10565        if (tmpFilesList == null) {
10566            return;
10567        }
10568        for (int i = 0; i < tmpFilesList.length; i++) {
10569            final File tmpFile = new File(directory, tmpFilesList[i]);
10570            tmpFile.delete();
10571        }
10572    }
10573
10574    private File createTempPackageFile(File installDir) {
10575        File tmpPackageFile;
10576        try {
10577            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10578        } catch (IOException e) {
10579            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10580            return null;
10581        }
10582        try {
10583            FileUtils.setPermissions(
10584                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10585                    -1, -1);
10586            if (!SELinux.restorecon(tmpPackageFile)) {
10587                return null;
10588            }
10589        } catch (IOException e) {
10590            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10591            return null;
10592        }
10593        return tmpPackageFile;
10594    }
10595
10596    @Override
10597    public void deletePackageAsUser(final String packageName,
10598                                    final IPackageDeleteObserver observer,
10599                                    final int userId, final int flags) {
10600        mContext.enforceCallingOrSelfPermission(
10601                android.Manifest.permission.DELETE_PACKAGES, null);
10602        final int uid = Binder.getCallingUid();
10603        if (UserHandle.getUserId(uid) != userId) {
10604            mContext.enforceCallingPermission(
10605                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10606                    "deletePackage for user " + userId);
10607        }
10608        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10609            try {
10610                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10611            } catch (RemoteException re) {
10612            }
10613            return;
10614        }
10615
10616        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10617        // Queue up an async operation since the package deletion may take a little while.
10618        mHandler.post(new Runnable() {
10619            public void run() {
10620                mHandler.removeCallbacks(this);
10621                final int returnCode = deletePackageX(packageName, userId, flags);
10622                if (observer != null) {
10623                    try {
10624                        observer.packageDeleted(packageName, returnCode);
10625                    } catch (RemoteException e) {
10626                        Log.i(TAG, "Observer no longer exists.");
10627                    } //end catch
10628                } //end if
10629            } //end run
10630        });
10631    }
10632
10633    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10634        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10635                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10636        try {
10637            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10638                    || dpm.isDeviceOwner(packageName))) {
10639                return true;
10640            }
10641        } catch (RemoteException e) {
10642        }
10643        return false;
10644    }
10645
10646    /**
10647     *  This method is an internal method that could be get invoked either
10648     *  to delete an installed package or to clean up a failed installation.
10649     *  After deleting an installed package, a broadcast is sent to notify any
10650     *  listeners that the package has been installed. For cleaning up a failed
10651     *  installation, the broadcast is not necessary since the package's
10652     *  installation wouldn't have sent the initial broadcast either
10653     *  The key steps in deleting a package are
10654     *  deleting the package information in internal structures like mPackages,
10655     *  deleting the packages base directories through installd
10656     *  updating mSettings to reflect current status
10657     *  persisting settings for later use
10658     *  sending a broadcast if necessary
10659     */
10660    private int deletePackageX(String packageName, int userId, int flags) {
10661        final PackageRemovedInfo info = new PackageRemovedInfo();
10662        final boolean res;
10663
10664        if (isPackageDeviceAdmin(packageName, userId)) {
10665            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10666            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10667        }
10668
10669        boolean removedForAllUsers = false;
10670        boolean systemUpdate = false;
10671
10672        // for the uninstall-updates case and restricted profiles, remember the per-
10673        // userhandle installed state
10674        int[] allUsers;
10675        boolean[] perUserInstalled;
10676        synchronized (mPackages) {
10677            PackageSetting ps = mSettings.mPackages.get(packageName);
10678            allUsers = sUserManager.getUserIds();
10679            perUserInstalled = new boolean[allUsers.length];
10680            for (int i = 0; i < allUsers.length; i++) {
10681                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10682            }
10683        }
10684
10685        synchronized (mInstallLock) {
10686            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10687            res = deletePackageLI(packageName,
10688                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10689                            ? UserHandle.ALL : new UserHandle(userId),
10690                    true, allUsers, perUserInstalled,
10691                    flags | REMOVE_CHATTY, info, true);
10692            systemUpdate = info.isRemovedPackageSystemUpdate;
10693            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10694                removedForAllUsers = true;
10695            }
10696            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10697                    + " removedForAllUsers=" + removedForAllUsers);
10698        }
10699
10700        if (res) {
10701            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10702
10703            // If the removed package was a system update, the old system package
10704            // was re-enabled; we need to broadcast this information
10705            if (systemUpdate) {
10706                Bundle extras = new Bundle(1);
10707                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10708                        ? info.removedAppId : info.uid);
10709                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10710
10711                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10712                        extras, null, null, null);
10713                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10714                        extras, null, null, null);
10715                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10716                        null, packageName, null, null);
10717            }
10718        }
10719        // Force a gc here.
10720        Runtime.getRuntime().gc();
10721        // Delete the resources here after sending the broadcast to let
10722        // other processes clean up before deleting resources.
10723        if (info.args != null) {
10724            synchronized (mInstallLock) {
10725                info.args.doPostDeleteLI(true);
10726            }
10727        }
10728
10729        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10730    }
10731
10732    static class PackageRemovedInfo {
10733        String removedPackage;
10734        int uid = -1;
10735        int removedAppId = -1;
10736        int[] removedUsers = null;
10737        boolean isRemovedPackageSystemUpdate = false;
10738        // Clean up resources deleted packages.
10739        InstallArgs args = null;
10740
10741        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10742            Bundle extras = new Bundle(1);
10743            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10744            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10745            if (replacing) {
10746                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10747            }
10748            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10749            if (removedPackage != null) {
10750                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10751                        extras, null, null, removedUsers);
10752                if (fullRemove && !replacing) {
10753                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10754                            extras, null, null, removedUsers);
10755                }
10756            }
10757            if (removedAppId >= 0) {
10758                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10759                        removedUsers);
10760            }
10761        }
10762    }
10763
10764    /*
10765     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10766     * flag is not set, the data directory is removed as well.
10767     * make sure this flag is set for partially installed apps. If not its meaningless to
10768     * delete a partially installed application.
10769     */
10770    private void removePackageDataLI(PackageSetting ps,
10771            int[] allUserHandles, boolean[] perUserInstalled,
10772            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10773        String packageName = ps.name;
10774        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10775        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10776        // Retrieve object to delete permissions for shared user later on
10777        final PackageSetting deletedPs;
10778        // reader
10779        synchronized (mPackages) {
10780            deletedPs = mSettings.mPackages.get(packageName);
10781            if (outInfo != null) {
10782                outInfo.removedPackage = packageName;
10783                outInfo.removedUsers = deletedPs != null
10784                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10785                        : null;
10786            }
10787        }
10788        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10789            removeDataDirsLI(packageName);
10790            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10791        }
10792        // writer
10793        synchronized (mPackages) {
10794            if (deletedPs != null) {
10795                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10796                    if (outInfo != null) {
10797                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10798                    }
10799                    if (deletedPs != null) {
10800                        updatePermissionsLPw(deletedPs.name, null, 0);
10801                        if (deletedPs.sharedUser != null) {
10802                            // remove permissions associated with package
10803                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10804                        }
10805                    }
10806                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10807                }
10808                // make sure to preserve per-user disabled state if this removal was just
10809                // a downgrade of a system app to the factory package
10810                if (allUserHandles != null && perUserInstalled != null) {
10811                    if (DEBUG_REMOVE) {
10812                        Slog.d(TAG, "Propagating install state across downgrade");
10813                    }
10814                    for (int i = 0; i < allUserHandles.length; i++) {
10815                        if (DEBUG_REMOVE) {
10816                            Slog.d(TAG, "    user " + allUserHandles[i]
10817                                    + " => " + perUserInstalled[i]);
10818                        }
10819                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10820                    }
10821                }
10822            }
10823            // can downgrade to reader
10824            if (writeSettings) {
10825                // Save settings now
10826                mSettings.writeLPr();
10827            }
10828        }
10829        if (outInfo != null) {
10830            // A user ID was deleted here. Go through all users and remove it
10831            // from KeyStore.
10832            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10833        }
10834    }
10835
10836    static boolean locationIsPrivileged(File path) {
10837        try {
10838            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10839                    .getCanonicalPath();
10840            return path.getCanonicalPath().startsWith(privilegedAppDir);
10841        } catch (IOException e) {
10842            Slog.e(TAG, "Unable to access code path " + path);
10843        }
10844        return false;
10845    }
10846
10847    /*
10848     * Tries to delete system package.
10849     */
10850    private boolean deleteSystemPackageLI(PackageSetting newPs,
10851            int[] allUserHandles, boolean[] perUserInstalled,
10852            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10853        final boolean applyUserRestrictions
10854                = (allUserHandles != null) && (perUserInstalled != null);
10855        PackageSetting disabledPs = null;
10856        // Confirm if the system package has been updated
10857        // An updated system app can be deleted. This will also have to restore
10858        // the system pkg from system partition
10859        // reader
10860        synchronized (mPackages) {
10861            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10862        }
10863        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10864                + " disabledPs=" + disabledPs);
10865        if (disabledPs == null) {
10866            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10867            return false;
10868        } else if (DEBUG_REMOVE) {
10869            Slog.d(TAG, "Deleting system pkg from data partition");
10870        }
10871        if (DEBUG_REMOVE) {
10872            if (applyUserRestrictions) {
10873                Slog.d(TAG, "Remembering install states:");
10874                for (int i = 0; i < allUserHandles.length; i++) {
10875                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10876                }
10877            }
10878        }
10879        // Delete the updated package
10880        outInfo.isRemovedPackageSystemUpdate = true;
10881        if (disabledPs.versionCode < newPs.versionCode) {
10882            // Delete data for downgrades
10883            flags &= ~PackageManager.DELETE_KEEP_DATA;
10884        } else {
10885            // Preserve data by setting flag
10886            flags |= PackageManager.DELETE_KEEP_DATA;
10887        }
10888        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10889                allUserHandles, perUserInstalled, outInfo, writeSettings);
10890        if (!ret) {
10891            return false;
10892        }
10893        // writer
10894        synchronized (mPackages) {
10895            // Reinstate the old system package
10896            mSettings.enableSystemPackageLPw(newPs.name);
10897            // Remove any native libraries from the upgraded package.
10898            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10899        }
10900        // Install the system package
10901        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10902        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10903        if (locationIsPrivileged(disabledPs.codePath)) {
10904            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10905        }
10906        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10907                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10908
10909        if (newPkg == null) {
10910            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10911                    + " with error:" + mLastScanError);
10912            return false;
10913        }
10914        // writer
10915        synchronized (mPackages) {
10916            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10917            setInternalAppNativeLibraryPath(newPkg, ps);
10918            updatePermissionsLPw(newPkg.packageName, newPkg,
10919                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10920            if (applyUserRestrictions) {
10921                if (DEBUG_REMOVE) {
10922                    Slog.d(TAG, "Propagating install state across reinstall");
10923                }
10924                for (int i = 0; i < allUserHandles.length; i++) {
10925                    if (DEBUG_REMOVE) {
10926                        Slog.d(TAG, "    user " + allUserHandles[i]
10927                                + " => " + perUserInstalled[i]);
10928                    }
10929                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10930                }
10931                // Regardless of writeSettings we need to ensure that this restriction
10932                // state propagation is persisted
10933                mSettings.writeAllUsersPackageRestrictionsLPr();
10934            }
10935            // can downgrade to reader here
10936            if (writeSettings) {
10937                mSettings.writeLPr();
10938            }
10939        }
10940        return true;
10941    }
10942
10943    private boolean deleteInstalledPackageLI(PackageSetting ps,
10944            boolean deleteCodeAndResources, int flags,
10945            int[] allUserHandles, boolean[] perUserInstalled,
10946            PackageRemovedInfo outInfo, boolean writeSettings) {
10947        if (outInfo != null) {
10948            outInfo.uid = ps.appId;
10949        }
10950
10951        // Delete package data from internal structures and also remove data if flag is set
10952        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10953
10954        // Delete application code and resources
10955        if (deleteCodeAndResources && (outInfo != null)) {
10956            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10957                    ps.resourcePathString, ps.nativeLibraryPathString,
10958                    getAppInstructionSetFromSettings(ps));
10959        }
10960        return true;
10961    }
10962
10963    /*
10964     * This method handles package deletion in general
10965     */
10966    private boolean deletePackageLI(String packageName, UserHandle user,
10967            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10968            int flags, PackageRemovedInfo outInfo,
10969            boolean writeSettings) {
10970        if (packageName == null) {
10971            Slog.w(TAG, "Attempt to delete null packageName.");
10972            return false;
10973        }
10974        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10975        PackageSetting ps;
10976        boolean dataOnly = false;
10977        int removeUser = -1;
10978        int appId = -1;
10979        synchronized (mPackages) {
10980            ps = mSettings.mPackages.get(packageName);
10981            if (ps == null) {
10982                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10983                return false;
10984            }
10985            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10986                    && user.getIdentifier() != UserHandle.USER_ALL) {
10987                // The caller is asking that the package only be deleted for a single
10988                // user.  To do this, we just mark its uninstalled state and delete
10989                // its data.  If this is a system app, we only allow this to happen if
10990                // they have set the special DELETE_SYSTEM_APP which requests different
10991                // semantics than normal for uninstalling system apps.
10992                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10993                ps.setUserState(user.getIdentifier(),
10994                        COMPONENT_ENABLED_STATE_DEFAULT,
10995                        false, //installed
10996                        true,  //stopped
10997                        true,  //notLaunched
10998                        false, //blocked
10999                        null, null, null);
11000                if (!isSystemApp(ps)) {
11001                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11002                        // Other user still have this package installed, so all
11003                        // we need to do is clear this user's data and save that
11004                        // it is uninstalled.
11005                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11006                        removeUser = user.getIdentifier();
11007                        appId = ps.appId;
11008                        mSettings.writePackageRestrictionsLPr(removeUser);
11009                    } else {
11010                        // We need to set it back to 'installed' so the uninstall
11011                        // broadcasts will be sent correctly.
11012                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11013                        ps.setInstalled(true, user.getIdentifier());
11014                    }
11015                } else {
11016                    // This is a system app, so we assume that the
11017                    // other users still have this package installed, so all
11018                    // we need to do is clear this user's data and save that
11019                    // it is uninstalled.
11020                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11021                    removeUser = user.getIdentifier();
11022                    appId = ps.appId;
11023                    mSettings.writePackageRestrictionsLPr(removeUser);
11024                }
11025            }
11026        }
11027
11028        if (removeUser >= 0) {
11029            // From above, we determined that we are deleting this only
11030            // for a single user.  Continue the work here.
11031            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11032            if (outInfo != null) {
11033                outInfo.removedPackage = packageName;
11034                outInfo.removedAppId = appId;
11035                outInfo.removedUsers = new int[] {removeUser};
11036            }
11037            mInstaller.clearUserData(packageName, removeUser);
11038            removeKeystoreDataIfNeeded(removeUser, appId);
11039            schedulePackageCleaning(packageName, removeUser, false);
11040            return true;
11041        }
11042
11043        if (dataOnly) {
11044            // Delete application data first
11045            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11046            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11047            return true;
11048        }
11049
11050        boolean ret = false;
11051        mSettings.mKeySetManager.removeAppKeySetData(packageName);
11052        if (isSystemApp(ps)) {
11053            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11054            // When an updated system application is deleted we delete the existing resources as well and
11055            // fall back to existing code in system partition
11056            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11057                    flags, outInfo, writeSettings);
11058        } else {
11059            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11060            // Kill application pre-emptively especially for apps on sd.
11061            killApplication(packageName, ps.appId, "uninstall pkg");
11062            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11063                    allUserHandles, perUserInstalled,
11064                    outInfo, writeSettings);
11065        }
11066
11067        return ret;
11068    }
11069
11070    private final class ClearStorageConnection implements ServiceConnection {
11071        IMediaContainerService mContainerService;
11072
11073        @Override
11074        public void onServiceConnected(ComponentName name, IBinder service) {
11075            synchronized (this) {
11076                mContainerService = IMediaContainerService.Stub.asInterface(service);
11077                notifyAll();
11078            }
11079        }
11080
11081        @Override
11082        public void onServiceDisconnected(ComponentName name) {
11083        }
11084    }
11085
11086    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11087        final boolean mounted;
11088        if (Environment.isExternalStorageEmulated()) {
11089            mounted = true;
11090        } else {
11091            final String status = Environment.getExternalStorageState();
11092
11093            mounted = status.equals(Environment.MEDIA_MOUNTED)
11094                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11095        }
11096
11097        if (!mounted) {
11098            return;
11099        }
11100
11101        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11102        int[] users;
11103        if (userId == UserHandle.USER_ALL) {
11104            users = sUserManager.getUserIds();
11105        } else {
11106            users = new int[] { userId };
11107        }
11108        final ClearStorageConnection conn = new ClearStorageConnection();
11109        if (mContext.bindServiceAsUser(
11110                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11111            try {
11112                for (int curUser : users) {
11113                    long timeout = SystemClock.uptimeMillis() + 5000;
11114                    synchronized (conn) {
11115                        long now = SystemClock.uptimeMillis();
11116                        while (conn.mContainerService == null && now < timeout) {
11117                            try {
11118                                conn.wait(timeout - now);
11119                            } catch (InterruptedException e) {
11120                            }
11121                        }
11122                    }
11123                    if (conn.mContainerService == null) {
11124                        return;
11125                    }
11126
11127                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11128                    clearDirectory(conn.mContainerService,
11129                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11130                    if (allData) {
11131                        clearDirectory(conn.mContainerService,
11132                                userEnv.buildExternalStorageAppDataDirs(packageName));
11133                        clearDirectory(conn.mContainerService,
11134                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11135                    }
11136                }
11137            } finally {
11138                mContext.unbindService(conn);
11139            }
11140        }
11141    }
11142
11143    @Override
11144    public void clearApplicationUserData(final String packageName,
11145            final IPackageDataObserver observer, final int userId) {
11146        mContext.enforceCallingOrSelfPermission(
11147                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11148        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11149        // Queue up an async operation since the package deletion may take a little while.
11150        mHandler.post(new Runnable() {
11151            public void run() {
11152                mHandler.removeCallbacks(this);
11153                final boolean succeeded;
11154                synchronized (mInstallLock) {
11155                    succeeded = clearApplicationUserDataLI(packageName, userId);
11156                }
11157                clearExternalStorageDataSync(packageName, userId, true);
11158                if (succeeded) {
11159                    // invoke DeviceStorageMonitor's update method to clear any notifications
11160                    DeviceStorageMonitorInternal
11161                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11162                    if (dsm != null) {
11163                        dsm.checkMemory();
11164                    }
11165                }
11166                if(observer != null) {
11167                    try {
11168                        observer.onRemoveCompleted(packageName, succeeded);
11169                    } catch (RemoteException e) {
11170                        Log.i(TAG, "Observer no longer exists.");
11171                    }
11172                } //end if observer
11173            } //end run
11174        });
11175    }
11176
11177    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11178        if (packageName == null) {
11179            Slog.w(TAG, "Attempt to delete null packageName.");
11180            return false;
11181        }
11182        PackageParser.Package p;
11183        boolean dataOnly = false;
11184        final int appId;
11185        synchronized (mPackages) {
11186            p = mPackages.get(packageName);
11187            if (p == null) {
11188                dataOnly = true;
11189                PackageSetting ps = mSettings.mPackages.get(packageName);
11190                if ((ps == null) || (ps.pkg == null)) {
11191                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11192                    return false;
11193                }
11194                p = ps.pkg;
11195            }
11196            if (!dataOnly) {
11197                // need to check this only for fully installed applications
11198                if (p == null) {
11199                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11200                    return false;
11201                }
11202                final ApplicationInfo applicationInfo = p.applicationInfo;
11203                if (applicationInfo == null) {
11204                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11205                    return false;
11206                }
11207            }
11208            if (p != null && p.applicationInfo != null) {
11209                appId = p.applicationInfo.uid;
11210            } else {
11211                appId = -1;
11212            }
11213        }
11214        int retCode = mInstaller.clearUserData(packageName, userId);
11215        if (retCode < 0) {
11216            Slog.w(TAG, "Couldn't remove cache files for package: "
11217                    + packageName);
11218            return false;
11219        }
11220        removeKeystoreDataIfNeeded(userId, appId);
11221        return true;
11222    }
11223
11224    /**
11225     * Remove entries from the keystore daemon. Will only remove it if the
11226     * {@code appId} is valid.
11227     */
11228    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11229        if (appId < 0) {
11230            return;
11231        }
11232
11233        final KeyStore keyStore = KeyStore.getInstance();
11234        if (keyStore != null) {
11235            if (userId == UserHandle.USER_ALL) {
11236                for (final int individual : sUserManager.getUserIds()) {
11237                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11238                }
11239            } else {
11240                keyStore.clearUid(UserHandle.getUid(userId, appId));
11241            }
11242        } else {
11243            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11244        }
11245    }
11246
11247    @Override
11248    public void deleteApplicationCacheFiles(final String packageName,
11249            final IPackageDataObserver observer) {
11250        mContext.enforceCallingOrSelfPermission(
11251                android.Manifest.permission.DELETE_CACHE_FILES, null);
11252        // Queue up an async operation since the package deletion may take a little while.
11253        final int userId = UserHandle.getCallingUserId();
11254        mHandler.post(new Runnable() {
11255            public void run() {
11256                mHandler.removeCallbacks(this);
11257                final boolean succeded;
11258                synchronized (mInstallLock) {
11259                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11260                }
11261                clearExternalStorageDataSync(packageName, userId, false);
11262                if(observer != null) {
11263                    try {
11264                        observer.onRemoveCompleted(packageName, succeded);
11265                    } catch (RemoteException e) {
11266                        Log.i(TAG, "Observer no longer exists.");
11267                    }
11268                } //end if observer
11269            } //end run
11270        });
11271    }
11272
11273    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11274        if (packageName == null) {
11275            Slog.w(TAG, "Attempt to delete null packageName.");
11276            return false;
11277        }
11278        PackageParser.Package p;
11279        synchronized (mPackages) {
11280            p = mPackages.get(packageName);
11281        }
11282        if (p == null) {
11283            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11284            return false;
11285        }
11286        final ApplicationInfo applicationInfo = p.applicationInfo;
11287        if (applicationInfo == null) {
11288            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11289            return false;
11290        }
11291        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11292        if (retCode < 0) {
11293            Slog.w(TAG, "Couldn't remove cache files for package: "
11294                       + packageName + " u" + userId);
11295            return false;
11296        }
11297        return true;
11298    }
11299
11300    @Override
11301    public void getPackageSizeInfo(final String packageName, int userHandle,
11302            final IPackageStatsObserver observer) {
11303        mContext.enforceCallingOrSelfPermission(
11304                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11305        if (packageName == null) {
11306            throw new IllegalArgumentException("Attempt to get size of null packageName");
11307        }
11308
11309        PackageStats stats = new PackageStats(packageName, userHandle);
11310
11311        /*
11312         * Queue up an async operation since the package measurement may take a
11313         * little while.
11314         */
11315        Message msg = mHandler.obtainMessage(INIT_COPY);
11316        msg.obj = new MeasureParams(stats, observer);
11317        mHandler.sendMessage(msg);
11318    }
11319
11320    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11321            PackageStats pStats) {
11322        if (packageName == null) {
11323            Slog.w(TAG, "Attempt to get size of null packageName.");
11324            return false;
11325        }
11326        PackageParser.Package p;
11327        boolean dataOnly = false;
11328        String libDirPath = null;
11329        String asecPath = null;
11330        PackageSetting ps = null;
11331        synchronized (mPackages) {
11332            p = mPackages.get(packageName);
11333            ps = mSettings.mPackages.get(packageName);
11334            if(p == null) {
11335                dataOnly = true;
11336                if((ps == null) || (ps.pkg == null)) {
11337                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11338                    return false;
11339                }
11340                p = ps.pkg;
11341            }
11342            if (ps != null) {
11343                libDirPath = ps.nativeLibraryPathString;
11344            }
11345            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11346                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11347                if (secureContainerId != null) {
11348                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11349                }
11350            }
11351        }
11352        String publicSrcDir = null;
11353        if(!dataOnly) {
11354            final ApplicationInfo applicationInfo = p.applicationInfo;
11355            if (applicationInfo == null) {
11356                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11357                return false;
11358            }
11359            if (isForwardLocked(p)) {
11360                publicSrcDir = applicationInfo.publicSourceDir;
11361            }
11362        }
11363        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11364                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11365                pStats);
11366        if (res < 0) {
11367            return false;
11368        }
11369
11370        // Fix-up for forward-locked applications in ASEC containers.
11371        if (!isExternal(p)) {
11372            pStats.codeSize += pStats.externalCodeSize;
11373            pStats.externalCodeSize = 0L;
11374        }
11375
11376        return true;
11377    }
11378
11379
11380    @Override
11381    public void addPackageToPreferred(String packageName) {
11382        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11383    }
11384
11385    @Override
11386    public void removePackageFromPreferred(String packageName) {
11387        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11388    }
11389
11390    @Override
11391    public List<PackageInfo> getPreferredPackages(int flags) {
11392        return new ArrayList<PackageInfo>();
11393    }
11394
11395    private int getUidTargetSdkVersionLockedLPr(int uid) {
11396        Object obj = mSettings.getUserIdLPr(uid);
11397        if (obj instanceof SharedUserSetting) {
11398            final SharedUserSetting sus = (SharedUserSetting) obj;
11399            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11400            final Iterator<PackageSetting> it = sus.packages.iterator();
11401            while (it.hasNext()) {
11402                final PackageSetting ps = it.next();
11403                if (ps.pkg != null) {
11404                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11405                    if (v < vers) vers = v;
11406                }
11407            }
11408            return vers;
11409        } else if (obj instanceof PackageSetting) {
11410            final PackageSetting ps = (PackageSetting) obj;
11411            if (ps.pkg != null) {
11412                return ps.pkg.applicationInfo.targetSdkVersion;
11413            }
11414        }
11415        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11416    }
11417
11418    @Override
11419    public void addPreferredActivity(IntentFilter filter, int match,
11420            ComponentName[] set, ComponentName activity, int userId) {
11421        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11422    }
11423
11424    private void addPreferredActivityInternal(IntentFilter filter, int match,
11425            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11426        // writer
11427        int callingUid = Binder.getCallingUid();
11428        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11429        if (filter.countActions() == 0) {
11430            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11431            return;
11432        }
11433        synchronized (mPackages) {
11434            if (mContext.checkCallingOrSelfPermission(
11435                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11436                    != PackageManager.PERMISSION_GRANTED) {
11437                if (getUidTargetSdkVersionLockedLPr(callingUid)
11438                        < Build.VERSION_CODES.FROYO) {
11439                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11440                            + callingUid);
11441                    return;
11442                }
11443                mContext.enforceCallingOrSelfPermission(
11444                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11445            }
11446
11447            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11448            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11449            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11450                    new PreferredActivity(filter, match, set, activity, always));
11451            mSettings.writePackageRestrictionsLPr(userId);
11452        }
11453    }
11454
11455    @Override
11456    public void replacePreferredActivity(IntentFilter filter, int match,
11457            ComponentName[] set, ComponentName activity) {
11458        if (filter.countActions() != 1) {
11459            throw new IllegalArgumentException(
11460                    "replacePreferredActivity expects filter to have only 1 action.");
11461        }
11462        if (filter.countDataAuthorities() != 0
11463                || filter.countDataPaths() != 0
11464                || filter.countDataSchemes() > 1
11465                || filter.countDataTypes() != 0) {
11466            throw new IllegalArgumentException(
11467                    "replacePreferredActivity expects filter to have no data authorities, " +
11468                    "paths, or types; and at most one scheme.");
11469        }
11470        synchronized (mPackages) {
11471            if (mContext.checkCallingOrSelfPermission(
11472                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11473                    != PackageManager.PERMISSION_GRANTED) {
11474                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11475                        < Build.VERSION_CODES.FROYO) {
11476                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11477                            + Binder.getCallingUid());
11478                    return;
11479                }
11480                mContext.enforceCallingOrSelfPermission(
11481                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11482            }
11483
11484            final int callingUserId = UserHandle.getCallingUserId();
11485            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11486            if (pir != null) {
11487                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11488                if (filter.countDataSchemes() == 1) {
11489                    Uri.Builder builder = new Uri.Builder();
11490                    builder.scheme(filter.getDataScheme(0));
11491                    intent.setData(builder.build());
11492                }
11493                List<PreferredActivity> matches = pir.queryIntent(
11494                        intent, null, true, callingUserId);
11495                if (DEBUG_PREFERRED) {
11496                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11497                }
11498                for (int i = 0; i < matches.size(); i++) {
11499                    PreferredActivity pa = matches.get(i);
11500                    if (DEBUG_PREFERRED) {
11501                        Slog.i(TAG, "Removing preferred activity "
11502                                + pa.mPref.mComponent + ":");
11503                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11504                    }
11505                    pir.removeFilter(pa);
11506                }
11507            }
11508            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11509        }
11510    }
11511
11512    @Override
11513    public void clearPackagePreferredActivities(String packageName) {
11514        final int uid = Binder.getCallingUid();
11515        // writer
11516        synchronized (mPackages) {
11517            PackageParser.Package pkg = mPackages.get(packageName);
11518            if (pkg == null || pkg.applicationInfo.uid != uid) {
11519                if (mContext.checkCallingOrSelfPermission(
11520                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11521                        != PackageManager.PERMISSION_GRANTED) {
11522                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11523                            < Build.VERSION_CODES.FROYO) {
11524                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11525                                + Binder.getCallingUid());
11526                        return;
11527                    }
11528                    mContext.enforceCallingOrSelfPermission(
11529                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11530                }
11531            }
11532
11533            int user = UserHandle.getCallingUserId();
11534            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11535                mSettings.writePackageRestrictionsLPr(user);
11536                scheduleWriteSettingsLocked();
11537            }
11538        }
11539    }
11540
11541    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11542    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11543        ArrayList<PreferredActivity> removed = null;
11544        boolean changed = false;
11545        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11546            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11547            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11548            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11549                continue;
11550            }
11551            Iterator<PreferredActivity> it = pir.filterIterator();
11552            while (it.hasNext()) {
11553                PreferredActivity pa = it.next();
11554                // Mark entry for removal only if it matches the package name
11555                // and the entry is of type "always".
11556                if (packageName == null ||
11557                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11558                                && pa.mPref.mAlways)) {
11559                    if (removed == null) {
11560                        removed = new ArrayList<PreferredActivity>();
11561                    }
11562                    removed.add(pa);
11563                }
11564            }
11565            if (removed != null) {
11566                for (int j=0; j<removed.size(); j++) {
11567                    PreferredActivity pa = removed.get(j);
11568                    pir.removeFilter(pa);
11569                }
11570                changed = true;
11571            }
11572        }
11573        return changed;
11574    }
11575
11576    @Override
11577    public void resetPreferredActivities(int userId) {
11578        mContext.enforceCallingOrSelfPermission(
11579                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11580        // writer
11581        synchronized (mPackages) {
11582            int user = UserHandle.getCallingUserId();
11583            clearPackagePreferredActivitiesLPw(null, user);
11584            mSettings.readDefaultPreferredAppsLPw(this, user);
11585            mSettings.writePackageRestrictionsLPr(user);
11586            scheduleWriteSettingsLocked();
11587        }
11588    }
11589
11590    @Override
11591    public int getPreferredActivities(List<IntentFilter> outFilters,
11592            List<ComponentName> outActivities, String packageName) {
11593
11594        int num = 0;
11595        final int userId = UserHandle.getCallingUserId();
11596        // reader
11597        synchronized (mPackages) {
11598            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11599            if (pir != null) {
11600                final Iterator<PreferredActivity> it = pir.filterIterator();
11601                while (it.hasNext()) {
11602                    final PreferredActivity pa = it.next();
11603                    if (packageName == null
11604                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11605                                    && pa.mPref.mAlways)) {
11606                        if (outFilters != null) {
11607                            outFilters.add(new IntentFilter(pa));
11608                        }
11609                        if (outActivities != null) {
11610                            outActivities.add(pa.mPref.mComponent);
11611                        }
11612                    }
11613                }
11614            }
11615        }
11616
11617        return num;
11618    }
11619
11620    @Override
11621    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11622            int userId) {
11623        int callingUid = Binder.getCallingUid();
11624        if (callingUid != Process.SYSTEM_UID) {
11625            throw new SecurityException(
11626                    "addPersistentPreferredActivity can only be run by the system");
11627        }
11628        if (filter.countActions() == 0) {
11629            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11630            return;
11631        }
11632        synchronized (mPackages) {
11633            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11634                    " :");
11635            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11636            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11637                    new PersistentPreferredActivity(filter, activity));
11638            mSettings.writePackageRestrictionsLPr(userId);
11639        }
11640    }
11641
11642    @Override
11643    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11644        int callingUid = Binder.getCallingUid();
11645        if (callingUid != Process.SYSTEM_UID) {
11646            throw new SecurityException(
11647                    "clearPackagePersistentPreferredActivities can only be run by the system");
11648        }
11649        ArrayList<PersistentPreferredActivity> removed = null;
11650        boolean changed = false;
11651        synchronized (mPackages) {
11652            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11653                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11654                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11655                        .valueAt(i);
11656                if (userId != thisUserId) {
11657                    continue;
11658                }
11659                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11660                while (it.hasNext()) {
11661                    PersistentPreferredActivity ppa = it.next();
11662                    // Mark entry for removal only if it matches the package name.
11663                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11664                        if (removed == null) {
11665                            removed = new ArrayList<PersistentPreferredActivity>();
11666                        }
11667                        removed.add(ppa);
11668                    }
11669                }
11670                if (removed != null) {
11671                    for (int j=0; j<removed.size(); j++) {
11672                        PersistentPreferredActivity ppa = removed.get(j);
11673                        ppir.removeFilter(ppa);
11674                    }
11675                    changed = true;
11676                }
11677            }
11678
11679            if (changed) {
11680                mSettings.writePackageRestrictionsLPr(userId);
11681            }
11682        }
11683    }
11684
11685    @Override
11686    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11687            int targetUserId, int flags) {
11688        mContext.enforceCallingOrSelfPermission(
11689                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11690        if (intentFilter.countActions() == 0) {
11691            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11692            return;
11693        }
11694        synchronized (mPackages) {
11695            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11696                    targetUserId, flags);
11697            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11698            mSettings.writePackageRestrictionsLPr(sourceUserId);
11699        }
11700    }
11701
11702    public void addCrossProfileIntentsForPackage(String packageName,
11703            int sourceUserId, int targetUserId) {
11704        mContext.enforceCallingOrSelfPermission(
11705                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11706        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11707        mSettings.writePackageRestrictionsLPr(sourceUserId);
11708    }
11709
11710    public void removeCrossProfileIntentsForPackage(String packageName,
11711            int sourceUserId, int targetUserId) {
11712        mContext.enforceCallingOrSelfPermission(
11713                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11714        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11715        mSettings.writePackageRestrictionsLPr(sourceUserId);
11716    }
11717
11718    @Override
11719    public void clearCrossProfileIntentFilters(int sourceUserId) {
11720        mContext.enforceCallingOrSelfPermission(
11721                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11722        synchronized (mPackages) {
11723            CrossProfileIntentResolver resolver =
11724                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11725            HashSet<CrossProfileIntentFilter> set =
11726                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11727            for (CrossProfileIntentFilter filter : set) {
11728                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11729                    resolver.removeFilter(filter);
11730                }
11731            }
11732            mSettings.writePackageRestrictionsLPr(sourceUserId);
11733        }
11734    }
11735
11736    @Override
11737    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11738        Intent intent = new Intent(Intent.ACTION_MAIN);
11739        intent.addCategory(Intent.CATEGORY_HOME);
11740
11741        final int callingUserId = UserHandle.getCallingUserId();
11742        List<ResolveInfo> list = queryIntentActivities(intent, null,
11743                PackageManager.GET_META_DATA, callingUserId);
11744        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11745                true, false, false, callingUserId);
11746
11747        allHomeCandidates.clear();
11748        if (list != null) {
11749            for (ResolveInfo ri : list) {
11750                allHomeCandidates.add(ri);
11751            }
11752        }
11753        return (preferred == null || preferred.activityInfo == null)
11754                ? null
11755                : new ComponentName(preferred.activityInfo.packageName,
11756                        preferred.activityInfo.name);
11757    }
11758
11759    @Override
11760    public void setApplicationEnabledSetting(String appPackageName,
11761            int newState, int flags, int userId, String callingPackage) {
11762        if (!sUserManager.exists(userId)) return;
11763        if (callingPackage == null) {
11764            callingPackage = Integer.toString(Binder.getCallingUid());
11765        }
11766        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11767    }
11768
11769    @Override
11770    public void setComponentEnabledSetting(ComponentName componentName,
11771            int newState, int flags, int userId) {
11772        if (!sUserManager.exists(userId)) return;
11773        setEnabledSetting(componentName.getPackageName(),
11774                componentName.getClassName(), newState, flags, userId, null);
11775    }
11776
11777    private void setEnabledSetting(final String packageName, String className, int newState,
11778            final int flags, int userId, String callingPackage) {
11779        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11780              || newState == COMPONENT_ENABLED_STATE_ENABLED
11781              || newState == COMPONENT_ENABLED_STATE_DISABLED
11782              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11783              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11784            throw new IllegalArgumentException("Invalid new component state: "
11785                    + newState);
11786        }
11787        PackageSetting pkgSetting;
11788        final int uid = Binder.getCallingUid();
11789        final int permission = mContext.checkCallingOrSelfPermission(
11790                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11791        enforceCrossUserPermission(uid, userId, false, "set enabled");
11792        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11793        boolean sendNow = false;
11794        boolean isApp = (className == null);
11795        String componentName = isApp ? packageName : className;
11796        int packageUid = -1;
11797        ArrayList<String> components;
11798
11799        // writer
11800        synchronized (mPackages) {
11801            pkgSetting = mSettings.mPackages.get(packageName);
11802            if (pkgSetting == null) {
11803                if (className == null) {
11804                    throw new IllegalArgumentException(
11805                            "Unknown package: " + packageName);
11806                }
11807                throw new IllegalArgumentException(
11808                        "Unknown component: " + packageName
11809                        + "/" + className);
11810            }
11811            // Allow root and verify that userId is not being specified by a different user
11812            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11813                throw new SecurityException(
11814                        "Permission Denial: attempt to change component state from pid="
11815                        + Binder.getCallingPid()
11816                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11817            }
11818            if (className == null) {
11819                // We're dealing with an application/package level state change
11820                if (pkgSetting.getEnabled(userId) == newState) {
11821                    // Nothing to do
11822                    return;
11823                }
11824                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11825                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11826                    // Don't care about who enables an app.
11827                    callingPackage = null;
11828                }
11829                pkgSetting.setEnabled(newState, userId, callingPackage);
11830                // pkgSetting.pkg.mSetEnabled = newState;
11831            } else {
11832                // We're dealing with a component level state change
11833                // First, verify that this is a valid class name.
11834                PackageParser.Package pkg = pkgSetting.pkg;
11835                if (pkg == null || !pkg.hasComponentClassName(className)) {
11836                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11837                        throw new IllegalArgumentException("Component class " + className
11838                                + " does not exist in " + packageName);
11839                    } else {
11840                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11841                                + className + " does not exist in " + packageName);
11842                    }
11843                }
11844                switch (newState) {
11845                case COMPONENT_ENABLED_STATE_ENABLED:
11846                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11847                        return;
11848                    }
11849                    break;
11850                case COMPONENT_ENABLED_STATE_DISABLED:
11851                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11852                        return;
11853                    }
11854                    break;
11855                case COMPONENT_ENABLED_STATE_DEFAULT:
11856                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11857                        return;
11858                    }
11859                    break;
11860                default:
11861                    Slog.e(TAG, "Invalid new component state: " + newState);
11862                    return;
11863                }
11864            }
11865            mSettings.writePackageRestrictionsLPr(userId);
11866            components = mPendingBroadcasts.get(userId, packageName);
11867            final boolean newPackage = components == null;
11868            if (newPackage) {
11869                components = new ArrayList<String>();
11870            }
11871            if (!components.contains(componentName)) {
11872                components.add(componentName);
11873            }
11874            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11875                sendNow = true;
11876                // Purge entry from pending broadcast list if another one exists already
11877                // since we are sending one right away.
11878                mPendingBroadcasts.remove(userId, packageName);
11879            } else {
11880                if (newPackage) {
11881                    mPendingBroadcasts.put(userId, packageName, components);
11882                }
11883                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11884                    // Schedule a message
11885                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11886                }
11887            }
11888        }
11889
11890        long callingId = Binder.clearCallingIdentity();
11891        try {
11892            if (sendNow) {
11893                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11894                sendPackageChangedBroadcast(packageName,
11895                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11896            }
11897        } finally {
11898            Binder.restoreCallingIdentity(callingId);
11899        }
11900    }
11901
11902    private void sendPackageChangedBroadcast(String packageName,
11903            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11904        if (DEBUG_INSTALL)
11905            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11906                    + componentNames);
11907        Bundle extras = new Bundle(4);
11908        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11909        String nameList[] = new String[componentNames.size()];
11910        componentNames.toArray(nameList);
11911        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11912        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11913        extras.putInt(Intent.EXTRA_UID, packageUid);
11914        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11915                new int[] {UserHandle.getUserId(packageUid)});
11916    }
11917
11918    @Override
11919    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11920        if (!sUserManager.exists(userId)) return;
11921        final int uid = Binder.getCallingUid();
11922        final int permission = mContext.checkCallingOrSelfPermission(
11923                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11924        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11925        enforceCrossUserPermission(uid, userId, true, "stop package");
11926        // writer
11927        synchronized (mPackages) {
11928            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11929                    uid, userId)) {
11930                scheduleWritePackageRestrictionsLocked(userId);
11931            }
11932        }
11933    }
11934
11935    @Override
11936    public String getInstallerPackageName(String packageName) {
11937        // reader
11938        synchronized (mPackages) {
11939            return mSettings.getInstallerPackageNameLPr(packageName);
11940        }
11941    }
11942
11943    @Override
11944    public int getApplicationEnabledSetting(String packageName, int userId) {
11945        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11946        int uid = Binder.getCallingUid();
11947        enforceCrossUserPermission(uid, userId, false, "get enabled");
11948        // reader
11949        synchronized (mPackages) {
11950            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11951        }
11952    }
11953
11954    @Override
11955    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11956        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11957        int uid = Binder.getCallingUid();
11958        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11959        // reader
11960        synchronized (mPackages) {
11961            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11962        }
11963    }
11964
11965    @Override
11966    public void enterSafeMode() {
11967        enforceSystemOrRoot("Only the system can request entering safe mode");
11968
11969        if (!mSystemReady) {
11970            mSafeMode = true;
11971        }
11972    }
11973
11974    @Override
11975    public void systemReady() {
11976        mSystemReady = true;
11977
11978        // Read the compatibilty setting when the system is ready.
11979        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11980                mContext.getContentResolver(),
11981                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11982        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11983        if (DEBUG_SETTINGS) {
11984            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11985        }
11986
11987        synchronized (mPackages) {
11988            // Verify that all of the preferred activity components actually
11989            // exist.  It is possible for applications to be updated and at
11990            // that point remove a previously declared activity component that
11991            // had been set as a preferred activity.  We try to clean this up
11992            // the next time we encounter that preferred activity, but it is
11993            // possible for the user flow to never be able to return to that
11994            // situation so here we do a sanity check to make sure we haven't
11995            // left any junk around.
11996            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11997            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11998                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11999                removed.clear();
12000                for (PreferredActivity pa : pir.filterSet()) {
12001                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12002                        removed.add(pa);
12003                    }
12004                }
12005                if (removed.size() > 0) {
12006                    for (int r=0; r<removed.size(); r++) {
12007                        PreferredActivity pa = removed.get(r);
12008                        Slog.w(TAG, "Removing dangling preferred activity: "
12009                                + pa.mPref.mComponent);
12010                        pir.removeFilter(pa);
12011                    }
12012                    mSettings.writePackageRestrictionsLPr(
12013                            mSettings.mPreferredActivities.keyAt(i));
12014                }
12015            }
12016        }
12017        sUserManager.systemReady();
12018    }
12019
12020    @Override
12021    public boolean isSafeMode() {
12022        return mSafeMode;
12023    }
12024
12025    @Override
12026    public boolean hasSystemUidErrors() {
12027        return mHasSystemUidErrors;
12028    }
12029
12030    static String arrayToString(int[] array) {
12031        StringBuffer buf = new StringBuffer(128);
12032        buf.append('[');
12033        if (array != null) {
12034            for (int i=0; i<array.length; i++) {
12035                if (i > 0) buf.append(", ");
12036                buf.append(array[i]);
12037            }
12038        }
12039        buf.append(']');
12040        return buf.toString();
12041    }
12042
12043    static class DumpState {
12044        public static final int DUMP_LIBS = 1 << 0;
12045
12046        public static final int DUMP_FEATURES = 1 << 1;
12047
12048        public static final int DUMP_RESOLVERS = 1 << 2;
12049
12050        public static final int DUMP_PERMISSIONS = 1 << 3;
12051
12052        public static final int DUMP_PACKAGES = 1 << 4;
12053
12054        public static final int DUMP_SHARED_USERS = 1 << 5;
12055
12056        public static final int DUMP_MESSAGES = 1 << 6;
12057
12058        public static final int DUMP_PROVIDERS = 1 << 7;
12059
12060        public static final int DUMP_VERIFIERS = 1 << 8;
12061
12062        public static final int DUMP_PREFERRED = 1 << 9;
12063
12064        public static final int DUMP_PREFERRED_XML = 1 << 10;
12065
12066        public static final int DUMP_KEYSETS = 1 << 11;
12067
12068        public static final int DUMP_VERSION = 1 << 12;
12069
12070        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12071
12072        private int mTypes;
12073
12074        private int mOptions;
12075
12076        private boolean mTitlePrinted;
12077
12078        private SharedUserSetting mSharedUser;
12079
12080        public boolean isDumping(int type) {
12081            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12082                return true;
12083            }
12084
12085            return (mTypes & type) != 0;
12086        }
12087
12088        public void setDump(int type) {
12089            mTypes |= type;
12090        }
12091
12092        public boolean isOptionEnabled(int option) {
12093            return (mOptions & option) != 0;
12094        }
12095
12096        public void setOptionEnabled(int option) {
12097            mOptions |= option;
12098        }
12099
12100        public boolean onTitlePrinted() {
12101            final boolean printed = mTitlePrinted;
12102            mTitlePrinted = true;
12103            return printed;
12104        }
12105
12106        public boolean getTitlePrinted() {
12107            return mTitlePrinted;
12108        }
12109
12110        public void setTitlePrinted(boolean enabled) {
12111            mTitlePrinted = enabled;
12112        }
12113
12114        public SharedUserSetting getSharedUser() {
12115            return mSharedUser;
12116        }
12117
12118        public void setSharedUser(SharedUserSetting user) {
12119            mSharedUser = user;
12120        }
12121    }
12122
12123    @Override
12124    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12125        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12126                != PackageManager.PERMISSION_GRANTED) {
12127            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12128                    + Binder.getCallingPid()
12129                    + ", uid=" + Binder.getCallingUid()
12130                    + " without permission "
12131                    + android.Manifest.permission.DUMP);
12132            return;
12133        }
12134
12135        DumpState dumpState = new DumpState();
12136        boolean fullPreferred = false;
12137        boolean checkin = false;
12138
12139        String packageName = null;
12140
12141        int opti = 0;
12142        while (opti < args.length) {
12143            String opt = args[opti];
12144            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12145                break;
12146            }
12147            opti++;
12148            if ("-a".equals(opt)) {
12149                // Right now we only know how to print all.
12150            } else if ("-h".equals(opt)) {
12151                pw.println("Package manager dump options:");
12152                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12153                pw.println("    --checkin: dump for a checkin");
12154                pw.println("    -f: print details of intent filters");
12155                pw.println("    -h: print this help");
12156                pw.println("  cmd may be one of:");
12157                pw.println("    l[ibraries]: list known shared libraries");
12158                pw.println("    f[ibraries]: list device features");
12159                pw.println("    k[eysets]: print known keysets");
12160                pw.println("    r[esolvers]: dump intent resolvers");
12161                pw.println("    perm[issions]: dump permissions");
12162                pw.println("    pref[erred]: print preferred package settings");
12163                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12164                pw.println("    prov[iders]: dump content providers");
12165                pw.println("    p[ackages]: dump installed packages");
12166                pw.println("    s[hared-users]: dump shared user IDs");
12167                pw.println("    m[essages]: print collected runtime messages");
12168                pw.println("    v[erifiers]: print package verifier info");
12169                pw.println("    version: print database version info");
12170                pw.println("    write: write current settings now");
12171                pw.println("    <package.name>: info about given package");
12172                return;
12173            } else if ("--checkin".equals(opt)) {
12174                checkin = true;
12175            } else if ("-f".equals(opt)) {
12176                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12177            } else {
12178                pw.println("Unknown argument: " + opt + "; use -h for help");
12179            }
12180        }
12181
12182        // Is the caller requesting to dump a particular piece of data?
12183        if (opti < args.length) {
12184            String cmd = args[opti];
12185            opti++;
12186            // Is this a package name?
12187            if ("android".equals(cmd) || cmd.contains(".")) {
12188                packageName = cmd;
12189                // When dumping a single package, we always dump all of its
12190                // filter information since the amount of data will be reasonable.
12191                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12192            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12193                dumpState.setDump(DumpState.DUMP_LIBS);
12194            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12195                dumpState.setDump(DumpState.DUMP_FEATURES);
12196            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12197                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12198            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12199                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12200            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12201                dumpState.setDump(DumpState.DUMP_PREFERRED);
12202            } else if ("preferred-xml".equals(cmd)) {
12203                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12204                if (opti < args.length && "--full".equals(args[opti])) {
12205                    fullPreferred = true;
12206                    opti++;
12207                }
12208            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12209                dumpState.setDump(DumpState.DUMP_PACKAGES);
12210            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12212            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12213                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12214            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12215                dumpState.setDump(DumpState.DUMP_MESSAGES);
12216            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12217                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12218            } else if ("version".equals(cmd)) {
12219                dumpState.setDump(DumpState.DUMP_VERSION);
12220            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12221                dumpState.setDump(DumpState.DUMP_KEYSETS);
12222            } else if ("write".equals(cmd)) {
12223                synchronized (mPackages) {
12224                    mSettings.writeLPr();
12225                    pw.println("Settings written.");
12226                    return;
12227                }
12228            }
12229        }
12230
12231        if (checkin) {
12232            pw.println("vers,1");
12233        }
12234
12235        // reader
12236        synchronized (mPackages) {
12237            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12238                if (!checkin) {
12239                    if (dumpState.onTitlePrinted())
12240                        pw.println();
12241                    pw.println("Database versions:");
12242                    pw.print("  SDK Version:");
12243                    pw.print(" internal=");
12244                    pw.print(mSettings.mInternalSdkPlatform);
12245                    pw.print(" external=");
12246                    pw.println(mSettings.mExternalSdkPlatform);
12247                    pw.print("  DB Version:");
12248                    pw.print(" internal=");
12249                    pw.print(mSettings.mInternalDatabaseVersion);
12250                    pw.print(" external=");
12251                    pw.println(mSettings.mExternalDatabaseVersion);
12252                }
12253            }
12254
12255            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12256                if (!checkin) {
12257                    if (dumpState.onTitlePrinted())
12258                        pw.println();
12259                    pw.println("Verifiers:");
12260                    pw.print("  Required: ");
12261                    pw.print(mRequiredVerifierPackage);
12262                    pw.print(" (uid=");
12263                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12264                    pw.println(")");
12265                } else if (mRequiredVerifierPackage != null) {
12266                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12267                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12268                }
12269            }
12270
12271            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12272                boolean printedHeader = false;
12273                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12274                while (it.hasNext()) {
12275                    String name = it.next();
12276                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12277                    if (!checkin) {
12278                        if (!printedHeader) {
12279                            if (dumpState.onTitlePrinted())
12280                                pw.println();
12281                            pw.println("Libraries:");
12282                            printedHeader = true;
12283                        }
12284                        pw.print("  ");
12285                    } else {
12286                        pw.print("lib,");
12287                    }
12288                    pw.print(name);
12289                    if (!checkin) {
12290                        pw.print(" -> ");
12291                    }
12292                    if (ent.path != null) {
12293                        if (!checkin) {
12294                            pw.print("(jar) ");
12295                            pw.print(ent.path);
12296                        } else {
12297                            pw.print(",jar,");
12298                            pw.print(ent.path);
12299                        }
12300                    } else {
12301                        if (!checkin) {
12302                            pw.print("(apk) ");
12303                            pw.print(ent.apk);
12304                        } else {
12305                            pw.print(",apk,");
12306                            pw.print(ent.apk);
12307                        }
12308                    }
12309                    pw.println();
12310                }
12311            }
12312
12313            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12314                if (dumpState.onTitlePrinted())
12315                    pw.println();
12316                if (!checkin) {
12317                    pw.println("Features:");
12318                }
12319                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12320                while (it.hasNext()) {
12321                    String name = it.next();
12322                    if (!checkin) {
12323                        pw.print("  ");
12324                    } else {
12325                        pw.print("feat,");
12326                    }
12327                    pw.println(name);
12328                }
12329            }
12330
12331            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12332                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12333                        : "Activity Resolver Table:", "  ", packageName,
12334                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12335                    dumpState.setTitlePrinted(true);
12336                }
12337                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12338                        : "Receiver Resolver Table:", "  ", packageName,
12339                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12340                    dumpState.setTitlePrinted(true);
12341                }
12342                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12343                        : "Service Resolver Table:", "  ", packageName,
12344                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12345                    dumpState.setTitlePrinted(true);
12346                }
12347                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12348                        : "Provider Resolver Table:", "  ", packageName,
12349                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12350                    dumpState.setTitlePrinted(true);
12351                }
12352            }
12353
12354            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12355                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12356                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12357                    int user = mSettings.mPreferredActivities.keyAt(i);
12358                    if (pir.dump(pw,
12359                            dumpState.getTitlePrinted()
12360                                ? "\nPreferred Activities User " + user + ":"
12361                                : "Preferred Activities User " + user + ":", "  ",
12362                            packageName, true)) {
12363                        dumpState.setTitlePrinted(true);
12364                    }
12365                }
12366            }
12367
12368            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12369                pw.flush();
12370                FileOutputStream fout = new FileOutputStream(fd);
12371                BufferedOutputStream str = new BufferedOutputStream(fout);
12372                XmlSerializer serializer = new FastXmlSerializer();
12373                try {
12374                    serializer.setOutput(str, "utf-8");
12375                    serializer.startDocument(null, true);
12376                    serializer.setFeature(
12377                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12378                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12379                    serializer.endDocument();
12380                    serializer.flush();
12381                } catch (IllegalArgumentException e) {
12382                    pw.println("Failed writing: " + e);
12383                } catch (IllegalStateException e) {
12384                    pw.println("Failed writing: " + e);
12385                } catch (IOException e) {
12386                    pw.println("Failed writing: " + e);
12387                }
12388            }
12389
12390            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12391                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12392            }
12393
12394            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12395                boolean printedSomething = false;
12396                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12397                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12398                        continue;
12399                    }
12400                    if (!printedSomething) {
12401                        if (dumpState.onTitlePrinted())
12402                            pw.println();
12403                        pw.println("Registered ContentProviders:");
12404                        printedSomething = true;
12405                    }
12406                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12407                    pw.print("    "); pw.println(p.toString());
12408                }
12409                printedSomething = false;
12410                for (Map.Entry<String, PackageParser.Provider> entry :
12411                        mProvidersByAuthority.entrySet()) {
12412                    PackageParser.Provider p = entry.getValue();
12413                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12414                        continue;
12415                    }
12416                    if (!printedSomething) {
12417                        if (dumpState.onTitlePrinted())
12418                            pw.println();
12419                        pw.println("ContentProvider Authorities:");
12420                        printedSomething = true;
12421                    }
12422                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12423                    pw.print("    "); pw.println(p.toString());
12424                    if (p.info != null && p.info.applicationInfo != null) {
12425                        final String appInfo = p.info.applicationInfo.toString();
12426                        pw.print("      applicationInfo="); pw.println(appInfo);
12427                    }
12428                }
12429            }
12430
12431            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12432                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12433            }
12434
12435            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12436                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12437            }
12438
12439            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12440                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12441            }
12442
12443            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12444                if (dumpState.onTitlePrinted())
12445                    pw.println();
12446                mSettings.dumpReadMessagesLPr(pw, dumpState);
12447
12448                pw.println();
12449                pw.println("Package warning messages:");
12450                final File fname = getSettingsProblemFile();
12451                FileInputStream in = null;
12452                try {
12453                    in = new FileInputStream(fname);
12454                    final int avail = in.available();
12455                    final byte[] data = new byte[avail];
12456                    in.read(data);
12457                    pw.print(new String(data));
12458                } catch (FileNotFoundException e) {
12459                } catch (IOException e) {
12460                } finally {
12461                    if (in != null) {
12462                        try {
12463                            in.close();
12464                        } catch (IOException e) {
12465                        }
12466                    }
12467                }
12468            }
12469        }
12470    }
12471
12472    // ------- apps on sdcard specific code -------
12473    static final boolean DEBUG_SD_INSTALL = false;
12474
12475    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12476
12477    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12478
12479    private boolean mMediaMounted = false;
12480
12481    private String getEncryptKey() {
12482        try {
12483            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12484                    SD_ENCRYPTION_KEYSTORE_NAME);
12485            if (sdEncKey == null) {
12486                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12487                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12488                if (sdEncKey == null) {
12489                    Slog.e(TAG, "Failed to create encryption keys");
12490                    return null;
12491                }
12492            }
12493            return sdEncKey;
12494        } catch (NoSuchAlgorithmException nsae) {
12495            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12496            return null;
12497        } catch (IOException ioe) {
12498            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12499            return null;
12500        }
12501
12502    }
12503
12504    /* package */static String getTempContainerId() {
12505        int tmpIdx = 1;
12506        String list[] = PackageHelper.getSecureContainerList();
12507        if (list != null) {
12508            for (final String name : list) {
12509                // Ignore null and non-temporary container entries
12510                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12511                    continue;
12512                }
12513
12514                String subStr = name.substring(mTempContainerPrefix.length());
12515                try {
12516                    int cid = Integer.parseInt(subStr);
12517                    if (cid >= tmpIdx) {
12518                        tmpIdx = cid + 1;
12519                    }
12520                } catch (NumberFormatException e) {
12521                }
12522            }
12523        }
12524        return mTempContainerPrefix + tmpIdx;
12525    }
12526
12527    /*
12528     * Update media status on PackageManager.
12529     */
12530    @Override
12531    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12532        int callingUid = Binder.getCallingUid();
12533        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12534            throw new SecurityException("Media status can only be updated by the system");
12535        }
12536        // reader; this apparently protects mMediaMounted, but should probably
12537        // be a different lock in that case.
12538        synchronized (mPackages) {
12539            Log.i(TAG, "Updating external media status from "
12540                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12541                    + (mediaStatus ? "mounted" : "unmounted"));
12542            if (DEBUG_SD_INSTALL)
12543                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12544                        + ", mMediaMounted=" + mMediaMounted);
12545            if (mediaStatus == mMediaMounted) {
12546                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12547                        : 0, -1);
12548                mHandler.sendMessage(msg);
12549                return;
12550            }
12551            mMediaMounted = mediaStatus;
12552        }
12553        // Queue up an async operation since the package installation may take a
12554        // little while.
12555        mHandler.post(new Runnable() {
12556            public void run() {
12557                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12558            }
12559        });
12560    }
12561
12562    /**
12563     * Called by MountService when the initial ASECs to scan are available.
12564     * Should block until all the ASEC containers are finished being scanned.
12565     */
12566    public void scanAvailableAsecs() {
12567        updateExternalMediaStatusInner(true, false, false);
12568        if (mShouldRestoreconData) {
12569            SELinuxMMAC.setRestoreconDone();
12570            mShouldRestoreconData = false;
12571        }
12572    }
12573
12574    /*
12575     * Collect information of applications on external media, map them against
12576     * existing containers and update information based on current mount status.
12577     * Please note that we always have to report status if reportStatus has been
12578     * set to true especially when unloading packages.
12579     */
12580    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12581            boolean externalStorage) {
12582        // Collection of uids
12583        int uidArr[] = null;
12584        // Collection of stale containers
12585        HashSet<String> removeCids = new HashSet<String>();
12586        // Collection of packages on external media with valid containers.
12587        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12588        // Get list of secure containers.
12589        final String list[] = PackageHelper.getSecureContainerList();
12590        if (list == null || list.length == 0) {
12591            Log.i(TAG, "No secure containers on sdcard");
12592        } else {
12593            // Process list of secure containers and categorize them
12594            // as active or stale based on their package internal state.
12595            int uidList[] = new int[list.length];
12596            int num = 0;
12597            // reader
12598            synchronized (mPackages) {
12599                for (String cid : list) {
12600                    if (DEBUG_SD_INSTALL)
12601                        Log.i(TAG, "Processing container " + cid);
12602                    String pkgName = getAsecPackageName(cid);
12603                    if (pkgName == null) {
12604                        if (DEBUG_SD_INSTALL)
12605                            Log.i(TAG, "Container : " + cid + " stale");
12606                        removeCids.add(cid);
12607                        continue;
12608                    }
12609                    if (DEBUG_SD_INSTALL)
12610                        Log.i(TAG, "Looking for pkg : " + pkgName);
12611
12612                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12613                    if (ps == null) {
12614                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12615                        removeCids.add(cid);
12616                        continue;
12617                    }
12618
12619                    /*
12620                     * Skip packages that are not external if we're unmounting
12621                     * external storage.
12622                     */
12623                    if (externalStorage && !isMounted && !isExternal(ps)) {
12624                        continue;
12625                    }
12626
12627                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12628                            getAppInstructionSetFromSettings(ps),
12629                            isForwardLocked(ps));
12630                    // The package status is changed only if the code path
12631                    // matches between settings and the container id.
12632                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12633                        if (DEBUG_SD_INSTALL) {
12634                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12635                                    + " at code path: " + ps.codePathString);
12636                        }
12637
12638                        // We do have a valid package installed on sdcard
12639                        processCids.put(args, ps.codePathString);
12640                        final int uid = ps.appId;
12641                        if (uid != -1) {
12642                            uidList[num++] = uid;
12643                        }
12644                    } else {
12645                        Log.i(TAG, "Deleting stale container for " + cid);
12646                        removeCids.add(cid);
12647                    }
12648                }
12649            }
12650
12651            if (num > 0) {
12652                // Sort uid list
12653                Arrays.sort(uidList, 0, num);
12654                // Throw away duplicates
12655                uidArr = new int[num];
12656                uidArr[0] = uidList[0];
12657                int di = 0;
12658                for (int i = 1; i < num; i++) {
12659                    if (uidList[i - 1] != uidList[i]) {
12660                        uidArr[di++] = uidList[i];
12661                    }
12662                }
12663            }
12664        }
12665        // Process packages with valid entries.
12666        if (isMounted) {
12667            if (DEBUG_SD_INSTALL)
12668                Log.i(TAG, "Loading packages");
12669            loadMediaPackages(processCids, uidArr, removeCids);
12670            startCleaningPackages();
12671        } else {
12672            if (DEBUG_SD_INSTALL)
12673                Log.i(TAG, "Unloading packages");
12674            unloadMediaPackages(processCids, uidArr, reportStatus);
12675        }
12676    }
12677
12678   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12679           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12680        int size = pkgList.size();
12681        if (size > 0) {
12682            // Send broadcasts here
12683            Bundle extras = new Bundle();
12684            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12685                    .toArray(new String[size]));
12686            if (uidArr != null) {
12687                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12688            }
12689            if (replacing) {
12690                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12691            }
12692            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12693                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12694            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12695        }
12696    }
12697
12698   /*
12699     * Look at potentially valid container ids from processCids If package
12700     * information doesn't match the one on record or package scanning fails,
12701     * the cid is added to list of removeCids. We currently don't delete stale
12702     * containers.
12703     */
12704   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12705            HashSet<String> removeCids) {
12706        ArrayList<String> pkgList = new ArrayList<String>();
12707        Set<AsecInstallArgs> keys = processCids.keySet();
12708        boolean doGc = false;
12709        for (AsecInstallArgs args : keys) {
12710            String codePath = processCids.get(args);
12711            if (DEBUG_SD_INSTALL)
12712                Log.i(TAG, "Loading container : " + args.cid);
12713            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12714            try {
12715                // Make sure there are no container errors first.
12716                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12717                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12718                            + " when installing from sdcard");
12719                    continue;
12720                }
12721                // Check code path here.
12722                if (codePath == null || !codePath.equals(args.getCodePath())) {
12723                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12724                            + " does not match one in settings " + codePath);
12725                    continue;
12726                }
12727                // Parse package
12728                int parseFlags = mDefParseFlags;
12729                if (args.isExternal()) {
12730                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12731                }
12732                if (args.isFwdLocked()) {
12733                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12734                }
12735
12736                doGc = true;
12737                synchronized (mInstallLock) {
12738                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12739                            0, 0, null, null);
12740                    // Scan the package
12741                    if (pkg != null) {
12742                        /*
12743                         * TODO why is the lock being held? doPostInstall is
12744                         * called in other places without the lock. This needs
12745                         * to be straightened out.
12746                         */
12747                        // writer
12748                        synchronized (mPackages) {
12749                            retCode = PackageManager.INSTALL_SUCCEEDED;
12750                            pkgList.add(pkg.packageName);
12751                            // Post process args
12752                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12753                                    pkg.applicationInfo.uid);
12754                        }
12755                    } else {
12756                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12757                    }
12758                }
12759
12760            } finally {
12761                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12762                    // Don't destroy container here. Wait till gc clears things
12763                    // up.
12764                    removeCids.add(args.cid);
12765                }
12766            }
12767        }
12768        // writer
12769        synchronized (mPackages) {
12770            // If the platform SDK has changed since the last time we booted,
12771            // we need to re-grant app permission to catch any new ones that
12772            // appear. This is really a hack, and means that apps can in some
12773            // cases get permissions that the user didn't initially explicitly
12774            // allow... it would be nice to have some better way to handle
12775            // this situation.
12776            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12777            if (regrantPermissions)
12778                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12779                        + mSdkVersion + "; regranting permissions for external storage");
12780            mSettings.mExternalSdkPlatform = mSdkVersion;
12781
12782            // Make sure group IDs have been assigned, and any permission
12783            // changes in other apps are accounted for
12784            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12785                    | (regrantPermissions
12786                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12787                            : 0));
12788
12789            mSettings.updateExternalDatabaseVersion();
12790
12791            // can downgrade to reader
12792            // Persist settings
12793            mSettings.writeLPr();
12794        }
12795        // Send a broadcast to let everyone know we are done processing
12796        if (pkgList.size() > 0) {
12797            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12798        }
12799        // Force gc to avoid any stale parser references that we might have.
12800        if (doGc) {
12801            Runtime.getRuntime().gc();
12802        }
12803        // List stale containers and destroy stale temporary containers.
12804        if (removeCids != null) {
12805            for (String cid : removeCids) {
12806                if (cid.startsWith(mTempContainerPrefix)) {
12807                    Log.i(TAG, "Destroying stale temporary container " + cid);
12808                    PackageHelper.destroySdDir(cid);
12809                } else {
12810                    Log.w(TAG, "Container " + cid + " is stale");
12811               }
12812           }
12813        }
12814    }
12815
12816   /*
12817     * Utility method to unload a list of specified containers
12818     */
12819    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12820        // Just unmount all valid containers.
12821        for (AsecInstallArgs arg : cidArgs) {
12822            synchronized (mInstallLock) {
12823                arg.doPostDeleteLI(false);
12824           }
12825       }
12826   }
12827
12828    /*
12829     * Unload packages mounted on external media. This involves deleting package
12830     * data from internal structures, sending broadcasts about diabled packages,
12831     * gc'ing to free up references, unmounting all secure containers
12832     * corresponding to packages on external media, and posting a
12833     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12834     * that we always have to post this message if status has been requested no
12835     * matter what.
12836     */
12837    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12838            final boolean reportStatus) {
12839        if (DEBUG_SD_INSTALL)
12840            Log.i(TAG, "unloading media packages");
12841        ArrayList<String> pkgList = new ArrayList<String>();
12842        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12843        final Set<AsecInstallArgs> keys = processCids.keySet();
12844        for (AsecInstallArgs args : keys) {
12845            String pkgName = args.getPackageName();
12846            if (DEBUG_SD_INSTALL)
12847                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12848            // Delete package internally
12849            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12850            synchronized (mInstallLock) {
12851                boolean res = deletePackageLI(pkgName, null, false, null, null,
12852                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12853                if (res) {
12854                    pkgList.add(pkgName);
12855                } else {
12856                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12857                    failedList.add(args);
12858                }
12859            }
12860        }
12861
12862        // reader
12863        synchronized (mPackages) {
12864            // We didn't update the settings after removing each package;
12865            // write them now for all packages.
12866            mSettings.writeLPr();
12867        }
12868
12869        // We have to absolutely send UPDATED_MEDIA_STATUS only
12870        // after confirming that all the receivers processed the ordered
12871        // broadcast when packages get disabled, force a gc to clean things up.
12872        // and unload all the containers.
12873        if (pkgList.size() > 0) {
12874            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12875                    new IIntentReceiver.Stub() {
12876                public void performReceive(Intent intent, int resultCode, String data,
12877                        Bundle extras, boolean ordered, boolean sticky,
12878                        int sendingUser) throws RemoteException {
12879                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12880                            reportStatus ? 1 : 0, 1, keys);
12881                    mHandler.sendMessage(msg);
12882                }
12883            });
12884        } else {
12885            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12886                    keys);
12887            mHandler.sendMessage(msg);
12888        }
12889    }
12890
12891    /** Binder call */
12892    @Override
12893    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12894            final int flags) {
12895        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12896        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12897        int returnCode = PackageManager.MOVE_SUCCEEDED;
12898        int currFlags = 0;
12899        int newFlags = 0;
12900        // reader
12901        synchronized (mPackages) {
12902            PackageParser.Package pkg = mPackages.get(packageName);
12903            if (pkg == null) {
12904                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12905            } else {
12906                // Disable moving fwd locked apps and system packages
12907                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12908                    Slog.w(TAG, "Cannot move system application");
12909                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12910                } else if (pkg.mOperationPending) {
12911                    Slog.w(TAG, "Attempt to move package which has pending operations");
12912                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12913                } else {
12914                    // Find install location first
12915                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12916                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12917                        Slog.w(TAG, "Ambigous flags specified for move location.");
12918                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12919                    } else {
12920                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12921                                : PackageManager.INSTALL_INTERNAL;
12922                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12923                                : PackageManager.INSTALL_INTERNAL;
12924
12925                        if (newFlags == currFlags) {
12926                            Slog.w(TAG, "No move required. Trying to move to same location");
12927                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12928                        } else {
12929                            if (isForwardLocked(pkg)) {
12930                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12931                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12932                            }
12933                        }
12934                    }
12935                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12936                        pkg.mOperationPending = true;
12937                    }
12938                }
12939            }
12940
12941            /*
12942             * TODO this next block probably shouldn't be inside the lock. We
12943             * can't guarantee these won't change after this is fired off
12944             * anyway.
12945             */
12946            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12947                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12948                        null, -1, user),
12949                        returnCode);
12950            } else {
12951                Message msg = mHandler.obtainMessage(INIT_COPY);
12952                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12953                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12954                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12955                        instructionSet);
12956                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12957                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12958                msg.obj = mp;
12959                mHandler.sendMessage(msg);
12960            }
12961        }
12962    }
12963
12964    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12965        // Queue up an async operation since the package deletion may take a
12966        // little while.
12967        mHandler.post(new Runnable() {
12968            public void run() {
12969                // TODO fix this; this does nothing.
12970                mHandler.removeCallbacks(this);
12971                int returnCode = currentStatus;
12972                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12973                    int uidArr[] = null;
12974                    ArrayList<String> pkgList = null;
12975                    synchronized (mPackages) {
12976                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12977                        if (pkg == null) {
12978                            Slog.w(TAG, " Package " + mp.packageName
12979                                    + " doesn't exist. Aborting move");
12980                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12981                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12982                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12983                                    + mp.srcArgs.getCodePath() + " to "
12984                                    + pkg.applicationInfo.sourceDir
12985                                    + " Aborting move and returning error");
12986                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12987                        } else {
12988                            uidArr = new int[] {
12989                                pkg.applicationInfo.uid
12990                            };
12991                            pkgList = new ArrayList<String>();
12992                            pkgList.add(mp.packageName);
12993                        }
12994                    }
12995                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12996                        // Send resources unavailable broadcast
12997                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12998                        // Update package code and resource paths
12999                        synchronized (mInstallLock) {
13000                            synchronized (mPackages) {
13001                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13002                                // Recheck for package again.
13003                                if (pkg == null) {
13004                                    Slog.w(TAG, " Package " + mp.packageName
13005                                            + " doesn't exist. Aborting move");
13006                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13007                                } else if (!mp.srcArgs.getCodePath().equals(
13008                                        pkg.applicationInfo.sourceDir)) {
13009                                    Slog.w(TAG, "Package " + mp.packageName
13010                                            + " code path changed from " + mp.srcArgs.getCodePath()
13011                                            + " to " + pkg.applicationInfo.sourceDir
13012                                            + " Aborting move and returning error");
13013                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13014                                } else {
13015                                    final String oldCodePath = pkg.codePath;
13016                                    final String newCodePath = mp.targetArgs.getCodePath();
13017                                    final String newResPath = mp.targetArgs.getResourcePath();
13018                                    final String newNativePath = mp.targetArgs
13019                                            .getNativeLibraryPath();
13020
13021                                    final File newNativeDir = new File(newNativePath);
13022
13023                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13024                                        // NOTE: We do not report any errors from the APK scan and library
13025                                        // copy at this point.
13026                                        NativeLibraryHelper.ApkHandle handle =
13027                                                new NativeLibraryHelper.ApkHandle(newCodePath);
13028                                        final int abi = NativeLibraryHelper.findSupportedAbi(
13029                                                handle, Build.SUPPORTED_ABIS);
13030                                        if (abi >= 0) {
13031                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13032                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13033                                        }
13034                                        handle.close();
13035                                    }
13036                                    final int[] users = sUserManager.getUserIds();
13037                                    for (int user : users) {
13038                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13039                                                newNativePath, user) < 0) {
13040                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13041                                        }
13042                                    }
13043
13044                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13045                                        pkg.codePath = newCodePath;
13046                                        // Move dex files around
13047                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13048                                            // Moving of dex files failed. Set
13049                                            // error code and abort move.
13050                                            pkg.codePath = oldCodePath;
13051                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13052                                        }
13053                                    }
13054
13055                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13056                                        pkg.applicationInfo.sourceDir = newCodePath;
13057                                        pkg.applicationInfo.publicSourceDir = newResPath;
13058                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
13059                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13060                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
13061                                        ps.codePathString = ps.codePath.getPath();
13062                                        ps.resourcePath = new File(
13063                                                pkg.applicationInfo.publicSourceDir);
13064                                        ps.resourcePathString = ps.resourcePath.getPath();
13065                                        ps.nativeLibraryPathString = newNativePath;
13066                                        // Set the application info flag
13067                                        // correctly.
13068                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13069                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13070                                        } else {
13071                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13072                                        }
13073                                        ps.setFlags(pkg.applicationInfo.flags);
13074                                        mAppDirs.remove(oldCodePath);
13075                                        mAppDirs.put(newCodePath, pkg);
13076                                        // Persist settings
13077                                        mSettings.writeLPr();
13078                                    }
13079                                }
13080                            }
13081                        }
13082                        // Send resources available broadcast
13083                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13084                    }
13085                }
13086                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13087                    // Clean up failed installation
13088                    if (mp.targetArgs != null) {
13089                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13090                                -1);
13091                    }
13092                } else {
13093                    // Force a gc to clear things up.
13094                    Runtime.getRuntime().gc();
13095                    // Delete older code
13096                    synchronized (mInstallLock) {
13097                        mp.srcArgs.doPostDeleteLI(true);
13098                    }
13099                }
13100
13101                // Allow more operations on this file if we didn't fail because
13102                // an operation was already pending for this package.
13103                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13104                    synchronized (mPackages) {
13105                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13106                        if (pkg != null) {
13107                            pkg.mOperationPending = false;
13108                       }
13109                   }
13110                }
13111
13112                IPackageMoveObserver observer = mp.observer;
13113                if (observer != null) {
13114                    try {
13115                        observer.packageMoved(mp.packageName, returnCode);
13116                    } catch (RemoteException e) {
13117                        Log.i(TAG, "Observer no longer exists.");
13118                    }
13119                }
13120            }
13121        });
13122    }
13123
13124    @Override
13125    public boolean setInstallLocation(int loc) {
13126        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13127                null);
13128        if (getInstallLocation() == loc) {
13129            return true;
13130        }
13131        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13132                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13133            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13134                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13135            return true;
13136        }
13137        return false;
13138   }
13139
13140    @Override
13141    public int getInstallLocation() {
13142        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13143                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13144                PackageHelper.APP_INSTALL_AUTO);
13145    }
13146
13147    /** Called by UserManagerService */
13148    void cleanUpUserLILPw(int userHandle) {
13149        mDirtyUsers.remove(userHandle);
13150        mSettings.removeUserLPr(userHandle);
13151        mPendingBroadcasts.remove(userHandle);
13152        if (mInstaller != null) {
13153            // Technically, we shouldn't be doing this with the package lock
13154            // held.  However, this is very rare, and there is already so much
13155            // other disk I/O going on, that we'll let it slide for now.
13156            mInstaller.removeUserDataDirs(userHandle);
13157        }
13158    }
13159
13160    /** Called by UserManagerService */
13161    void createNewUserLILPw(int userHandle, File path) {
13162        if (mInstaller != null) {
13163            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13164        }
13165    }
13166
13167    @Override
13168    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13169        mContext.enforceCallingOrSelfPermission(
13170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13171                "Only package verification agents can read the verifier device identity");
13172
13173        synchronized (mPackages) {
13174            return mSettings.getVerifierDeviceIdentityLPw();
13175        }
13176    }
13177
13178    @Override
13179    public void setPermissionEnforced(String permission, boolean enforced) {
13180        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13181        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13182            synchronized (mPackages) {
13183                if (mSettings.mReadExternalStorageEnforced == null
13184                        || mSettings.mReadExternalStorageEnforced != enforced) {
13185                    mSettings.mReadExternalStorageEnforced = enforced;
13186                    mSettings.writeLPr();
13187                }
13188            }
13189            // kill any non-foreground processes so we restart them and
13190            // grant/revoke the GID.
13191            final IActivityManager am = ActivityManagerNative.getDefault();
13192            if (am != null) {
13193                final long token = Binder.clearCallingIdentity();
13194                try {
13195                    am.killProcessesBelowForeground("setPermissionEnforcement");
13196                } catch (RemoteException e) {
13197                } finally {
13198                    Binder.restoreCallingIdentity(token);
13199                }
13200            }
13201        } else {
13202            throw new IllegalArgumentException("No selective enforcement for " + permission);
13203        }
13204    }
13205
13206    @Override
13207    @Deprecated
13208    public boolean isPermissionEnforced(String permission) {
13209        return true;
13210    }
13211
13212    @Override
13213    public boolean isStorageLow() {
13214        final long token = Binder.clearCallingIdentity();
13215        try {
13216            final DeviceStorageMonitorInternal
13217                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13218            if (dsm != null) {
13219                return dsm.isMemoryLow();
13220            } else {
13221                return false;
13222            }
13223        } finally {
13224            Binder.restoreCallingIdentity(token);
13225        }
13226    }
13227
13228    @Override
13229    public IPackageInstaller getPackageInstaller() {
13230        return mInstallerService;
13231    }
13232}
13233