PackageManagerService.java revision a8e65fd82a323e6065ae9ae6cc8eaa130d3c1efd
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.system.OsConstants.S_IRWXU;
27import static android.system.OsConstants.S_IRGRP;
28import static android.system.OsConstants.S_IXGRP;
29import static android.system.OsConstants.S_IROTH;
30import static android.system.OsConstants.S_IXOTH;
31import static com.android.internal.util.ArrayUtils.appendInt;
32import static com.android.internal.util.ArrayUtils.removeInt;
33
34import com.android.internal.app.IMediaContainerService;
35import com.android.internal.app.ResolverActivity;
36import com.android.internal.content.NativeLibraryHelper;
37import com.android.internal.content.PackageHelper;
38import com.android.internal.util.FastPrintWriter;
39import com.android.internal.util.FastXmlSerializer;
40import com.android.internal.util.XmlUtils;
41import com.android.server.EventLogTags;
42import com.android.server.IntentResolver;
43import com.android.server.ServiceThread;
44
45import com.android.server.LocalServices;
46import com.android.server.Watchdog;
47import org.xmlpull.v1.XmlPullParser;
48import org.xmlpull.v1.XmlPullParserException;
49import org.xmlpull.v1.XmlSerializer;
50
51import android.app.ActivityManager;
52import android.app.ActivityManagerNative;
53import android.app.IActivityManager;
54import android.app.admin.IDevicePolicyManager;
55import android.app.backup.IBackupManager;
56import android.content.BroadcastReceiver;
57import android.content.ComponentName;
58import android.content.Context;
59import android.content.IIntentReceiver;
60import android.content.Intent;
61import android.content.IntentFilter;
62import android.content.IntentSender;
63import android.content.IntentSender.SendIntentException;
64import android.content.ServiceConnection;
65import android.content.pm.ActivityInfo;
66import android.content.pm.ApplicationInfo;
67import android.content.pm.ContainerEncryptionParams;
68import android.content.pm.FeatureInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageDeleteObserver;
71import android.content.pm.IPackageInstallObserver;
72import android.content.pm.IPackageInstallObserver2;
73import android.content.pm.IPackageManager;
74import android.content.pm.IPackageMoveObserver;
75import android.content.pm.IPackageStatsObserver;
76import android.content.pm.InstrumentationInfo;
77import android.content.pm.ManifestDigest;
78import android.content.pm.PackageCleanItem;
79import android.content.pm.PackageInfo;
80import android.content.pm.PackageInfoLite;
81import android.content.pm.PackageManager;
82import android.content.pm.PackageParser;
83import android.content.pm.PackageParser.ActivityIntentInfo;
84import android.content.pm.PackageStats;
85import android.content.pm.PackageUserState;
86import android.content.pm.ParceledListSlice;
87import android.content.pm.PermissionGroupInfo;
88import android.content.pm.PermissionInfo;
89import android.content.pm.ProviderInfo;
90import android.content.pm.ResolveInfo;
91import android.content.pm.ServiceInfo;
92import android.content.pm.Signature;
93import android.content.pm.VerificationParams;
94import android.content.pm.VerifierDeviceIdentity;
95import android.content.pm.VerifierInfo;
96import android.content.res.Resources;
97import android.hardware.display.DisplayManager;
98import android.net.Uri;
99import android.os.Binder;
100import android.os.Build;
101import android.os.Bundle;
102import android.os.Environment;
103import android.os.Environment.UserEnvironment;
104import android.os.FileObserver;
105import android.os.FileUtils;
106import android.os.Handler;
107import android.os.IBinder;
108import android.os.Looper;
109import android.os.Message;
110import android.os.Parcel;
111import android.os.ParcelFileDescriptor;
112import android.os.Process;
113import android.os.RemoteException;
114import android.os.SELinux;
115import android.os.ServiceManager;
116import android.os.SystemClock;
117import android.os.SystemProperties;
118import android.os.UserHandle;
119import android.os.UserManager;
120import android.security.KeyStore;
121import android.security.SystemKeyStore;
122import android.system.ErrnoException;
123import android.system.Os;
124import android.system.StructStat;
125import android.text.TextUtils;
126import android.util.DisplayMetrics;
127import android.util.EventLog;
128import android.util.Log;
129import android.util.LogPrinter;
130import android.util.PrintStreamPrinter;
131import android.util.Slog;
132import android.util.SparseArray;
133import android.util.Xml;
134import android.view.Display;
135
136import java.io.BufferedOutputStream;
137import java.io.File;
138import java.io.FileDescriptor;
139import java.io.FileInputStream;
140import java.io.FileNotFoundException;
141import java.io.FileOutputStream;
142import java.io.FileReader;
143import java.io.FilenameFilter;
144import java.io.IOException;
145import java.io.PrintWriter;
146import java.security.NoSuchAlgorithmException;
147import java.security.PublicKey;
148import java.security.cert.Certificate;
149import java.security.cert.CertificateEncodingException;
150import java.security.cert.CertificateException;
151import java.text.SimpleDateFormat;
152import java.util.ArrayList;
153import java.util.Arrays;
154import java.util.Collection;
155import java.util.Collections;
156import java.util.Comparator;
157import java.util.Date;
158import java.util.HashMap;
159import java.util.HashSet;
160import java.util.Iterator;
161import java.util.List;
162import java.util.Map;
163import java.util.Set;
164
165import libcore.io.IoUtils;
166
167import com.android.internal.R;
168import com.android.server.pm.Settings.DatabaseVersion;
169import com.android.server.storage.DeviceStorageMonitorInternal;
170
171/**
172 * Keep track of all those .apks everywhere.
173 *
174 * This is very central to the platform's security; please run the unit
175 * tests whenever making modifications here:
176 *
177mmm frameworks/base/tests/AndroidTests
178adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
179adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
180 *
181 * {@hide}
182 */
183public class PackageManagerService extends IPackageManager.Stub {
184    static final String TAG = "PackageManager";
185    static final boolean DEBUG_SETTINGS = false;
186    static final boolean DEBUG_PREFERRED = false;
187    static final boolean DEBUG_UPGRADE = false;
188    private static final boolean DEBUG_INSTALL = false;
189    private static final boolean DEBUG_REMOVE = false;
190    private static final boolean DEBUG_BROADCASTS = false;
191    private static final boolean DEBUG_SHOW_INFO = false;
192    private static final boolean DEBUG_PACKAGE_INFO = false;
193    private static final boolean DEBUG_INTENT_MATCHING = false;
194    private static final boolean DEBUG_PACKAGE_SCANNING = false;
195    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
196    private static final boolean DEBUG_VERIFY = false;
197
198    private static final int RADIO_UID = Process.PHONE_UID;
199    private static final int LOG_UID = Process.LOG_UID;
200    private static final int NFC_UID = Process.NFC_UID;
201    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
202    private static final int SHELL_UID = Process.SHELL_UID;
203
204    // Cap the size of permission trees that 3rd party apps can define
205    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
206
207    private static final int REMOVE_EVENTS =
208        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
209    private static final int ADD_EVENTS =
210        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
211
212    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
213    // Suffix used during package installation when copying/moving
214    // package apks to install directory.
215    private static final String INSTALL_PACKAGE_SUFFIX = "-";
216
217    static final int SCAN_MONITOR = 1<<0;
218    static final int SCAN_NO_DEX = 1<<1;
219    static final int SCAN_FORCE_DEX = 1<<2;
220    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
221    static final int SCAN_NEW_INSTALL = 1<<4;
222    static final int SCAN_NO_PATHS = 1<<5;
223    static final int SCAN_UPDATE_TIME = 1<<6;
224    static final int SCAN_DEFER_DEX = 1<<7;
225    static final int SCAN_BOOTING = 1<<8;
226    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
227    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
228
229    static final int REMOVE_CHATTY = 1<<16;
230
231    /**
232     * Timeout (in milliseconds) after which the watchdog should declare that
233     * our handler thread is wedged.  The usual default for such things is one
234     * minute but we sometimes do very lengthy I/O operations on this thread,
235     * such as installing multi-gigabyte applications, so ours needs to be longer.
236     */
237    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
238
239    /**
240     * Whether verification is enabled by default.
241     */
242    private static final boolean DEFAULT_VERIFY_ENABLE = true;
243
244    /**
245     * The default maximum time to wait for the verification agent to return in
246     * milliseconds.
247     */
248    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
249
250    /**
251     * The default response for package verification timeout.
252     *
253     * This can be either PackageManager.VERIFICATION_ALLOW or
254     * PackageManager.VERIFICATION_REJECT.
255     */
256    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
257
258    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
259
260    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
261            DEFAULT_CONTAINER_PACKAGE,
262            "com.android.defcontainer.DefaultContainerService");
263
264    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
265
266    private static final String LIB_DIR_NAME = "lib";
267    private static final String LIB64_DIR_NAME = "lib64";
268
269    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
270
271    static final String mTempContainerPrefix = "smdl2tmp";
272
273    final ServiceThread mHandlerThread;
274
275    private static final String IDMAP_PREFIX = "/data/resource-cache/";
276    private static final String IDMAP_SUFFIX = "@idmap";
277
278    final PackageHandler mHandler;
279
280    final int mSdkVersion = Build.VERSION.SDK_INT;
281
282    final Context mContext;
283    final boolean mFactoryTest;
284    final boolean mOnlyCore;
285    final boolean mNoDexOpt;
286    final DisplayMetrics mMetrics;
287    final int mDefParseFlags;
288    final String[] mSeparateProcesses;
289
290    // This is where all application persistent data goes.
291    final File mAppDataDir;
292
293    // This is where all application persistent data goes for secondary users.
294    final File mUserAppDataDir;
295
296    /** The location for ASEC container files on internal storage. */
297    final String mAsecInternalPath;
298
299    // This is the object monitoring the framework dir.
300    final FileObserver mFrameworkInstallObserver;
301
302    // This is the object monitoring the system app dir.
303    final FileObserver mSystemInstallObserver;
304
305    // This is the object monitoring the privileged system app dir.
306    final FileObserver mPrivilegedInstallObserver;
307
308    // This is the object monitoring the vendor app dir.
309    final FileObserver mVendorInstallObserver;
310
311    // This is the object monitoring the vendor overlay package dir.
312    final FileObserver mVendorOverlayInstallObserver;
313
314    // This is the object monitoring the OEM app dir.
315    final FileObserver mOemInstallObserver;
316
317    // This is the object monitoring mAppInstallDir.
318    final FileObserver mAppInstallObserver;
319
320    // This is the object monitoring mDrmAppPrivateInstallDir.
321    final FileObserver mDrmAppInstallObserver;
322
323    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
324    // LOCK HELD.  Can be called with mInstallLock held.
325    final Installer mInstaller;
326
327    final File mAppInstallDir;
328
329    /**
330     * Directory to which applications installed internally have native
331     * libraries copied.
332     */
333    private File mAppLibInstallDir;
334
335    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
336    // apps.
337    final File mDrmAppPrivateInstallDir;
338
339    // ----------------------------------------------------------------
340
341    // Lock for state used when installing and doing other long running
342    // operations.  Methods that must be called with this lock held have
343    // the suffix "LI".
344    final Object mInstallLock = new Object();
345
346    // These are the directories in the 3rd party applications installed dir
347    // that we have currently loaded packages from.  Keys are the application's
348    // installed zip file (absolute codePath), and values are Package.
349    final HashMap<String, PackageParser.Package> mAppDirs =
350            new HashMap<String, PackageParser.Package>();
351
352    // Information for the parser to write more useful error messages.
353    int mLastScanError;
354
355    // ----------------------------------------------------------------
356
357    // Keys are String (package name), values are Package.  This also serves
358    // as the lock for the global state.  Methods that must be called with
359    // this lock held have the prefix "LP".
360    final HashMap<String, PackageParser.Package> mPackages =
361            new HashMap<String, PackageParser.Package>();
362
363    // Tracks available target package names -> overlay package paths.
364    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
365        new HashMap<String, HashMap<String, PackageParser.Package>>();
366
367    final Settings mSettings;
368    boolean mRestoredSettings;
369
370    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
371    int[] mGlobalGids;
372
373    // These are the built-in uid -> permission mappings that were read from the
374    // etc/permissions.xml file.
375    final SparseArray<HashSet<String>> mSystemPermissions =
376            new SparseArray<HashSet<String>>();
377
378    static final class SharedLibraryEntry {
379        final String path;
380        final String apk;
381
382        SharedLibraryEntry(String _path, String _apk) {
383            path = _path;
384            apk = _apk;
385        }
386    }
387
388    // These are the built-in shared libraries that were read from the
389    // etc/permissions.xml file.
390    final HashMap<String, SharedLibraryEntry> mSharedLibraries
391            = new HashMap<String, SharedLibraryEntry>();
392
393    // Temporary for building the final shared libraries for an .apk.
394    String[] mTmpSharedLibraries = null;
395
396    // These are the features this devices supports that were read from the
397    // etc/permissions.xml file.
398    final HashMap<String, FeatureInfo> mAvailableFeatures =
399            new HashMap<String, FeatureInfo>();
400
401    // If mac_permissions.xml was found for seinfo labeling.
402    boolean mFoundPolicyFile;
403
404    // If a recursive restorecon of /data/data/<pkg> is needed.
405    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
406
407    // All available activities, for your resolving pleasure.
408    final ActivityIntentResolver mActivities =
409            new ActivityIntentResolver();
410
411    // All available receivers, for your resolving pleasure.
412    final ActivityIntentResolver mReceivers =
413            new ActivityIntentResolver();
414
415    // All available services, for your resolving pleasure.
416    final ServiceIntentResolver mServices = new ServiceIntentResolver();
417
418    // All available providers, for your resolving pleasure.
419    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
420
421    // Mapping from provider base names (first directory in content URI codePath)
422    // to the provider information.
423    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
424            new HashMap<String, PackageParser.Provider>();
425
426    // Mapping from instrumentation class names to info about them.
427    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
428            new HashMap<ComponentName, PackageParser.Instrumentation>();
429
430    // Mapping from permission names to info about them.
431    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
432            new HashMap<String, PackageParser.PermissionGroup>();
433
434    // Packages whose data we have transfered into another package, thus
435    // should no longer exist.
436    final HashSet<String> mTransferedPackages = new HashSet<String>();
437
438    // Broadcast actions that are only available to the system.
439    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
440
441    /** List of packages waiting for verification. */
442    final SparseArray<PackageVerificationState> mPendingVerification
443            = new SparseArray<PackageVerificationState>();
444
445    HashSet<PackageParser.Package> mDeferredDexOpt = null;
446
447    /** Token for keys in mPendingVerification. */
448    private int mPendingVerificationToken = 0;
449
450    boolean mSystemReady;
451    boolean mSafeMode;
452    boolean mHasSystemUidErrors;
453
454    ApplicationInfo mAndroidApplication;
455    final ActivityInfo mResolveActivity = new ActivityInfo();
456    final ResolveInfo mResolveInfo = new ResolveInfo();
457    ComponentName mResolveComponentName;
458    PackageParser.Package mPlatformPackage;
459    ComponentName mCustomResolverComponentName;
460
461    boolean mResolverReplaced = false;
462
463    // Set of pending broadcasts for aggregating enable/disable of components.
464    static class PendingPackageBroadcasts {
465        // for each user id, a map of <package name -> components within that package>
466        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
467
468        public PendingPackageBroadcasts() {
469            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
470        }
471
472        public ArrayList<String> get(int userId, String packageName) {
473            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
474            return packages.get(packageName);
475        }
476
477        public void put(int userId, String packageName, ArrayList<String> components) {
478            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
479            packages.put(packageName, components);
480        }
481
482        public void remove(int userId, String packageName) {
483            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
484            if (packages != null) {
485                packages.remove(packageName);
486            }
487        }
488
489        public void remove(int userId) {
490            mUidMap.remove(userId);
491        }
492
493        public int userIdCount() {
494            return mUidMap.size();
495        }
496
497        public int userIdAt(int n) {
498            return mUidMap.keyAt(n);
499        }
500
501        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
502            return mUidMap.get(userId);
503        }
504
505        public int size() {
506            // total number of pending broadcast entries across all userIds
507            int num = 0;
508            for (int i = 0; i< mUidMap.size(); i++) {
509                num += mUidMap.valueAt(i).size();
510            }
511            return num;
512        }
513
514        public void clear() {
515            mUidMap.clear();
516        }
517
518        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
519            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
520            if (map == null) {
521                map = new HashMap<String, ArrayList<String>>();
522                mUidMap.put(userId, map);
523            }
524            return map;
525        }
526    }
527    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
528
529    // Service Connection to remote media container service to copy
530    // package uri's from external media onto secure containers
531    // or internal storage.
532    private IMediaContainerService mContainerService = null;
533
534    static final int SEND_PENDING_BROADCAST = 1;
535    static final int MCS_BOUND = 3;
536    static final int END_COPY = 4;
537    static final int INIT_COPY = 5;
538    static final int MCS_UNBIND = 6;
539    static final int START_CLEANING_PACKAGE = 7;
540    static final int FIND_INSTALL_LOC = 8;
541    static final int POST_INSTALL = 9;
542    static final int MCS_RECONNECT = 10;
543    static final int MCS_GIVE_UP = 11;
544    static final int UPDATED_MEDIA_STATUS = 12;
545    static final int WRITE_SETTINGS = 13;
546    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
547    static final int PACKAGE_VERIFIED = 15;
548    static final int CHECK_PENDING_VERIFICATION = 16;
549
550    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
551
552    // Delay time in millisecs
553    static final int BROADCAST_DELAY = 10 * 1000;
554
555    static UserManagerService sUserManager;
556
557    // Stores a list of users whose package restrictions file needs to be updated
558    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
559
560    final private DefaultContainerConnection mDefContainerConn =
561            new DefaultContainerConnection();
562    class DefaultContainerConnection implements ServiceConnection {
563        public void onServiceConnected(ComponentName name, IBinder service) {
564            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
565            IMediaContainerService imcs =
566                IMediaContainerService.Stub.asInterface(service);
567            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
568        }
569
570        public void onServiceDisconnected(ComponentName name) {
571            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
572        }
573    };
574
575    // Recordkeeping of restore-after-install operations that are currently in flight
576    // between the Package Manager and the Backup Manager
577    class PostInstallData {
578        public InstallArgs args;
579        public PackageInstalledInfo res;
580
581        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
582            args = _a;
583            res = _r;
584        }
585    };
586    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
587    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
588
589    private final String mRequiredVerifierPackage;
590
591    class PackageHandler extends Handler {
592        private boolean mBound = false;
593        final ArrayList<HandlerParams> mPendingInstalls =
594            new ArrayList<HandlerParams>();
595
596        private boolean connectToService() {
597            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
598                    " DefaultContainerService");
599            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
600            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
601            if (mContext.bindServiceAsUser(service, mDefContainerConn,
602                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
603                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
604                mBound = true;
605                return true;
606            }
607            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
608            return false;
609        }
610
611        private void disconnectService() {
612            mContainerService = null;
613            mBound = false;
614            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
615            mContext.unbindService(mDefContainerConn);
616            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
617        }
618
619        PackageHandler(Looper looper) {
620            super(looper);
621        }
622
623        public void handleMessage(Message msg) {
624            try {
625                doHandleMessage(msg);
626            } finally {
627                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
628            }
629        }
630
631        void doHandleMessage(Message msg) {
632            switch (msg.what) {
633                case INIT_COPY: {
634                    HandlerParams params = (HandlerParams) msg.obj;
635                    int idx = mPendingInstalls.size();
636                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
637                    // If a bind was already initiated we dont really
638                    // need to do anything. The pending install
639                    // will be processed later on.
640                    if (!mBound) {
641                        // If this is the only one pending we might
642                        // have to bind to the service again.
643                        if (!connectToService()) {
644                            Slog.e(TAG, "Failed to bind to media container service");
645                            params.serviceError();
646                            return;
647                        } else {
648                            // Once we bind to the service, the first
649                            // pending request will be processed.
650                            mPendingInstalls.add(idx, params);
651                        }
652                    } else {
653                        mPendingInstalls.add(idx, params);
654                        // Already bound to the service. Just make
655                        // sure we trigger off processing the first request.
656                        if (idx == 0) {
657                            mHandler.sendEmptyMessage(MCS_BOUND);
658                        }
659                    }
660                    break;
661                }
662                case MCS_BOUND: {
663                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
664                    if (msg.obj != null) {
665                        mContainerService = (IMediaContainerService) msg.obj;
666                    }
667                    if (mContainerService == null) {
668                        // Something seriously wrong. Bail out
669                        Slog.e(TAG, "Cannot bind to media container service");
670                        for (HandlerParams params : mPendingInstalls) {
671                            // Indicate service bind error
672                            params.serviceError();
673                        }
674                        mPendingInstalls.clear();
675                    } else if (mPendingInstalls.size() > 0) {
676                        HandlerParams params = mPendingInstalls.get(0);
677                        if (params != null) {
678                            if (params.startCopy()) {
679                                // We are done...  look for more work or to
680                                // go idle.
681                                if (DEBUG_SD_INSTALL) Log.i(TAG,
682                                        "Checking for more work or unbind...");
683                                // Delete pending install
684                                if (mPendingInstalls.size() > 0) {
685                                    mPendingInstalls.remove(0);
686                                }
687                                if (mPendingInstalls.size() == 0) {
688                                    if (mBound) {
689                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
690                                                "Posting delayed MCS_UNBIND");
691                                        removeMessages(MCS_UNBIND);
692                                        Message ubmsg = obtainMessage(MCS_UNBIND);
693                                        // Unbind after a little delay, to avoid
694                                        // continual thrashing.
695                                        sendMessageDelayed(ubmsg, 10000);
696                                    }
697                                } else {
698                                    // There are more pending requests in queue.
699                                    // Just post MCS_BOUND message to trigger processing
700                                    // of next pending install.
701                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
702                                            "Posting MCS_BOUND for next work");
703                                    mHandler.sendEmptyMessage(MCS_BOUND);
704                                }
705                            }
706                        }
707                    } else {
708                        // Should never happen ideally.
709                        Slog.w(TAG, "Empty queue");
710                    }
711                    break;
712                }
713                case MCS_RECONNECT: {
714                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
715                    if (mPendingInstalls.size() > 0) {
716                        if (mBound) {
717                            disconnectService();
718                        }
719                        if (!connectToService()) {
720                            Slog.e(TAG, "Failed to bind to media container service");
721                            for (HandlerParams params : mPendingInstalls) {
722                                // Indicate service bind error
723                                params.serviceError();
724                            }
725                            mPendingInstalls.clear();
726                        }
727                    }
728                    break;
729                }
730                case MCS_UNBIND: {
731                    // If there is no actual work left, then time to unbind.
732                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
733
734                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
735                        if (mBound) {
736                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
737
738                            disconnectService();
739                        }
740                    } else if (mPendingInstalls.size() > 0) {
741                        // There are more pending requests in queue.
742                        // Just post MCS_BOUND message to trigger processing
743                        // of next pending install.
744                        mHandler.sendEmptyMessage(MCS_BOUND);
745                    }
746
747                    break;
748                }
749                case MCS_GIVE_UP: {
750                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
751                    mPendingInstalls.remove(0);
752                    break;
753                }
754                case SEND_PENDING_BROADCAST: {
755                    String packages[];
756                    ArrayList<String> components[];
757                    int size = 0;
758                    int uids[];
759                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
760                    synchronized (mPackages) {
761                        if (mPendingBroadcasts == null) {
762                            return;
763                        }
764                        size = mPendingBroadcasts.size();
765                        if (size <= 0) {
766                            // Nothing to be done. Just return
767                            return;
768                        }
769                        packages = new String[size];
770                        components = new ArrayList[size];
771                        uids = new int[size];
772                        int i = 0;  // filling out the above arrays
773
774                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
775                            int packageUserId = mPendingBroadcasts.userIdAt(n);
776                            Iterator<Map.Entry<String, ArrayList<String>>> it
777                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
778                                            .entrySet().iterator();
779                            while (it.hasNext() && i < size) {
780                                Map.Entry<String, ArrayList<String>> ent = it.next();
781                                packages[i] = ent.getKey();
782                                components[i] = ent.getValue();
783                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
784                                uids[i] = (ps != null)
785                                        ? UserHandle.getUid(packageUserId, ps.appId)
786                                        : -1;
787                                i++;
788                            }
789                        }
790                        size = i;
791                        mPendingBroadcasts.clear();
792                    }
793                    // Send broadcasts
794                    for (int i = 0; i < size; i++) {
795                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
796                    }
797                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
798                    break;
799                }
800                case START_CLEANING_PACKAGE: {
801                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
802                    final String packageName = (String)msg.obj;
803                    final int userId = msg.arg1;
804                    final boolean andCode = msg.arg2 != 0;
805                    synchronized (mPackages) {
806                        if (userId == UserHandle.USER_ALL) {
807                            int[] users = sUserManager.getUserIds();
808                            for (int user : users) {
809                                mSettings.addPackageToCleanLPw(
810                                        new PackageCleanItem(user, packageName, andCode));
811                            }
812                        } else {
813                            mSettings.addPackageToCleanLPw(
814                                    new PackageCleanItem(userId, packageName, andCode));
815                        }
816                    }
817                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
818                    startCleaningPackages();
819                } break;
820                case POST_INSTALL: {
821                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
822                    PostInstallData data = mRunningInstalls.get(msg.arg1);
823                    mRunningInstalls.delete(msg.arg1);
824                    boolean deleteOld = false;
825
826                    if (data != null) {
827                        InstallArgs args = data.args;
828                        PackageInstalledInfo res = data.res;
829
830                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
831                            res.removedInfo.sendBroadcast(false, true, false);
832                            Bundle extras = new Bundle(1);
833                            extras.putInt(Intent.EXTRA_UID, res.uid);
834                            // Determine the set of users who are adding this
835                            // package for the first time vs. those who are seeing
836                            // an update.
837                            int[] firstUsers;
838                            int[] updateUsers = new int[0];
839                            if (res.origUsers == null || res.origUsers.length == 0) {
840                                firstUsers = res.newUsers;
841                            } else {
842                                firstUsers = new int[0];
843                                for (int i=0; i<res.newUsers.length; i++) {
844                                    int user = res.newUsers[i];
845                                    boolean isNew = true;
846                                    for (int j=0; j<res.origUsers.length; j++) {
847                                        if (res.origUsers[j] == user) {
848                                            isNew = false;
849                                            break;
850                                        }
851                                    }
852                                    if (isNew) {
853                                        int[] newFirst = new int[firstUsers.length+1];
854                                        System.arraycopy(firstUsers, 0, newFirst, 0,
855                                                firstUsers.length);
856                                        newFirst[firstUsers.length] = user;
857                                        firstUsers = newFirst;
858                                    } else {
859                                        int[] newUpdate = new int[updateUsers.length+1];
860                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
861                                                updateUsers.length);
862                                        newUpdate[updateUsers.length] = user;
863                                        updateUsers = newUpdate;
864                                    }
865                                }
866                            }
867                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
868                                    res.pkg.applicationInfo.packageName,
869                                    extras, null, null, firstUsers);
870                            final boolean update = res.removedInfo.removedPackage != null;
871                            if (update) {
872                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
873                            }
874                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
875                                    res.pkg.applicationInfo.packageName,
876                                    extras, null, null, updateUsers);
877                            if (update) {
878                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
879                                        res.pkg.applicationInfo.packageName,
880                                        extras, null, null, updateUsers);
881                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
882                                        null, null,
883                                        res.pkg.applicationInfo.packageName, null, updateUsers);
884
885                                // treat asec-hosted packages like removable media on upgrade
886                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
887                                    if (DEBUG_INSTALL) {
888                                        Slog.i(TAG, "upgrading pkg " + res.pkg
889                                                + " is ASEC-hosted -> AVAILABLE");
890                                    }
891                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
892                                    ArrayList<String> pkgList = new ArrayList<String>(1);
893                                    pkgList.add(res.pkg.applicationInfo.packageName);
894                                    sendResourcesChangedBroadcast(true, true,
895                                            pkgList,uidArray, null);
896                                }
897                            }
898                            if (res.removedInfo.args != null) {
899                                // Remove the replaced package's older resources safely now
900                                deleteOld = true;
901                            }
902
903                            // Log current value of "unknown sources" setting
904                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
905                                getUnknownSourcesSettings());
906                        }
907                        // Force a gc to clear up things
908                        Runtime.getRuntime().gc();
909                        // We delete after a gc for applications  on sdcard.
910                        if (deleteOld) {
911                            synchronized (mInstallLock) {
912                                res.removedInfo.args.doPostDeleteLI(true);
913                            }
914                        }
915                        if (args.observer != null) {
916                            try {
917                                args.observer.packageInstalled(res.name, res.returnCode);
918                            } catch (RemoteException e) {
919                                Slog.i(TAG, "Observer no longer exists.");
920                            }
921                        }
922                        if (args.observer2 != null) {
923                            try {
924                                Bundle extras = extrasForInstallResult(res);
925                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
926                            } catch (RemoteException e) {
927                                Slog.i(TAG, "Observer no longer exists.");
928                            }
929                        }
930                    } else {
931                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
932                    }
933                } break;
934                case UPDATED_MEDIA_STATUS: {
935                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
936                    boolean reportStatus = msg.arg1 == 1;
937                    boolean doGc = msg.arg2 == 1;
938                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
939                    if (doGc) {
940                        // Force a gc to clear up stale containers.
941                        Runtime.getRuntime().gc();
942                    }
943                    if (msg.obj != null) {
944                        @SuppressWarnings("unchecked")
945                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
946                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
947                        // Unload containers
948                        unloadAllContainers(args);
949                    }
950                    if (reportStatus) {
951                        try {
952                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
953                            PackageHelper.getMountService().finishMediaUpdate();
954                        } catch (RemoteException e) {
955                            Log.e(TAG, "MountService not running?");
956                        }
957                    }
958                } break;
959                case WRITE_SETTINGS: {
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
961                    synchronized (mPackages) {
962                        removeMessages(WRITE_SETTINGS);
963                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
964                        mSettings.writeLPr();
965                        mDirtyUsers.clear();
966                    }
967                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
968                } break;
969                case WRITE_PACKAGE_RESTRICTIONS: {
970                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
971                    synchronized (mPackages) {
972                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
973                        for (int userId : mDirtyUsers) {
974                            mSettings.writePackageRestrictionsLPr(userId);
975                        }
976                        mDirtyUsers.clear();
977                    }
978                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
979                } break;
980                case CHECK_PENDING_VERIFICATION: {
981                    final int verificationId = msg.arg1;
982                    final PackageVerificationState state = mPendingVerification.get(verificationId);
983
984                    if ((state != null) && !state.timeoutExtended()) {
985                        final InstallArgs args = state.getInstallArgs();
986                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
987                        mPendingVerification.remove(verificationId);
988
989                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
990
991                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
992                            Slog.i(TAG, "Continuing with installation of "
993                                    + args.packageURI.toString());
994                            state.setVerifierResponse(Binder.getCallingUid(),
995                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
996                            broadcastPackageVerified(verificationId, args.packageURI,
997                                    PackageManager.VERIFICATION_ALLOW,
998                                    state.getInstallArgs().getUser());
999                            try {
1000                                ret = args.copyApk(mContainerService, true);
1001                            } catch (RemoteException e) {
1002                                Slog.e(TAG, "Could not contact the ContainerService");
1003                            }
1004                        } else {
1005                            broadcastPackageVerified(verificationId, args.packageURI,
1006                                    PackageManager.VERIFICATION_REJECT,
1007                                    state.getInstallArgs().getUser());
1008                        }
1009
1010                        processPendingInstall(args, ret);
1011                        mHandler.sendEmptyMessage(MCS_UNBIND);
1012                    }
1013                    break;
1014                }
1015                case PACKAGE_VERIFIED: {
1016                    final int verificationId = msg.arg1;
1017
1018                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1019                    if (state == null) {
1020                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1021                        break;
1022                    }
1023
1024                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1025
1026                    state.setVerifierResponse(response.callerUid, response.code);
1027
1028                    if (state.isVerificationComplete()) {
1029                        mPendingVerification.remove(verificationId);
1030
1031                        final InstallArgs args = state.getInstallArgs();
1032
1033                        int ret;
1034                        if (state.isInstallAllowed()) {
1035                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1036                            broadcastPackageVerified(verificationId, args.packageURI,
1037                                    response.code, state.getInstallArgs().getUser());
1038                            try {
1039                                ret = args.copyApk(mContainerService, true);
1040                            } catch (RemoteException e) {
1041                                Slog.e(TAG, "Could not contact the ContainerService");
1042                            }
1043                        } else {
1044                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1045                        }
1046
1047                        processPendingInstall(args, ret);
1048
1049                        mHandler.sendEmptyMessage(MCS_UNBIND);
1050                    }
1051
1052                    break;
1053                }
1054            }
1055        }
1056    }
1057
1058    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1059        Bundle extras = null;
1060        switch (res.returnCode) {
1061            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1062                extras = new Bundle();
1063                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1064                        res.origPermission);
1065                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1066                        res.origPackage);
1067                break;
1068            }
1069        }
1070        return extras;
1071    }
1072
1073    void scheduleWriteSettingsLocked() {
1074        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1075            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1076        }
1077    }
1078
1079    void scheduleWritePackageRestrictionsLocked(int userId) {
1080        if (!sUserManager.exists(userId)) return;
1081        mDirtyUsers.add(userId);
1082        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1083            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1084        }
1085    }
1086
1087    public static final IPackageManager main(Context context, Installer installer,
1088            boolean factoryTest, boolean onlyCore) {
1089        PackageManagerService m = new PackageManagerService(context, installer,
1090                factoryTest, onlyCore);
1091        ServiceManager.addService("package", m);
1092        return m;
1093    }
1094
1095    static String[] splitString(String str, char sep) {
1096        int count = 1;
1097        int i = 0;
1098        while ((i=str.indexOf(sep, i)) >= 0) {
1099            count++;
1100            i++;
1101        }
1102
1103        String[] res = new String[count];
1104        i=0;
1105        count = 0;
1106        int lastI=0;
1107        while ((i=str.indexOf(sep, i)) >= 0) {
1108            res[count] = str.substring(lastI, i);
1109            count++;
1110            i++;
1111            lastI = i;
1112        }
1113        res[count] = str.substring(lastI, str.length());
1114        return res;
1115    }
1116
1117    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1118        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1119                Context.DISPLAY_SERVICE);
1120        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1121    }
1122
1123    public PackageManagerService(Context context, Installer installer,
1124            boolean factoryTest, boolean onlyCore) {
1125        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1126                SystemClock.uptimeMillis());
1127
1128        if (mSdkVersion <= 0) {
1129            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1130        }
1131
1132        mContext = context;
1133        mFactoryTest = factoryTest;
1134        mOnlyCore = onlyCore;
1135        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1136        mMetrics = new DisplayMetrics();
1137        mSettings = new Settings(context);
1138        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1139                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1140        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1141                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1142        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1143                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1144        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1145                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1146        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1147                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1148        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1149                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1150
1151        String separateProcesses = SystemProperties.get("debug.separate_processes");
1152        if (separateProcesses != null && separateProcesses.length() > 0) {
1153            if ("*".equals(separateProcesses)) {
1154                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1155                mSeparateProcesses = null;
1156                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1157            } else {
1158                mDefParseFlags = 0;
1159                mSeparateProcesses = separateProcesses.split(",");
1160                Slog.w(TAG, "Running with debug.separate_processes: "
1161                        + separateProcesses);
1162            }
1163        } else {
1164            mDefParseFlags = 0;
1165            mSeparateProcesses = null;
1166        }
1167
1168        mInstaller = installer;
1169
1170        getDefaultDisplayMetrics(context, mMetrics);
1171
1172        synchronized (mInstallLock) {
1173        // writer
1174        synchronized (mPackages) {
1175            mHandlerThread = new ServiceThread(TAG,
1176                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1177            mHandlerThread.start();
1178            mHandler = new PackageHandler(mHandlerThread.getLooper());
1179            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1180
1181            File dataDir = Environment.getDataDirectory();
1182            mAppDataDir = new File(dataDir, "data");
1183            mAppInstallDir = new File(dataDir, "app");
1184            mAppLibInstallDir = new File(dataDir, "app-lib");
1185            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1186            mUserAppDataDir = new File(dataDir, "user");
1187            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1188
1189            sUserManager = new UserManagerService(context, this,
1190                    mInstallLock, mPackages);
1191
1192            // Read permissions and features from system
1193            readPermissions(Environment.buildPath(
1194                    Environment.getRootDirectory(), "etc", "permissions"), false);
1195            // Only read features from OEM
1196            readPermissions(Environment.buildPath(
1197                    Environment.getOemDirectory(), "etc", "permissions"), true);
1198
1199            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1200
1201            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1202                    mSdkVersion, mOnlyCore);
1203
1204            String customResolverActivity = Resources.getSystem().getString(
1205                    R.string.config_customResolverActivity);
1206            if (TextUtils.isEmpty(customResolverActivity)) {
1207                customResolverActivity = null;
1208            } else {
1209                mCustomResolverComponentName = ComponentName.unflattenFromString(
1210                        customResolverActivity);
1211            }
1212
1213            long startTime = SystemClock.uptimeMillis();
1214
1215            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1216                    startTime);
1217
1218            // Set flag to monitor and not change apk file paths when
1219            // scanning install directories.
1220            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1221            if (mNoDexOpt) {
1222                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1223                scanMode |= SCAN_NO_DEX;
1224            }
1225
1226            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1227
1228            /**
1229             * Add everything in the in the boot class path to the
1230             * list of process files because dexopt will have been run
1231             * if necessary during zygote startup.
1232             */
1233            String bootClassPath = System.getProperty("java.boot.class.path");
1234            if (bootClassPath != null) {
1235                String[] paths = splitString(bootClassPath, ':');
1236                for (int i=0; i<paths.length; i++) {
1237                    alreadyDexOpted.add(paths[i]);
1238                }
1239            } else {
1240                Slog.w(TAG, "No BOOTCLASSPATH found!");
1241            }
1242
1243            boolean didDexOpt = false;
1244
1245            /**
1246             * Ensure all external libraries have had dexopt run on them.
1247             */
1248            if (mSharedLibraries.size() > 0) {
1249                Iterator<SharedLibraryEntry> libs = mSharedLibraries.values().iterator();
1250                while (libs.hasNext()) {
1251                    String lib = libs.next().path;
1252                    if (lib == null) {
1253                        continue;
1254                    }
1255                    try {
1256                        if (dalvik.system.DexFile.isDexOptNeededInternal(lib, null, false)) {
1257                            alreadyDexOpted.add(lib);
1258                            mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1259                            didDexOpt = true;
1260                        }
1261                    } catch (FileNotFoundException e) {
1262                        Slog.w(TAG, "Library not found: " + lib);
1263                    } catch (IOException e) {
1264                        Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1265                                + e.getMessage());
1266                    }
1267                }
1268            }
1269
1270            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1271
1272            // Gross hack for now: we know this file doesn't contain any
1273            // code, so don't dexopt it to avoid the resulting log spew.
1274            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1275
1276            // Gross hack for now: we know this file is only part of
1277            // the boot class path for art, so don't dexopt it to
1278            // avoid the resulting log spew.
1279            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1280
1281            /**
1282             * And there are a number of commands implemented in Java, which
1283             * we currently need to do the dexopt on so that they can be
1284             * run from a non-root shell.
1285             */
1286            String[] frameworkFiles = frameworkDir.list();
1287            if (frameworkFiles != null) {
1288                for (int i=0; i<frameworkFiles.length; i++) {
1289                    File libPath = new File(frameworkDir, frameworkFiles[i]);
1290                    String path = libPath.getPath();
1291                    // Skip the file if we alrady did it.
1292                    if (alreadyDexOpted.contains(path)) {
1293                        continue;
1294                    }
1295                    // Skip the file if it is not a type we want to dexopt.
1296                    if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1297                        continue;
1298                    }
1299                    try {
1300                        if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, false)) {
1301                            mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1302                            didDexOpt = true;
1303                        }
1304                    } catch (FileNotFoundException e) {
1305                        Slog.w(TAG, "Jar not found: " + path);
1306                    } catch (IOException e) {
1307                        Slog.w(TAG, "Exception reading jar: " + path, e);
1308                    }
1309                }
1310            }
1311
1312            if (didDexOpt) {
1313                File dalvikCacheDir = new File(dataDir, "dalvik-cache");
1314
1315                // If we had to do a dexopt of one of the previous
1316                // things, then something on the system has changed.
1317                // Consider this significant, and wipe away all other
1318                // existing dexopt files to ensure we don't leave any
1319                // dangling around.
1320                String[] files = dalvikCacheDir.list();
1321                if (files != null) {
1322                    for (int i=0; i<files.length; i++) {
1323                        String fn = files[i];
1324                        if (fn.startsWith("data@app@")
1325                                || fn.startsWith("data@app-private@")) {
1326                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1327                            (new File(dalvikCacheDir, fn)).delete();
1328                        }
1329                    }
1330                }
1331            }
1332
1333            // Collect vendor overlay packages.
1334            // (Do this before scanning any apps.)
1335            // For security and version matching reason, only consider
1336            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1337            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1338            mVendorOverlayInstallObserver = new AppDirObserver(
1339                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1340            mVendorOverlayInstallObserver.startWatching();
1341            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1342                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1343
1344            // Find base frameworks (resource packages without code).
1345            mFrameworkInstallObserver = new AppDirObserver(
1346                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1347            mFrameworkInstallObserver.startWatching();
1348            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1349                    | PackageParser.PARSE_IS_SYSTEM_DIR
1350                    | PackageParser.PARSE_IS_PRIVILEGED,
1351                    scanMode | SCAN_NO_DEX, 0);
1352
1353            // Collected privileged system packages.
1354            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1355            mPrivilegedInstallObserver = new AppDirObserver(
1356                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1357            mPrivilegedInstallObserver.startWatching();
1358                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1359                        | PackageParser.PARSE_IS_SYSTEM_DIR
1360                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1361
1362            // Collect ordinary system packages.
1363            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1364            mSystemInstallObserver = new AppDirObserver(
1365                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1366            mSystemInstallObserver.startWatching();
1367            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1368                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1369
1370            // Collect all vendor packages.
1371            File vendorAppDir = new File("/vendor/app");
1372            try {
1373                vendorAppDir = vendorAppDir.getCanonicalFile();
1374            } catch (IOException e) {
1375                // failed to look up canonical path, continue with original one
1376            }
1377            mVendorInstallObserver = new AppDirObserver(
1378                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1379            mVendorInstallObserver.startWatching();
1380            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1381                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1382
1383            // Collect all OEM packages.
1384            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1385            mOemInstallObserver = new AppDirObserver(
1386                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1387            mOemInstallObserver.startWatching();
1388            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1389                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1390
1391            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1392            mInstaller.moveFiles();
1393
1394            // Prune any system packages that no longer exist.
1395            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1396            if (!mOnlyCore) {
1397                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1398                while (psit.hasNext()) {
1399                    PackageSetting ps = psit.next();
1400
1401                    /*
1402                     * If this is not a system app, it can't be a
1403                     * disable system app.
1404                     */
1405                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1406                        continue;
1407                    }
1408
1409                    /*
1410                     * If the package is scanned, it's not erased.
1411                     */
1412                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1413                    if (scannedPkg != null) {
1414                        /*
1415                         * If the system app is both scanned and in the
1416                         * disabled packages list, then it must have been
1417                         * added via OTA. Remove it from the currently
1418                         * scanned package so the previously user-installed
1419                         * application can be scanned.
1420                         */
1421                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1422                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1423                                    + "; removing system app");
1424                            removePackageLI(ps, true);
1425                        }
1426
1427                        continue;
1428                    }
1429
1430                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1431                        psit.remove();
1432                        String msg = "System package " + ps.name
1433                                + " no longer exists; wiping its data";
1434                        reportSettingsProblem(Log.WARN, msg);
1435                        removeDataDirsLI(ps.name);
1436                    } else {
1437                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1438                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1439                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1440                        }
1441                    }
1442                }
1443            }
1444
1445            //look for any incomplete package installations
1446            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1447            //clean up list
1448            for(int i = 0; i < deletePkgsList.size(); i++) {
1449                //clean up here
1450                cleanupInstallFailedPackage(deletePkgsList.get(i));
1451            }
1452            //delete tmp files
1453            deleteTempPackageFiles();
1454
1455            // Remove any shared userIDs that have no associated packages
1456            mSettings.pruneSharedUsersLPw();
1457
1458            if (!mOnlyCore) {
1459                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1460                        SystemClock.uptimeMillis());
1461                mAppInstallObserver = new AppDirObserver(
1462                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1463                mAppInstallObserver.startWatching();
1464                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1465
1466                mDrmAppInstallObserver = new AppDirObserver(
1467                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1468                mDrmAppInstallObserver.startWatching();
1469                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1470                        scanMode, 0);
1471
1472                /**
1473                 * Remove disable package settings for any updated system
1474                 * apps that were removed via an OTA. If they're not a
1475                 * previously-updated app, remove them completely.
1476                 * Otherwise, just revoke their system-level permissions.
1477                 */
1478                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1479                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1480                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1481
1482                    String msg;
1483                    if (deletedPkg == null) {
1484                        msg = "Updated system package " + deletedAppName
1485                                + " no longer exists; wiping its data";
1486                        removeDataDirsLI(deletedAppName);
1487                    } else {
1488                        msg = "Updated system app + " + deletedAppName
1489                                + " no longer present; removing system privileges for "
1490                                + deletedAppName;
1491
1492                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1493
1494                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1495                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1496                    }
1497                    reportSettingsProblem(Log.WARN, msg);
1498                }
1499            } else {
1500                mAppInstallObserver = null;
1501                mDrmAppInstallObserver = null;
1502            }
1503
1504            // Now that we know all of the shared libraries, update all clients to have
1505            // the correct library paths.
1506            updateAllSharedLibrariesLPw();
1507
1508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1509                    SystemClock.uptimeMillis());
1510            Slog.i(TAG, "Time to scan packages: "
1511                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1512                    + " seconds");
1513
1514            // If the platform SDK has changed since the last time we booted,
1515            // we need to re-grant app permission to catch any new ones that
1516            // appear.  This is really a hack, and means that apps can in some
1517            // cases get permissions that the user didn't initially explicitly
1518            // allow...  it would be nice to have some better way to handle
1519            // this situation.
1520            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1521                    != mSdkVersion;
1522            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1523                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1524                    + "; regranting permissions for internal storage");
1525            mSettings.mInternalSdkPlatform = mSdkVersion;
1526
1527            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1528                    | (regrantPermissions
1529                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1530                            : 0));
1531
1532            // If this is the first boot, and it is a normal boot, then
1533            // we need to initialize the default preferred apps.
1534            if (!mRestoredSettings && !onlyCore) {
1535                mSettings.readDefaultPreferredAppsLPw(this, 0);
1536            }
1537
1538            // All the changes are done during package scanning.
1539            mSettings.updateInternalDatabaseVersion();
1540
1541            // can downgrade to reader
1542            mSettings.writeLPr();
1543
1544            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1545                    SystemClock.uptimeMillis());
1546
1547            // Now after opening every single application zip, make sure they
1548            // are all flushed.  Not really needed, but keeps things nice and
1549            // tidy.
1550            Runtime.getRuntime().gc();
1551
1552            mRequiredVerifierPackage = getRequiredVerifierLPr();
1553        } // synchronized (mPackages)
1554        } // synchronized (mInstallLock)
1555    }
1556
1557    public boolean isFirstBoot() {
1558        return !mRestoredSettings;
1559    }
1560
1561    public boolean isOnlyCoreApps() {
1562        return mOnlyCore;
1563    }
1564
1565    private String getRequiredVerifierLPr() {
1566        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1567        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1568                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1569
1570        String requiredVerifier = null;
1571
1572        final int N = receivers.size();
1573        for (int i = 0; i < N; i++) {
1574            final ResolveInfo info = receivers.get(i);
1575
1576            if (info.activityInfo == null) {
1577                continue;
1578            }
1579
1580            final String packageName = info.activityInfo.packageName;
1581
1582            final PackageSetting ps = mSettings.mPackages.get(packageName);
1583            if (ps == null) {
1584                continue;
1585            }
1586
1587            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1588            if (!gp.grantedPermissions
1589                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1590                continue;
1591            }
1592
1593            if (requiredVerifier != null) {
1594                throw new RuntimeException("There can be only one required verifier");
1595            }
1596
1597            requiredVerifier = packageName;
1598        }
1599
1600        return requiredVerifier;
1601    }
1602
1603    @Override
1604    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1605            throws RemoteException {
1606        try {
1607            return super.onTransact(code, data, reply, flags);
1608        } catch (RuntimeException e) {
1609            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1610                Slog.wtf(TAG, "Package Manager Crash", e);
1611            }
1612            throw e;
1613        }
1614    }
1615
1616    void cleanupInstallFailedPackage(PackageSetting ps) {
1617        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1618        removeDataDirsLI(ps.name);
1619        if (ps.codePath != null) {
1620            if (!ps.codePath.delete()) {
1621                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1622            }
1623        }
1624        if (ps.resourcePath != null) {
1625            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1626                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1627            }
1628        }
1629        mSettings.removePackageLPw(ps.name);
1630    }
1631
1632    void readPermissions(File libraryDir, boolean onlyFeatures) {
1633        // Read permissions from .../etc/permission directory.
1634        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1635            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1636            return;
1637        }
1638        if (!libraryDir.canRead()) {
1639            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1640            return;
1641        }
1642
1643        // Iterate over the files in the directory and scan .xml files
1644        for (File f : libraryDir.listFiles()) {
1645            // We'll read platform.xml last
1646            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1647                continue;
1648            }
1649
1650            if (!f.getPath().endsWith(".xml")) {
1651                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1652                continue;
1653            }
1654            if (!f.canRead()) {
1655                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1656                continue;
1657            }
1658
1659            readPermissionsFromXml(f, onlyFeatures);
1660        }
1661
1662        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1663        final File permFile = new File(Environment.getRootDirectory(),
1664                "etc/permissions/platform.xml");
1665        readPermissionsFromXml(permFile, onlyFeatures);
1666    }
1667
1668    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1669        FileReader permReader = null;
1670        try {
1671            permReader = new FileReader(permFile);
1672        } catch (FileNotFoundException e) {
1673            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1674            return;
1675        }
1676
1677        try {
1678            XmlPullParser parser = Xml.newPullParser();
1679            parser.setInput(permReader);
1680
1681            XmlUtils.beginDocument(parser, "permissions");
1682
1683            while (true) {
1684                XmlUtils.nextElement(parser);
1685                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1686                    break;
1687                }
1688
1689                String name = parser.getName();
1690                if ("group".equals(name) && !onlyFeatures) {
1691                    String gidStr = parser.getAttributeValue(null, "gid");
1692                    if (gidStr != null) {
1693                        int gid = Process.getGidForName(gidStr);
1694                        mGlobalGids = appendInt(mGlobalGids, gid);
1695                    } else {
1696                        Slog.w(TAG, "<group> without gid at "
1697                                + parser.getPositionDescription());
1698                    }
1699
1700                    XmlUtils.skipCurrentTag(parser);
1701                    continue;
1702                } else if ("permission".equals(name) && !onlyFeatures) {
1703                    String perm = parser.getAttributeValue(null, "name");
1704                    if (perm == null) {
1705                        Slog.w(TAG, "<permission> without name at "
1706                                + parser.getPositionDescription());
1707                        XmlUtils.skipCurrentTag(parser);
1708                        continue;
1709                    }
1710                    perm = perm.intern();
1711                    readPermission(parser, perm);
1712
1713                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1714                    String perm = parser.getAttributeValue(null, "name");
1715                    if (perm == null) {
1716                        Slog.w(TAG, "<assign-permission> without name at "
1717                                + parser.getPositionDescription());
1718                        XmlUtils.skipCurrentTag(parser);
1719                        continue;
1720                    }
1721                    String uidStr = parser.getAttributeValue(null, "uid");
1722                    if (uidStr == null) {
1723                        Slog.w(TAG, "<assign-permission> without uid at "
1724                                + parser.getPositionDescription());
1725                        XmlUtils.skipCurrentTag(parser);
1726                        continue;
1727                    }
1728                    int uid = Process.getUidForName(uidStr);
1729                    if (uid < 0) {
1730                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1731                                + uidStr + "\" at "
1732                                + parser.getPositionDescription());
1733                        XmlUtils.skipCurrentTag(parser);
1734                        continue;
1735                    }
1736                    perm = perm.intern();
1737                    HashSet<String> perms = mSystemPermissions.get(uid);
1738                    if (perms == null) {
1739                        perms = new HashSet<String>();
1740                        mSystemPermissions.put(uid, perms);
1741                    }
1742                    perms.add(perm);
1743                    XmlUtils.skipCurrentTag(parser);
1744
1745                } else if ("library".equals(name) && !onlyFeatures) {
1746                    String lname = parser.getAttributeValue(null, "name");
1747                    String lfile = parser.getAttributeValue(null, "file");
1748                    if (lname == null) {
1749                        Slog.w(TAG, "<library> without name at "
1750                                + parser.getPositionDescription());
1751                    } else if (lfile == null) {
1752                        Slog.w(TAG, "<library> without file at "
1753                                + parser.getPositionDescription());
1754                    } else {
1755                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1756                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1757                    }
1758                    XmlUtils.skipCurrentTag(parser);
1759                    continue;
1760
1761                } else if ("feature".equals(name)) {
1762                    String fname = parser.getAttributeValue(null, "name");
1763                    if (fname == null) {
1764                        Slog.w(TAG, "<feature> without name at "
1765                                + parser.getPositionDescription());
1766                    } else {
1767                        //Log.i(TAG, "Got feature " + fname);
1768                        FeatureInfo fi = new FeatureInfo();
1769                        fi.name = fname;
1770                        mAvailableFeatures.put(fname, fi);
1771                    }
1772                    XmlUtils.skipCurrentTag(parser);
1773                    continue;
1774
1775                } else {
1776                    XmlUtils.skipCurrentTag(parser);
1777                    continue;
1778                }
1779
1780            }
1781            permReader.close();
1782        } catch (XmlPullParserException e) {
1783            Slog.w(TAG, "Got execption parsing permissions.", e);
1784        } catch (IOException e) {
1785            Slog.w(TAG, "Got execption parsing permissions.", e);
1786        }
1787    }
1788
1789    void readPermission(XmlPullParser parser, String name)
1790            throws IOException, XmlPullParserException {
1791
1792        name = name.intern();
1793
1794        BasePermission bp = mSettings.mPermissions.get(name);
1795        if (bp == null) {
1796            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1797            mSettings.mPermissions.put(name, bp);
1798        }
1799        int outerDepth = parser.getDepth();
1800        int type;
1801        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1802               && (type != XmlPullParser.END_TAG
1803                       || parser.getDepth() > outerDepth)) {
1804            if (type == XmlPullParser.END_TAG
1805                    || type == XmlPullParser.TEXT) {
1806                continue;
1807            }
1808
1809            String tagName = parser.getName();
1810            if ("group".equals(tagName)) {
1811                String gidStr = parser.getAttributeValue(null, "gid");
1812                if (gidStr != null) {
1813                    int gid = Process.getGidForName(gidStr);
1814                    bp.gids = appendInt(bp.gids, gid);
1815                } else {
1816                    Slog.w(TAG, "<group> without gid at "
1817                            + parser.getPositionDescription());
1818                }
1819            }
1820            XmlUtils.skipCurrentTag(parser);
1821        }
1822    }
1823
1824    static int[] appendInts(int[] cur, int[] add) {
1825        if (add == null) return cur;
1826        if (cur == null) return add;
1827        final int N = add.length;
1828        for (int i=0; i<N; i++) {
1829            cur = appendInt(cur, add[i]);
1830        }
1831        return cur;
1832    }
1833
1834    static int[] removeInts(int[] cur, int[] rem) {
1835        if (rem == null) return cur;
1836        if (cur == null) return cur;
1837        final int N = rem.length;
1838        for (int i=0; i<N; i++) {
1839            cur = removeInt(cur, rem[i]);
1840        }
1841        return cur;
1842    }
1843
1844    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1845        if (!sUserManager.exists(userId)) return null;
1846        PackageInfo pi;
1847        final PackageSetting ps = (PackageSetting) p.mExtras;
1848        if (ps == null) {
1849            return null;
1850        }
1851        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1852        final PackageUserState state = ps.readUserState(userId);
1853        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1854                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1855                state, userId);
1856    }
1857
1858    public boolean isPackageAvailable(String packageName, int userId) {
1859        if (!sUserManager.exists(userId)) return false;
1860        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1861        synchronized (mPackages) {
1862            PackageParser.Package p = mPackages.get(packageName);
1863            if (p != null) {
1864                final PackageSetting ps = (PackageSetting) p.mExtras;
1865                if (ps != null) {
1866                    final PackageUserState state = ps.readUserState(userId);
1867                    if (state != null) {
1868                        return PackageParser.isAvailable(state);
1869                    }
1870                }
1871            }
1872        }
1873        return false;
1874    }
1875
1876    @Override
1877    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1878        if (!sUserManager.exists(userId)) return null;
1879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1880        // reader
1881        synchronized (mPackages) {
1882            PackageParser.Package p = mPackages.get(packageName);
1883            if (DEBUG_PACKAGE_INFO)
1884                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1885            if (p != null) {
1886                return generatePackageInfo(p, flags, userId);
1887            }
1888            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1889                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1890            }
1891        }
1892        return null;
1893    }
1894
1895    public String[] currentToCanonicalPackageNames(String[] names) {
1896        String[] out = new String[names.length];
1897        // reader
1898        synchronized (mPackages) {
1899            for (int i=names.length-1; i>=0; i--) {
1900                PackageSetting ps = mSettings.mPackages.get(names[i]);
1901                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1902            }
1903        }
1904        return out;
1905    }
1906
1907    public String[] canonicalToCurrentPackageNames(String[] names) {
1908        String[] out = new String[names.length];
1909        // reader
1910        synchronized (mPackages) {
1911            for (int i=names.length-1; i>=0; i--) {
1912                String cur = mSettings.mRenamedPackages.get(names[i]);
1913                out[i] = cur != null ? cur : names[i];
1914            }
1915        }
1916        return out;
1917    }
1918
1919    @Override
1920    public int getPackageUid(String packageName, int userId) {
1921        if (!sUserManager.exists(userId)) return -1;
1922        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1923        // reader
1924        synchronized (mPackages) {
1925            PackageParser.Package p = mPackages.get(packageName);
1926            if(p != null) {
1927                return UserHandle.getUid(userId, p.applicationInfo.uid);
1928            }
1929            PackageSetting ps = mSettings.mPackages.get(packageName);
1930            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1931                return -1;
1932            }
1933            p = ps.pkg;
1934            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1935        }
1936    }
1937
1938    @Override
1939    public int[] getPackageGids(String packageName) {
1940        // reader
1941        synchronized (mPackages) {
1942            PackageParser.Package p = mPackages.get(packageName);
1943            if (DEBUG_PACKAGE_INFO)
1944                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1945            if (p != null) {
1946                final PackageSetting ps = (PackageSetting)p.mExtras;
1947                return ps.getGids();
1948            }
1949        }
1950        // stupid thing to indicate an error.
1951        return new int[0];
1952    }
1953
1954    static final PermissionInfo generatePermissionInfo(
1955            BasePermission bp, int flags) {
1956        if (bp.perm != null) {
1957            return PackageParser.generatePermissionInfo(bp.perm, flags);
1958        }
1959        PermissionInfo pi = new PermissionInfo();
1960        pi.name = bp.name;
1961        pi.packageName = bp.sourcePackage;
1962        pi.nonLocalizedLabel = bp.name;
1963        pi.protectionLevel = bp.protectionLevel;
1964        return pi;
1965    }
1966
1967    public PermissionInfo getPermissionInfo(String name, int flags) {
1968        // reader
1969        synchronized (mPackages) {
1970            final BasePermission p = mSettings.mPermissions.get(name);
1971            if (p != null) {
1972                return generatePermissionInfo(p, flags);
1973            }
1974            return null;
1975        }
1976    }
1977
1978    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1979        // reader
1980        synchronized (mPackages) {
1981            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1982            for (BasePermission p : mSettings.mPermissions.values()) {
1983                if (group == null) {
1984                    if (p.perm == null || p.perm.info.group == null) {
1985                        out.add(generatePermissionInfo(p, flags));
1986                    }
1987                } else {
1988                    if (p.perm != null && group.equals(p.perm.info.group)) {
1989                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1990                    }
1991                }
1992            }
1993
1994            if (out.size() > 0) {
1995                return out;
1996            }
1997            return mPermissionGroups.containsKey(group) ? out : null;
1998        }
1999    }
2000
2001    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2002        // reader
2003        synchronized (mPackages) {
2004            return PackageParser.generatePermissionGroupInfo(
2005                    mPermissionGroups.get(name), flags);
2006        }
2007    }
2008
2009    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2010        // reader
2011        synchronized (mPackages) {
2012            final int N = mPermissionGroups.size();
2013            ArrayList<PermissionGroupInfo> out
2014                    = new ArrayList<PermissionGroupInfo>(N);
2015            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2016                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2017            }
2018            return out;
2019        }
2020    }
2021
2022    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2023            int userId) {
2024        if (!sUserManager.exists(userId)) return null;
2025        PackageSetting ps = mSettings.mPackages.get(packageName);
2026        if (ps != null) {
2027            if (ps.pkg == null) {
2028                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2029                        flags, userId);
2030                if (pInfo != null) {
2031                    return pInfo.applicationInfo;
2032                }
2033                return null;
2034            }
2035            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2036                    ps.readUserState(userId), userId);
2037        }
2038        return null;
2039    }
2040
2041    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2042            int userId) {
2043        if (!sUserManager.exists(userId)) return null;
2044        PackageSetting ps = mSettings.mPackages.get(packageName);
2045        if (ps != null) {
2046            PackageParser.Package pkg = ps.pkg;
2047            if (pkg == null) {
2048                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2049                    return null;
2050                }
2051                pkg = new PackageParser.Package(packageName);
2052                pkg.applicationInfo.packageName = packageName;
2053                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2054                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2055                pkg.applicationInfo.sourceDir = ps.codePathString;
2056                pkg.applicationInfo.dataDir =
2057                        getDataPathForPackage(packageName, 0).getPath();
2058                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2059                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2060            }
2061            return generatePackageInfo(pkg, flags, userId);
2062        }
2063        return null;
2064    }
2065
2066    @Override
2067    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2068        if (!sUserManager.exists(userId)) return null;
2069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2070        // writer
2071        synchronized (mPackages) {
2072            PackageParser.Package p = mPackages.get(packageName);
2073            if (DEBUG_PACKAGE_INFO) Log.v(
2074                    TAG, "getApplicationInfo " + packageName
2075                    + ": " + p);
2076            if (p != null) {
2077                PackageSetting ps = mSettings.mPackages.get(packageName);
2078                if (ps == null) return null;
2079                // Note: isEnabledLP() does not apply here - always return info
2080                return PackageParser.generateApplicationInfo(
2081                        p, flags, ps.readUserState(userId), userId);
2082            }
2083            if ("android".equals(packageName)||"system".equals(packageName)) {
2084                return mAndroidApplication;
2085            }
2086            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2087                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2088            }
2089        }
2090        return null;
2091    }
2092
2093
2094    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2095        mContext.enforceCallingOrSelfPermission(
2096                android.Manifest.permission.CLEAR_APP_CACHE, null);
2097        // Queue up an async operation since clearing cache may take a little while.
2098        mHandler.post(new Runnable() {
2099            public void run() {
2100                mHandler.removeCallbacks(this);
2101                int retCode = -1;
2102                synchronized (mInstallLock) {
2103                    retCode = mInstaller.freeCache(freeStorageSize);
2104                    if (retCode < 0) {
2105                        Slog.w(TAG, "Couldn't clear application caches");
2106                    }
2107                }
2108                if (observer != null) {
2109                    try {
2110                        observer.onRemoveCompleted(null, (retCode >= 0));
2111                    } catch (RemoteException e) {
2112                        Slog.w(TAG, "RemoveException when invoking call back");
2113                    }
2114                }
2115            }
2116        });
2117    }
2118
2119    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2120        mContext.enforceCallingOrSelfPermission(
2121                android.Manifest.permission.CLEAR_APP_CACHE, null);
2122        // Queue up an async operation since clearing cache may take a little while.
2123        mHandler.post(new Runnable() {
2124            public void run() {
2125                mHandler.removeCallbacks(this);
2126                int retCode = -1;
2127                synchronized (mInstallLock) {
2128                    retCode = mInstaller.freeCache(freeStorageSize);
2129                    if (retCode < 0) {
2130                        Slog.w(TAG, "Couldn't clear application caches");
2131                    }
2132                }
2133                if(pi != null) {
2134                    try {
2135                        // Callback via pending intent
2136                        int code = (retCode >= 0) ? 1 : 0;
2137                        pi.sendIntent(null, code, null,
2138                                null, null);
2139                    } catch (SendIntentException e1) {
2140                        Slog.i(TAG, "Failed to send pending intent");
2141                    }
2142                }
2143            }
2144        });
2145    }
2146
2147    @Override
2148    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2149        if (!sUserManager.exists(userId)) return null;
2150        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2151        synchronized (mPackages) {
2152            PackageParser.Activity a = mActivities.mActivities.get(component);
2153
2154            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2155            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2156                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2157                if (ps == null) return null;
2158                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2159                        userId);
2160            }
2161            if (mResolveComponentName.equals(component)) {
2162                return mResolveActivity;
2163            }
2164        }
2165        return null;
2166    }
2167
2168    @Override
2169    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2170            String resolvedType) {
2171        synchronized (mPackages) {
2172            PackageParser.Activity a = mActivities.mActivities.get(component);
2173            if (a == null) {
2174                return false;
2175            }
2176            for (int i=0; i<a.intents.size(); i++) {
2177                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2178                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2179                    return true;
2180                }
2181            }
2182            return false;
2183        }
2184    }
2185
2186    @Override
2187    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2188        if (!sUserManager.exists(userId)) return null;
2189        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2190        synchronized (mPackages) {
2191            PackageParser.Activity a = mReceivers.mActivities.get(component);
2192            if (DEBUG_PACKAGE_INFO) Log.v(
2193                TAG, "getReceiverInfo " + component + ": " + a);
2194            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2195                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2196                if (ps == null) return null;
2197                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2198                        userId);
2199            }
2200        }
2201        return null;
2202    }
2203
2204    @Override
2205    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2206        if (!sUserManager.exists(userId)) return null;
2207        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2208        synchronized (mPackages) {
2209            PackageParser.Service s = mServices.mServices.get(component);
2210            if (DEBUG_PACKAGE_INFO) Log.v(
2211                TAG, "getServiceInfo " + component + ": " + s);
2212            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2213                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2214                if (ps == null) return null;
2215                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2216                        userId);
2217            }
2218        }
2219        return null;
2220    }
2221
2222    @Override
2223    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2224        if (!sUserManager.exists(userId)) return null;
2225        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2226        synchronized (mPackages) {
2227            PackageParser.Provider p = mProviders.mProviders.get(component);
2228            if (DEBUG_PACKAGE_INFO) Log.v(
2229                TAG, "getProviderInfo " + component + ": " + p);
2230            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2231                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2232                if (ps == null) return null;
2233                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2234                        userId);
2235            }
2236        }
2237        return null;
2238    }
2239
2240    public String[] getSystemSharedLibraryNames() {
2241        Set<String> libSet;
2242        synchronized (mPackages) {
2243            libSet = mSharedLibraries.keySet();
2244            int size = libSet.size();
2245            if (size > 0) {
2246                String[] libs = new String[size];
2247                libSet.toArray(libs);
2248                return libs;
2249            }
2250        }
2251        return null;
2252    }
2253
2254    public FeatureInfo[] getSystemAvailableFeatures() {
2255        Collection<FeatureInfo> featSet;
2256        synchronized (mPackages) {
2257            featSet = mAvailableFeatures.values();
2258            int size = featSet.size();
2259            if (size > 0) {
2260                FeatureInfo[] features = new FeatureInfo[size+1];
2261                featSet.toArray(features);
2262                FeatureInfo fi = new FeatureInfo();
2263                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2264                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2265                features[size] = fi;
2266                return features;
2267            }
2268        }
2269        return null;
2270    }
2271
2272    public boolean hasSystemFeature(String name) {
2273        synchronized (mPackages) {
2274            return mAvailableFeatures.containsKey(name);
2275        }
2276    }
2277
2278    private void checkValidCaller(int uid, int userId) {
2279        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2280            return;
2281
2282        throw new SecurityException("Caller uid=" + uid
2283                + " is not privileged to communicate with user=" + userId);
2284    }
2285
2286    public int checkPermission(String permName, String pkgName) {
2287        synchronized (mPackages) {
2288            PackageParser.Package p = mPackages.get(pkgName);
2289            if (p != null && p.mExtras != null) {
2290                PackageSetting ps = (PackageSetting)p.mExtras;
2291                if (ps.sharedUser != null) {
2292                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2293                        return PackageManager.PERMISSION_GRANTED;
2294                    }
2295                } else if (ps.grantedPermissions.contains(permName)) {
2296                    return PackageManager.PERMISSION_GRANTED;
2297                }
2298            }
2299        }
2300        return PackageManager.PERMISSION_DENIED;
2301    }
2302
2303    public int checkUidPermission(String permName, int uid) {
2304        synchronized (mPackages) {
2305            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2306            if (obj != null) {
2307                GrantedPermissions gp = (GrantedPermissions)obj;
2308                if (gp.grantedPermissions.contains(permName)) {
2309                    return PackageManager.PERMISSION_GRANTED;
2310                }
2311            } else {
2312                HashSet<String> perms = mSystemPermissions.get(uid);
2313                if (perms != null && perms.contains(permName)) {
2314                    return PackageManager.PERMISSION_GRANTED;
2315                }
2316            }
2317        }
2318        return PackageManager.PERMISSION_DENIED;
2319    }
2320
2321    /**
2322     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2323     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2324     * @param message the message to log on security exception
2325     * @return
2326     */
2327    private void enforceCrossUserPermission(int callingUid, int userId,
2328            boolean requireFullPermission, String message) {
2329        if (userId < 0) {
2330            throw new IllegalArgumentException("Invalid userId " + userId);
2331        }
2332        if (userId == UserHandle.getUserId(callingUid)) return;
2333        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2334            if (requireFullPermission) {
2335                mContext.enforceCallingOrSelfPermission(
2336                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2337            } else {
2338                try {
2339                    mContext.enforceCallingOrSelfPermission(
2340                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2341                } catch (SecurityException se) {
2342                    mContext.enforceCallingOrSelfPermission(
2343                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2344                }
2345            }
2346        }
2347    }
2348
2349    private BasePermission findPermissionTreeLP(String permName) {
2350        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2351            if (permName.startsWith(bp.name) &&
2352                    permName.length() > bp.name.length() &&
2353                    permName.charAt(bp.name.length()) == '.') {
2354                return bp;
2355            }
2356        }
2357        return null;
2358    }
2359
2360    private BasePermission checkPermissionTreeLP(String permName) {
2361        if (permName != null) {
2362            BasePermission bp = findPermissionTreeLP(permName);
2363            if (bp != null) {
2364                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2365                    return bp;
2366                }
2367                throw new SecurityException("Calling uid "
2368                        + Binder.getCallingUid()
2369                        + " is not allowed to add to permission tree "
2370                        + bp.name + " owned by uid " + bp.uid);
2371            }
2372        }
2373        throw new SecurityException("No permission tree found for " + permName);
2374    }
2375
2376    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2377        if (s1 == null) {
2378            return s2 == null;
2379        }
2380        if (s2 == null) {
2381            return false;
2382        }
2383        if (s1.getClass() != s2.getClass()) {
2384            return false;
2385        }
2386        return s1.equals(s2);
2387    }
2388
2389    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2390        if (pi1.icon != pi2.icon) return false;
2391        if (pi1.logo != pi2.logo) return false;
2392        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2393        if (!compareStrings(pi1.name, pi2.name)) return false;
2394        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2395        // We'll take care of setting this one.
2396        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2397        // These are not currently stored in settings.
2398        //if (!compareStrings(pi1.group, pi2.group)) return false;
2399        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2400        //if (pi1.labelRes != pi2.labelRes) return false;
2401        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2402        return true;
2403    }
2404
2405    int permissionInfoFootprint(PermissionInfo info) {
2406        int size = info.name.length();
2407        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2408        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2409        return size;
2410    }
2411
2412    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2413        int size = 0;
2414        for (BasePermission perm : mSettings.mPermissions.values()) {
2415            if (perm.uid == tree.uid) {
2416                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2417            }
2418        }
2419        return size;
2420    }
2421
2422    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2423        // We calculate the max size of permissions defined by this uid and throw
2424        // if that plus the size of 'info' would exceed our stated maximum.
2425        if (tree.uid != Process.SYSTEM_UID) {
2426            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2427            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2428                throw new SecurityException("Permission tree size cap exceeded");
2429            }
2430        }
2431    }
2432
2433    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2434        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2435            throw new SecurityException("Label must be specified in permission");
2436        }
2437        BasePermission tree = checkPermissionTreeLP(info.name);
2438        BasePermission bp = mSettings.mPermissions.get(info.name);
2439        boolean added = bp == null;
2440        boolean changed = true;
2441        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2442        if (added) {
2443            enforcePermissionCapLocked(info, tree);
2444            bp = new BasePermission(info.name, tree.sourcePackage,
2445                    BasePermission.TYPE_DYNAMIC);
2446        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2447            throw new SecurityException(
2448                    "Not allowed to modify non-dynamic permission "
2449                    + info.name);
2450        } else {
2451            if (bp.protectionLevel == fixedLevel
2452                    && bp.perm.owner.equals(tree.perm.owner)
2453                    && bp.uid == tree.uid
2454                    && comparePermissionInfos(bp.perm.info, info)) {
2455                changed = false;
2456            }
2457        }
2458        bp.protectionLevel = fixedLevel;
2459        info = new PermissionInfo(info);
2460        info.protectionLevel = fixedLevel;
2461        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2462        bp.perm.info.packageName = tree.perm.info.packageName;
2463        bp.uid = tree.uid;
2464        if (added) {
2465            mSettings.mPermissions.put(info.name, bp);
2466        }
2467        if (changed) {
2468            if (!async) {
2469                mSettings.writeLPr();
2470            } else {
2471                scheduleWriteSettingsLocked();
2472            }
2473        }
2474        return added;
2475    }
2476
2477    public boolean addPermission(PermissionInfo info) {
2478        synchronized (mPackages) {
2479            return addPermissionLocked(info, false);
2480        }
2481    }
2482
2483    public boolean addPermissionAsync(PermissionInfo info) {
2484        synchronized (mPackages) {
2485            return addPermissionLocked(info, true);
2486        }
2487    }
2488
2489    public void removePermission(String name) {
2490        synchronized (mPackages) {
2491            checkPermissionTreeLP(name);
2492            BasePermission bp = mSettings.mPermissions.get(name);
2493            if (bp != null) {
2494                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2495                    throw new SecurityException(
2496                            "Not allowed to modify non-dynamic permission "
2497                            + name);
2498                }
2499                mSettings.mPermissions.remove(name);
2500                mSettings.writeLPr();
2501            }
2502        }
2503    }
2504
2505    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2506        int index = pkg.requestedPermissions.indexOf(bp.name);
2507        if (index == -1) {
2508            throw new SecurityException("Package " + pkg.packageName
2509                    + " has not requested permission " + bp.name);
2510        }
2511        boolean isNormal =
2512                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2513                        == PermissionInfo.PROTECTION_NORMAL);
2514        boolean isDangerous =
2515                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2516                        == PermissionInfo.PROTECTION_DANGEROUS);
2517        boolean isDevelopment =
2518                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2519
2520        if (!isNormal && !isDangerous && !isDevelopment) {
2521            throw new SecurityException("Permission " + bp.name
2522                    + " is not a changeable permission type");
2523        }
2524
2525        if (isNormal || isDangerous) {
2526            if (pkg.requestedPermissionsRequired.get(index)) {
2527                throw new SecurityException("Can't change " + bp.name
2528                        + ". It is required by the application");
2529            }
2530        }
2531    }
2532
2533    public void grantPermission(String packageName, String permissionName) {
2534        mContext.enforceCallingOrSelfPermission(
2535                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2536        synchronized (mPackages) {
2537            final PackageParser.Package pkg = mPackages.get(packageName);
2538            if (pkg == null) {
2539                throw new IllegalArgumentException("Unknown package: " + packageName);
2540            }
2541            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2542            if (bp == null) {
2543                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2544            }
2545
2546            checkGrantRevokePermissions(pkg, bp);
2547
2548            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2549            if (ps == null) {
2550                return;
2551            }
2552            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2553            if (gp.grantedPermissions.add(permissionName)) {
2554                if (ps.haveGids) {
2555                    gp.gids = appendInts(gp.gids, bp.gids);
2556                }
2557                mSettings.writeLPr();
2558            }
2559        }
2560    }
2561
2562    public void revokePermission(String packageName, String permissionName) {
2563        int changedAppId = -1;
2564
2565        synchronized (mPackages) {
2566            final PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg == null) {
2568                throw new IllegalArgumentException("Unknown package: " + packageName);
2569            }
2570            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2571                mContext.enforceCallingOrSelfPermission(
2572                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2573            }
2574            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2575            if (bp == null) {
2576                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2577            }
2578
2579            checkGrantRevokePermissions(pkg, bp);
2580
2581            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2582            if (ps == null) {
2583                return;
2584            }
2585            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2586            if (gp.grantedPermissions.remove(permissionName)) {
2587                gp.grantedPermissions.remove(permissionName);
2588                if (ps.haveGids) {
2589                    gp.gids = removeInts(gp.gids, bp.gids);
2590                }
2591                mSettings.writeLPr();
2592                changedAppId = ps.appId;
2593            }
2594        }
2595
2596        if (changedAppId >= 0) {
2597            // We changed the perm on someone, kill its processes.
2598            IActivityManager am = ActivityManagerNative.getDefault();
2599            if (am != null) {
2600                final int callingUserId = UserHandle.getCallingUserId();
2601                final long ident = Binder.clearCallingIdentity();
2602                try {
2603                    //XXX we should only revoke for the calling user's app permissions,
2604                    // but for now we impact all users.
2605                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2606                    //        "revoke " + permissionName);
2607                    int[] users = sUserManager.getUserIds();
2608                    for (int user : users) {
2609                        am.killUid(UserHandle.getUid(user, changedAppId),
2610                                "revoke " + permissionName);
2611                    }
2612                } catch (RemoteException e) {
2613                } finally {
2614                    Binder.restoreCallingIdentity(ident);
2615                }
2616            }
2617        }
2618    }
2619
2620    public boolean isProtectedBroadcast(String actionName) {
2621        synchronized (mPackages) {
2622            return mProtectedBroadcasts.contains(actionName);
2623        }
2624    }
2625
2626    public int checkSignatures(String pkg1, String pkg2) {
2627        synchronized (mPackages) {
2628            final PackageParser.Package p1 = mPackages.get(pkg1);
2629            final PackageParser.Package p2 = mPackages.get(pkg2);
2630            if (p1 == null || p1.mExtras == null
2631                    || p2 == null || p2.mExtras == null) {
2632                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2633            }
2634            return compareSignatures(p1.mSignatures, p2.mSignatures);
2635        }
2636    }
2637
2638    public int checkUidSignatures(int uid1, int uid2) {
2639        // Map to base uids.
2640        uid1 = UserHandle.getAppId(uid1);
2641        uid2 = UserHandle.getAppId(uid2);
2642        // reader
2643        synchronized (mPackages) {
2644            Signature[] s1;
2645            Signature[] s2;
2646            Object obj = mSettings.getUserIdLPr(uid1);
2647            if (obj != null) {
2648                if (obj instanceof SharedUserSetting) {
2649                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2650                } else if (obj instanceof PackageSetting) {
2651                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2652                } else {
2653                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2654                }
2655            } else {
2656                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2657            }
2658            obj = mSettings.getUserIdLPr(uid2);
2659            if (obj != null) {
2660                if (obj instanceof SharedUserSetting) {
2661                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2662                } else if (obj instanceof PackageSetting) {
2663                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2664                } else {
2665                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2666                }
2667            } else {
2668                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2669            }
2670            return compareSignatures(s1, s2);
2671        }
2672    }
2673
2674    /**
2675     * Compares two sets of signatures. Returns:
2676     * <br />
2677     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2678     * <br />
2679     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2680     * <br />
2681     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2682     * <br />
2683     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2684     * <br />
2685     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2686     */
2687    static int compareSignatures(Signature[] s1, Signature[] s2) {
2688        if (s1 == null) {
2689            return s2 == null
2690                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2691                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2692        }
2693
2694        if (s2 == null) {
2695            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2696        }
2697
2698        if (s1.length != s2.length) {
2699            return PackageManager.SIGNATURE_NO_MATCH;
2700        }
2701
2702        // Since both signature sets are of size 1, we can compare without HashSets.
2703        if (s1.length == 1) {
2704            return s1[0].equals(s2[0]) ?
2705                    PackageManager.SIGNATURE_MATCH :
2706                    PackageManager.SIGNATURE_NO_MATCH;
2707        }
2708
2709        HashSet<Signature> set1 = new HashSet<Signature>();
2710        for (Signature sig : s1) {
2711            set1.add(sig);
2712        }
2713        HashSet<Signature> set2 = new HashSet<Signature>();
2714        for (Signature sig : s2) {
2715            set2.add(sig);
2716        }
2717        // Make sure s2 contains all signatures in s1.
2718        if (set1.equals(set2)) {
2719            return PackageManager.SIGNATURE_MATCH;
2720        }
2721        return PackageManager.SIGNATURE_NO_MATCH;
2722    }
2723
2724    /**
2725     * If the database version for this type of package (internal storage or
2726     * external storage) is less than the version where package signatures
2727     * were updated, return true.
2728     */
2729    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2730        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2731                DatabaseVersion.SIGNATURE_END_ENTITY))
2732                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2733                        DatabaseVersion.SIGNATURE_END_ENTITY));
2734    }
2735
2736    /**
2737     * Used for backward compatibility to make sure any packages with
2738     * certificate chains get upgraded to the new style. {@code existingSigs}
2739     * will be in the old format (since they were stored on disk from before the
2740     * system upgrade) and {@code scannedSigs} will be in the newer format.
2741     */
2742    private int compareSignaturesCompat(PackageSignatures existingSigs,
2743            PackageParser.Package scannedPkg) {
2744        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2745            return PackageManager.SIGNATURE_NO_MATCH;
2746        }
2747
2748        HashSet<Signature> existingSet = new HashSet<Signature>();
2749        for (Signature sig : existingSigs.mSignatures) {
2750            existingSet.add(sig);
2751        }
2752        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2753        for (Signature sig : scannedPkg.mSignatures) {
2754            try {
2755                Signature[] chainSignatures = sig.getChainSignatures();
2756                for (Signature chainSig : chainSignatures) {
2757                    scannedCompatSet.add(chainSig);
2758                }
2759            } catch (CertificateEncodingException e) {
2760                scannedCompatSet.add(sig);
2761            }
2762        }
2763        /*
2764         * Make sure the expanded scanned set contains all signatures in the
2765         * existing one.
2766         */
2767        if (scannedCompatSet.equals(existingSet)) {
2768            // Migrate the old signatures to the new scheme.
2769            existingSigs.assignSignatures(scannedPkg.mSignatures);
2770            // The new KeySets will be re-added later in the scanning process.
2771            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2772            return PackageManager.SIGNATURE_MATCH;
2773        }
2774        return PackageManager.SIGNATURE_NO_MATCH;
2775    }
2776
2777    public String[] getPackagesForUid(int uid) {
2778        uid = UserHandle.getAppId(uid);
2779        // reader
2780        synchronized (mPackages) {
2781            Object obj = mSettings.getUserIdLPr(uid);
2782            if (obj instanceof SharedUserSetting) {
2783                final SharedUserSetting sus = (SharedUserSetting) obj;
2784                final int N = sus.packages.size();
2785                final String[] res = new String[N];
2786                final Iterator<PackageSetting> it = sus.packages.iterator();
2787                int i = 0;
2788                while (it.hasNext()) {
2789                    res[i++] = it.next().name;
2790                }
2791                return res;
2792            } else if (obj instanceof PackageSetting) {
2793                final PackageSetting ps = (PackageSetting) obj;
2794                return new String[] { ps.name };
2795            }
2796        }
2797        return null;
2798    }
2799
2800    public String getNameForUid(int uid) {
2801        // reader
2802        synchronized (mPackages) {
2803            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2804            if (obj instanceof SharedUserSetting) {
2805                final SharedUserSetting sus = (SharedUserSetting) obj;
2806                return sus.name + ":" + sus.userId;
2807            } else if (obj instanceof PackageSetting) {
2808                final PackageSetting ps = (PackageSetting) obj;
2809                return ps.name;
2810            }
2811        }
2812        return null;
2813    }
2814
2815    public int getUidForSharedUser(String sharedUserName) {
2816        if(sharedUserName == null) {
2817            return -1;
2818        }
2819        // reader
2820        synchronized (mPackages) {
2821            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2822            if (suid == null) {
2823                return -1;
2824            }
2825            return suid.userId;
2826        }
2827    }
2828
2829    public int getFlagsForUid(int uid) {
2830        synchronized (mPackages) {
2831            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2832            if (obj instanceof SharedUserSetting) {
2833                final SharedUserSetting sus = (SharedUserSetting) obj;
2834                return sus.pkgFlags;
2835            } else if (obj instanceof PackageSetting) {
2836                final PackageSetting ps = (PackageSetting) obj;
2837                return ps.pkgFlags;
2838            }
2839        }
2840        return 0;
2841    }
2842
2843    @Override
2844    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2845            int flags, int userId) {
2846        if (!sUserManager.exists(userId)) return null;
2847        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2848        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2849        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2850    }
2851
2852    @Override
2853    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2854            IntentFilter filter, int match, ComponentName activity) {
2855        final int userId = UserHandle.getCallingUserId();
2856        if (DEBUG_PREFERRED) {
2857            Log.v(TAG, "setLastChosenActivity intent=" + intent
2858                + " resolvedType=" + resolvedType
2859                + " flags=" + flags
2860                + " filter=" + filter
2861                + " match=" + match
2862                + " activity=" + activity);
2863            filter.dump(new PrintStreamPrinter(System.out), "    ");
2864        }
2865        intent.setComponent(null);
2866        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2867        // Find any earlier preferred or last chosen entries and nuke them
2868        findPreferredActivity(intent, resolvedType,
2869                flags, query, 0, false, true, false, userId);
2870        // Add the new activity as the last chosen for this filter
2871        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2872    }
2873
2874    @Override
2875    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2876        final int userId = UserHandle.getCallingUserId();
2877        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2878        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2879        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2880                false, false, false, userId);
2881    }
2882
2883    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2884            int flags, List<ResolveInfo> query, int userId) {
2885        if (query != null) {
2886            final int N = query.size();
2887            if (N == 1) {
2888                return query.get(0);
2889            } else if (N > 1) {
2890                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2891                // If there is more than one activity with the same priority,
2892                // then let the user decide between them.
2893                ResolveInfo r0 = query.get(0);
2894                ResolveInfo r1 = query.get(1);
2895                if (DEBUG_INTENT_MATCHING || debug) {
2896                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2897                            + r1.activityInfo.name + "=" + r1.priority);
2898                }
2899                // If the first activity has a higher priority, or a different
2900                // default, then it is always desireable to pick it.
2901                if (r0.priority != r1.priority
2902                        || r0.preferredOrder != r1.preferredOrder
2903                        || r0.isDefault != r1.isDefault) {
2904                    return query.get(0);
2905                }
2906                // If we have saved a preference for a preferred activity for
2907                // this Intent, use that.
2908                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2909                        flags, query, r0.priority, true, false, debug, userId);
2910                if (ri != null) {
2911                    return ri;
2912                }
2913                if (userId != 0) {
2914                    ri = new ResolveInfo(mResolveInfo);
2915                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2916                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2917                            ri.activityInfo.applicationInfo);
2918                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2919                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2920                    return ri;
2921                }
2922                return mResolveInfo;
2923            }
2924        }
2925        return null;
2926    }
2927
2928    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2929            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2930        final int N = query.size();
2931        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2932                .get(userId);
2933        // Get the list of persistent preferred activities that handle the intent
2934        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2935        List<PersistentPreferredActivity> pprefs = ppir != null
2936                ? ppir.queryIntent(intent, resolvedType,
2937                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2938                : null;
2939        if (pprefs != null && pprefs.size() > 0) {
2940            final int M = pprefs.size();
2941            for (int i=0; i<M; i++) {
2942                final PersistentPreferredActivity ppa = pprefs.get(i);
2943                if (DEBUG_PREFERRED || debug) {
2944                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2945                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2946                            + "\n  component=" + ppa.mComponent);
2947                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2948                }
2949                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2950                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2951                if (DEBUG_PREFERRED || debug) {
2952                    Slog.v(TAG, "Found persistent preferred activity:");
2953                    if (ai != null) {
2954                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2955                    } else {
2956                        Slog.v(TAG, "  null");
2957                    }
2958                }
2959                if (ai == null) {
2960                    // This previously registered persistent preferred activity
2961                    // component is no longer known. Ignore it and do NOT remove it.
2962                    continue;
2963                }
2964                for (int j=0; j<N; j++) {
2965                    final ResolveInfo ri = query.get(j);
2966                    if (!ri.activityInfo.applicationInfo.packageName
2967                            .equals(ai.applicationInfo.packageName)) {
2968                        continue;
2969                    }
2970                    if (!ri.activityInfo.name.equals(ai.name)) {
2971                        continue;
2972                    }
2973                    //  Found a persistent preference that can handle the intent.
2974                    if (DEBUG_PREFERRED || debug) {
2975                        Slog.v(TAG, "Returning persistent preferred activity: " +
2976                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
2977                    }
2978                    return ri;
2979                }
2980            }
2981        }
2982        return null;
2983    }
2984
2985    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
2986            List<ResolveInfo> query, int priority, boolean always,
2987            boolean removeMatches, boolean debug, int userId) {
2988        if (!sUserManager.exists(userId)) return null;
2989        // writer
2990        synchronized (mPackages) {
2991            if (intent.getSelector() != null) {
2992                intent = intent.getSelector();
2993            }
2994            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2995
2996            // Try to find a matching persistent preferred activity.
2997            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
2998                    debug, userId);
2999
3000            // If a persistent preferred activity matched, use it.
3001            if (pri != null) {
3002                return pri;
3003            }
3004
3005            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3006            // Get the list of preferred activities that handle the intent
3007            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3008            List<PreferredActivity> prefs = pir != null
3009                    ? pir.queryIntent(intent, resolvedType,
3010                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3011                    : null;
3012            if (prefs != null && prefs.size() > 0) {
3013                // First figure out how good the original match set is.
3014                // We will only allow preferred activities that came
3015                // from the same match quality.
3016                int match = 0;
3017
3018                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3019
3020                final int N = query.size();
3021                for (int j=0; j<N; j++) {
3022                    final ResolveInfo ri = query.get(j);
3023                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3024                            + ": 0x" + Integer.toHexString(match));
3025                    if (ri.match > match) {
3026                        match = ri.match;
3027                    }
3028                }
3029
3030                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3031                        + Integer.toHexString(match));
3032
3033                match &= IntentFilter.MATCH_CATEGORY_MASK;
3034                final int M = prefs.size();
3035                for (int i=0; i<M; i++) {
3036                    final PreferredActivity pa = prefs.get(i);
3037                    if (DEBUG_PREFERRED || debug) {
3038                        Slog.v(TAG, "Checking PreferredActivity ds="
3039                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3040                                + "\n  component=" + pa.mPref.mComponent);
3041                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3042                    }
3043                    if (pa.mPref.mMatch != match) {
3044                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3045                                + Integer.toHexString(pa.mPref.mMatch));
3046                        continue;
3047                    }
3048                    // If it's not an "always" type preferred activity and that's what we're
3049                    // looking for, skip it.
3050                    if (always && !pa.mPref.mAlways) {
3051                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3052                        continue;
3053                    }
3054                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3055                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3056                    if (DEBUG_PREFERRED || debug) {
3057                        Slog.v(TAG, "Found preferred activity:");
3058                        if (ai != null) {
3059                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3060                        } else {
3061                            Slog.v(TAG, "  null");
3062                        }
3063                    }
3064                    if (ai == null) {
3065                        // This previously registered preferred activity
3066                        // component is no longer known.  Most likely an update
3067                        // to the app was installed and in the new version this
3068                        // component no longer exists.  Clean it up by removing
3069                        // it from the preferred activities list, and skip it.
3070                        Slog.w(TAG, "Removing dangling preferred activity: "
3071                                + pa.mPref.mComponent);
3072                        pir.removeFilter(pa);
3073                        continue;
3074                    }
3075                    for (int j=0; j<N; j++) {
3076                        final ResolveInfo ri = query.get(j);
3077                        if (!ri.activityInfo.applicationInfo.packageName
3078                                .equals(ai.applicationInfo.packageName)) {
3079                            continue;
3080                        }
3081                        if (!ri.activityInfo.name.equals(ai.name)) {
3082                            continue;
3083                        }
3084
3085                        if (removeMatches) {
3086                            pir.removeFilter(pa);
3087                            if (DEBUG_PREFERRED) {
3088                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3089                            }
3090                            break;
3091                        }
3092
3093                        // Okay we found a previously set preferred or last chosen app.
3094                        // If the result set is different from when this
3095                        // was created, we need to clear it and re-ask the
3096                        // user their preference, if we're looking for an "always" type entry.
3097                        if (always && !pa.mPref.sameSet(query, priority)) {
3098                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3099                                    + intent + " type " + resolvedType);
3100                            if (DEBUG_PREFERRED) {
3101                                Slog.v(TAG, "Removing preferred activity since set changed "
3102                                        + pa.mPref.mComponent);
3103                            }
3104                            pir.removeFilter(pa);
3105                            // Re-add the filter as a "last chosen" entry (!always)
3106                            PreferredActivity lastChosen = new PreferredActivity(
3107                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3108                            pir.addFilter(lastChosen);
3109                            mSettings.writePackageRestrictionsLPr(userId);
3110                            return null;
3111                        }
3112
3113                        // Yay! Either the set matched or we're looking for the last chosen
3114                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3115                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3116                        mSettings.writePackageRestrictionsLPr(userId);
3117                        return ri;
3118                    }
3119                }
3120            }
3121            mSettings.writePackageRestrictionsLPr(userId);
3122        }
3123        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3124        return null;
3125    }
3126
3127    @Override
3128    public List<ResolveInfo> queryIntentActivities(Intent intent,
3129            String resolvedType, int flags, int userId) {
3130        if (!sUserManager.exists(userId)) return Collections.emptyList();
3131        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3132        ComponentName comp = intent.getComponent();
3133        if (comp == null) {
3134            if (intent.getSelector() != null) {
3135                intent = intent.getSelector();
3136                comp = intent.getComponent();
3137            }
3138        }
3139
3140        if (comp != null) {
3141            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3142            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3143            if (ai != null) {
3144                final ResolveInfo ri = new ResolveInfo();
3145                ri.activityInfo = ai;
3146                list.add(ri);
3147            }
3148            return list;
3149        }
3150
3151        // reader
3152        synchronized (mPackages) {
3153            final String pkgName = intent.getPackage();
3154            if (pkgName == null) {
3155                return mActivities.queryIntent(intent, resolvedType, flags, userId);
3156            }
3157            final PackageParser.Package pkg = mPackages.get(pkgName);
3158            if (pkg != null) {
3159                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3160                        pkg.activities, userId);
3161            }
3162            return new ArrayList<ResolveInfo>();
3163        }
3164    }
3165
3166    @Override
3167    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3168            Intent[] specifics, String[] specificTypes, Intent intent,
3169            String resolvedType, int flags, int userId) {
3170        if (!sUserManager.exists(userId)) return Collections.emptyList();
3171        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3172                "query intent activity options");
3173        final String resultsAction = intent.getAction();
3174
3175        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3176                | PackageManager.GET_RESOLVED_FILTER, userId);
3177
3178        if (DEBUG_INTENT_MATCHING) {
3179            Log.v(TAG, "Query " + intent + ": " + results);
3180        }
3181
3182        int specificsPos = 0;
3183        int N;
3184
3185        // todo: note that the algorithm used here is O(N^2).  This
3186        // isn't a problem in our current environment, but if we start running
3187        // into situations where we have more than 5 or 10 matches then this
3188        // should probably be changed to something smarter...
3189
3190        // First we go through and resolve each of the specific items
3191        // that were supplied, taking care of removing any corresponding
3192        // duplicate items in the generic resolve list.
3193        if (specifics != null) {
3194            for (int i=0; i<specifics.length; i++) {
3195                final Intent sintent = specifics[i];
3196                if (sintent == null) {
3197                    continue;
3198                }
3199
3200                if (DEBUG_INTENT_MATCHING) {
3201                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3202                }
3203
3204                String action = sintent.getAction();
3205                if (resultsAction != null && resultsAction.equals(action)) {
3206                    // If this action was explicitly requested, then don't
3207                    // remove things that have it.
3208                    action = null;
3209                }
3210
3211                ResolveInfo ri = null;
3212                ActivityInfo ai = null;
3213
3214                ComponentName comp = sintent.getComponent();
3215                if (comp == null) {
3216                    ri = resolveIntent(
3217                        sintent,
3218                        specificTypes != null ? specificTypes[i] : null,
3219                            flags, userId);
3220                    if (ri == null) {
3221                        continue;
3222                    }
3223                    if (ri == mResolveInfo) {
3224                        // ACK!  Must do something better with this.
3225                    }
3226                    ai = ri.activityInfo;
3227                    comp = new ComponentName(ai.applicationInfo.packageName,
3228                            ai.name);
3229                } else {
3230                    ai = getActivityInfo(comp, flags, userId);
3231                    if (ai == null) {
3232                        continue;
3233                    }
3234                }
3235
3236                // Look for any generic query activities that are duplicates
3237                // of this specific one, and remove them from the results.
3238                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3239                N = results.size();
3240                int j;
3241                for (j=specificsPos; j<N; j++) {
3242                    ResolveInfo sri = results.get(j);
3243                    if ((sri.activityInfo.name.equals(comp.getClassName())
3244                            && sri.activityInfo.applicationInfo.packageName.equals(
3245                                    comp.getPackageName()))
3246                        || (action != null && sri.filter.matchAction(action))) {
3247                        results.remove(j);
3248                        if (DEBUG_INTENT_MATCHING) Log.v(
3249                            TAG, "Removing duplicate item from " + j
3250                            + " due to specific " + specificsPos);
3251                        if (ri == null) {
3252                            ri = sri;
3253                        }
3254                        j--;
3255                        N--;
3256                    }
3257                }
3258
3259                // Add this specific item to its proper place.
3260                if (ri == null) {
3261                    ri = new ResolveInfo();
3262                    ri.activityInfo = ai;
3263                }
3264                results.add(specificsPos, ri);
3265                ri.specificIndex = i;
3266                specificsPos++;
3267            }
3268        }
3269
3270        // Now we go through the remaining generic results and remove any
3271        // duplicate actions that are found here.
3272        N = results.size();
3273        for (int i=specificsPos; i<N-1; i++) {
3274            final ResolveInfo rii = results.get(i);
3275            if (rii.filter == null) {
3276                continue;
3277            }
3278
3279            // Iterate over all of the actions of this result's intent
3280            // filter...  typically this should be just one.
3281            final Iterator<String> it = rii.filter.actionsIterator();
3282            if (it == null) {
3283                continue;
3284            }
3285            while (it.hasNext()) {
3286                final String action = it.next();
3287                if (resultsAction != null && resultsAction.equals(action)) {
3288                    // If this action was explicitly requested, then don't
3289                    // remove things that have it.
3290                    continue;
3291                }
3292                for (int j=i+1; j<N; j++) {
3293                    final ResolveInfo rij = results.get(j);
3294                    if (rij.filter != null && rij.filter.hasAction(action)) {
3295                        results.remove(j);
3296                        if (DEBUG_INTENT_MATCHING) Log.v(
3297                            TAG, "Removing duplicate item from " + j
3298                            + " due to action " + action + " at " + i);
3299                        j--;
3300                        N--;
3301                    }
3302                }
3303            }
3304
3305            // If the caller didn't request filter information, drop it now
3306            // so we don't have to marshall/unmarshall it.
3307            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3308                rii.filter = null;
3309            }
3310        }
3311
3312        // Filter out the caller activity if so requested.
3313        if (caller != null) {
3314            N = results.size();
3315            for (int i=0; i<N; i++) {
3316                ActivityInfo ainfo = results.get(i).activityInfo;
3317                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3318                        && caller.getClassName().equals(ainfo.name)) {
3319                    results.remove(i);
3320                    break;
3321                }
3322            }
3323        }
3324
3325        // If the caller didn't request filter information,
3326        // drop them now so we don't have to
3327        // marshall/unmarshall it.
3328        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3329            N = results.size();
3330            for (int i=0; i<N; i++) {
3331                results.get(i).filter = null;
3332            }
3333        }
3334
3335        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3336        return results;
3337    }
3338
3339    @Override
3340    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3341            int userId) {
3342        if (!sUserManager.exists(userId)) return Collections.emptyList();
3343        ComponentName comp = intent.getComponent();
3344        if (comp == null) {
3345            if (intent.getSelector() != null) {
3346                intent = intent.getSelector();
3347                comp = intent.getComponent();
3348            }
3349        }
3350        if (comp != null) {
3351            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3352            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3353            if (ai != null) {
3354                ResolveInfo ri = new ResolveInfo();
3355                ri.activityInfo = ai;
3356                list.add(ri);
3357            }
3358            return list;
3359        }
3360
3361        // reader
3362        synchronized (mPackages) {
3363            String pkgName = intent.getPackage();
3364            if (pkgName == null) {
3365                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3366            }
3367            final PackageParser.Package pkg = mPackages.get(pkgName);
3368            if (pkg != null) {
3369                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3370                        userId);
3371            }
3372            return null;
3373        }
3374    }
3375
3376    @Override
3377    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3378        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3379        if (!sUserManager.exists(userId)) return null;
3380        if (query != null) {
3381            if (query.size() >= 1) {
3382                // If there is more than one service with the same priority,
3383                // just arbitrarily pick the first one.
3384                return query.get(0);
3385            }
3386        }
3387        return null;
3388    }
3389
3390    @Override
3391    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3392            int userId) {
3393        if (!sUserManager.exists(userId)) return Collections.emptyList();
3394        ComponentName comp = intent.getComponent();
3395        if (comp == null) {
3396            if (intent.getSelector() != null) {
3397                intent = intent.getSelector();
3398                comp = intent.getComponent();
3399            }
3400        }
3401        if (comp != null) {
3402            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3403            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3404            if (si != null) {
3405                final ResolveInfo ri = new ResolveInfo();
3406                ri.serviceInfo = si;
3407                list.add(ri);
3408            }
3409            return list;
3410        }
3411
3412        // reader
3413        synchronized (mPackages) {
3414            String pkgName = intent.getPackage();
3415            if (pkgName == null) {
3416                return mServices.queryIntent(intent, resolvedType, flags, userId);
3417            }
3418            final PackageParser.Package pkg = mPackages.get(pkgName);
3419            if (pkg != null) {
3420                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3421                        userId);
3422            }
3423            return null;
3424        }
3425    }
3426
3427    @Override
3428    public List<ResolveInfo> queryIntentContentProviders(
3429            Intent intent, String resolvedType, int flags, int userId) {
3430        if (!sUserManager.exists(userId)) return Collections.emptyList();
3431        ComponentName comp = intent.getComponent();
3432        if (comp == null) {
3433            if (intent.getSelector() != null) {
3434                intent = intent.getSelector();
3435                comp = intent.getComponent();
3436            }
3437        }
3438        if (comp != null) {
3439            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3440            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3441            if (pi != null) {
3442                final ResolveInfo ri = new ResolveInfo();
3443                ri.providerInfo = pi;
3444                list.add(ri);
3445            }
3446            return list;
3447        }
3448
3449        // reader
3450        synchronized (mPackages) {
3451            String pkgName = intent.getPackage();
3452            if (pkgName == null) {
3453                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3454            }
3455            final PackageParser.Package pkg = mPackages.get(pkgName);
3456            if (pkg != null) {
3457                return mProviders.queryIntentForPackage(
3458                        intent, resolvedType, flags, pkg.providers, userId);
3459            }
3460            return null;
3461        }
3462    }
3463
3464    @Override
3465    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3466        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3467
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3469
3470        // writer
3471        synchronized (mPackages) {
3472            ArrayList<PackageInfo> list;
3473            if (listUninstalled) {
3474                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3475                for (PackageSetting ps : mSettings.mPackages.values()) {
3476                    PackageInfo pi;
3477                    if (ps.pkg != null) {
3478                        pi = generatePackageInfo(ps.pkg, flags, userId);
3479                    } else {
3480                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3481                    }
3482                    if (pi != null) {
3483                        list.add(pi);
3484                    }
3485                }
3486            } else {
3487                list = new ArrayList<PackageInfo>(mPackages.size());
3488                for (PackageParser.Package p : mPackages.values()) {
3489                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3490                    if (pi != null) {
3491                        list.add(pi);
3492                    }
3493                }
3494            }
3495
3496            return new ParceledListSlice<PackageInfo>(list);
3497        }
3498    }
3499
3500    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3501            String[] permissions, boolean[] tmp, int flags, int userId) {
3502        int numMatch = 0;
3503        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3504        for (int i=0; i<permissions.length; i++) {
3505            if (gp.grantedPermissions.contains(permissions[i])) {
3506                tmp[i] = true;
3507                numMatch++;
3508            } else {
3509                tmp[i] = false;
3510            }
3511        }
3512        if (numMatch == 0) {
3513            return;
3514        }
3515        PackageInfo pi;
3516        if (ps.pkg != null) {
3517            pi = generatePackageInfo(ps.pkg, flags, userId);
3518        } else {
3519            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3520        }
3521        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3522            if (numMatch == permissions.length) {
3523                pi.requestedPermissions = permissions;
3524            } else {
3525                pi.requestedPermissions = new String[numMatch];
3526                numMatch = 0;
3527                for (int i=0; i<permissions.length; i++) {
3528                    if (tmp[i]) {
3529                        pi.requestedPermissions[numMatch] = permissions[i];
3530                        numMatch++;
3531                    }
3532                }
3533            }
3534        }
3535        list.add(pi);
3536    }
3537
3538    @Override
3539    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3540            String[] permissions, int flags, int userId) {
3541        if (!sUserManager.exists(userId)) return null;
3542        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3543
3544        // writer
3545        synchronized (mPackages) {
3546            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3547            boolean[] tmpBools = new boolean[permissions.length];
3548            if (listUninstalled) {
3549                for (PackageSetting ps : mSettings.mPackages.values()) {
3550                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3551                }
3552            } else {
3553                for (PackageParser.Package pkg : mPackages.values()) {
3554                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3555                    if (ps != null) {
3556                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3557                                userId);
3558                    }
3559                }
3560            }
3561
3562            return new ParceledListSlice<PackageInfo>(list);
3563        }
3564    }
3565
3566    @Override
3567    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3570
3571        // writer
3572        synchronized (mPackages) {
3573            ArrayList<ApplicationInfo> list;
3574            if (listUninstalled) {
3575                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3576                for (PackageSetting ps : mSettings.mPackages.values()) {
3577                    ApplicationInfo ai;
3578                    if (ps.pkg != null) {
3579                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3580                                ps.readUserState(userId), userId);
3581                    } else {
3582                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3583                    }
3584                    if (ai != null) {
3585                        list.add(ai);
3586                    }
3587                }
3588            } else {
3589                list = new ArrayList<ApplicationInfo>(mPackages.size());
3590                for (PackageParser.Package p : mPackages.values()) {
3591                    if (p.mExtras != null) {
3592                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3593                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3594                        if (ai != null) {
3595                            list.add(ai);
3596                        }
3597                    }
3598                }
3599            }
3600
3601            return new ParceledListSlice<ApplicationInfo>(list);
3602        }
3603    }
3604
3605    public List<ApplicationInfo> getPersistentApplications(int flags) {
3606        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3607
3608        // reader
3609        synchronized (mPackages) {
3610            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3611            final int userId = UserHandle.getCallingUserId();
3612            while (i.hasNext()) {
3613                final PackageParser.Package p = i.next();
3614                if (p.applicationInfo != null
3615                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3616                        && (!mSafeMode || isSystemApp(p))) {
3617                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3618                    if (ps != null) {
3619                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3620                                ps.readUserState(userId), userId);
3621                        if (ai != null) {
3622                            finalList.add(ai);
3623                        }
3624                    }
3625                }
3626            }
3627        }
3628
3629        return finalList;
3630    }
3631
3632    @Override
3633    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3634        if (!sUserManager.exists(userId)) return null;
3635        // reader
3636        synchronized (mPackages) {
3637            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3638            PackageSetting ps = provider != null
3639                    ? mSettings.mPackages.get(provider.owner.packageName)
3640                    : null;
3641            return ps != null
3642                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3643                    && (!mSafeMode || (provider.info.applicationInfo.flags
3644                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3645                    ? PackageParser.generateProviderInfo(provider, flags,
3646                            ps.readUserState(userId), userId)
3647                    : null;
3648        }
3649    }
3650
3651    /**
3652     * @deprecated
3653     */
3654    @Deprecated
3655    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3656        // reader
3657        synchronized (mPackages) {
3658            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3659                    .entrySet().iterator();
3660            final int userId = UserHandle.getCallingUserId();
3661            while (i.hasNext()) {
3662                Map.Entry<String, PackageParser.Provider> entry = i.next();
3663                PackageParser.Provider p = entry.getValue();
3664                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3665
3666                if (ps != null && p.syncable
3667                        && (!mSafeMode || (p.info.applicationInfo.flags
3668                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3669                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3670                            ps.readUserState(userId), userId);
3671                    if (info != null) {
3672                        outNames.add(entry.getKey());
3673                        outInfo.add(info);
3674                    }
3675                }
3676            }
3677        }
3678    }
3679
3680    public List<ProviderInfo> queryContentProviders(String processName,
3681            int uid, int flags) {
3682        ArrayList<ProviderInfo> finalList = null;
3683        // reader
3684        synchronized (mPackages) {
3685            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3686            final int userId = processName != null ?
3687                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3688            while (i.hasNext()) {
3689                final PackageParser.Provider p = i.next();
3690                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3691                if (ps != null && p.info.authority != null
3692                        && (processName == null
3693                                || (p.info.processName.equals(processName)
3694                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3695                        && mSettings.isEnabledLPr(p.info, flags, userId)
3696                        && (!mSafeMode
3697                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3698                    if (finalList == null) {
3699                        finalList = new ArrayList<ProviderInfo>(3);
3700                    }
3701                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3702                            ps.readUserState(userId), userId);
3703                    if (info != null) {
3704                        finalList.add(info);
3705                    }
3706                }
3707            }
3708        }
3709
3710        if (finalList != null) {
3711            Collections.sort(finalList, mProviderInitOrderSorter);
3712        }
3713
3714        return finalList;
3715    }
3716
3717    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3718            int flags) {
3719        // reader
3720        synchronized (mPackages) {
3721            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3722            return PackageParser.generateInstrumentationInfo(i, flags);
3723        }
3724    }
3725
3726    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3727            int flags) {
3728        ArrayList<InstrumentationInfo> finalList =
3729            new ArrayList<InstrumentationInfo>();
3730
3731        // reader
3732        synchronized (mPackages) {
3733            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3734            while (i.hasNext()) {
3735                final PackageParser.Instrumentation p = i.next();
3736                if (targetPackage == null
3737                        || targetPackage.equals(p.info.targetPackage)) {
3738                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3739                            flags);
3740                    if (ii != null) {
3741                        finalList.add(ii);
3742                    }
3743                }
3744            }
3745        }
3746
3747        return finalList;
3748    }
3749
3750    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3751        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3752        if (overlays == null) {
3753            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3754            return;
3755        }
3756        for (PackageParser.Package opkg : overlays.values()) {
3757            // Not much to do if idmap fails: we already logged the error
3758            // and we certainly don't want to abort installation of pkg simply
3759            // because an overlay didn't fit properly. For these reasons,
3760            // ignore the return value of createIdmapForPackagePairLI.
3761            createIdmapForPackagePairLI(pkg, opkg);
3762        }
3763    }
3764
3765    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3766            PackageParser.Package opkg) {
3767        if (!opkg.mTrustedOverlay) {
3768            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3769                    opkg.mScanPath + ": overlay not trusted");
3770            return false;
3771        }
3772        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3773        if (overlaySet == null) {
3774            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3775                    opkg.mScanPath + " but target package has no known overlays");
3776            return false;
3777        }
3778        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3779        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3780            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3781            return false;
3782        }
3783        PackageParser.Package[] overlayArray =
3784            overlaySet.values().toArray(new PackageParser.Package[0]);
3785        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3786            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3787                return p1.mOverlayPriority - p2.mOverlayPriority;
3788            }
3789        };
3790        Arrays.sort(overlayArray, cmp);
3791
3792        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3793        int i = 0;
3794        for (PackageParser.Package p : overlayArray) {
3795            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3796        }
3797        return true;
3798    }
3799
3800    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3801        String[] files = dir.list();
3802        if (files == null) {
3803            Log.d(TAG, "No files in app dir " + dir);
3804            return;
3805        }
3806
3807        if (DEBUG_PACKAGE_SCANNING) {
3808            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3809                    + " flags=0x" + Integer.toHexString(flags));
3810        }
3811
3812        int i;
3813        for (i=0; i<files.length; i++) {
3814            File file = new File(dir, files[i]);
3815            if (!isPackageFilename(files[i])) {
3816                // Ignore entries which are not apk's
3817                continue;
3818            }
3819            PackageParser.Package pkg = scanPackageLI(file,
3820                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3821            // Don't mess around with apps in system partition.
3822            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3823                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3824                // Delete the apk
3825                Slog.w(TAG, "Cleaning up failed install of " + file);
3826                file.delete();
3827            }
3828        }
3829    }
3830
3831    private static File getSettingsProblemFile() {
3832        File dataDir = Environment.getDataDirectory();
3833        File systemDir = new File(dataDir, "system");
3834        File fname = new File(systemDir, "uiderrors.txt");
3835        return fname;
3836    }
3837
3838    static void reportSettingsProblem(int priority, String msg) {
3839        try {
3840            File fname = getSettingsProblemFile();
3841            FileOutputStream out = new FileOutputStream(fname, true);
3842            PrintWriter pw = new FastPrintWriter(out);
3843            SimpleDateFormat formatter = new SimpleDateFormat();
3844            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3845            pw.println(dateString + ": " + msg);
3846            pw.close();
3847            FileUtils.setPermissions(
3848                    fname.toString(),
3849                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3850                    -1, -1);
3851        } catch (java.io.IOException e) {
3852        }
3853        Slog.println(priority, TAG, msg);
3854    }
3855
3856    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3857            PackageParser.Package pkg, File srcFile, int parseFlags) {
3858        if (ps != null
3859                && ps.codePath.equals(srcFile)
3860                && ps.timeStamp == srcFile.lastModified()
3861                && !isCompatSignatureUpdateNeeded(pkg)) {
3862            if (ps.signatures.mSignatures != null
3863                    && ps.signatures.mSignatures.length != 0) {
3864                // Optimization: reuse the existing cached certificates
3865                // if the package appears to be unchanged.
3866                pkg.mSignatures = ps.signatures.mSignatures;
3867                return true;
3868            }
3869
3870            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3871        } else {
3872            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3873        }
3874
3875        if (!pp.collectCertificates(pkg, parseFlags)) {
3876            mLastScanError = pp.getParseError();
3877            return false;
3878        }
3879        return true;
3880    }
3881
3882    /*
3883     *  Scan a package and return the newly parsed package.
3884     *  Returns null in case of errors and the error code is stored in mLastScanError
3885     */
3886    private PackageParser.Package scanPackageLI(File scanFile,
3887            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3888        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3889        String scanPath = scanFile.getPath();
3890        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3891        parseFlags |= mDefParseFlags;
3892        PackageParser pp = new PackageParser(scanPath);
3893        pp.setSeparateProcesses(mSeparateProcesses);
3894        pp.setOnlyCoreApps(mOnlyCore);
3895        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3896                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3897
3898        if (pkg == null) {
3899            mLastScanError = pp.getParseError();
3900            return null;
3901        }
3902
3903        PackageSetting ps = null;
3904        PackageSetting updatedPkg;
3905        // reader
3906        synchronized (mPackages) {
3907            // Look to see if we already know about this package.
3908            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3909            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3910                // This package has been renamed to its original name.  Let's
3911                // use that.
3912                ps = mSettings.peekPackageLPr(oldName);
3913            }
3914            // If there was no original package, see one for the real package name.
3915            if (ps == null) {
3916                ps = mSettings.peekPackageLPr(pkg.packageName);
3917            }
3918            // Check to see if this package could be hiding/updating a system
3919            // package.  Must look for it either under the original or real
3920            // package name depending on our state.
3921            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3922            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3923        }
3924        boolean updatedPkgBetter = false;
3925        // First check if this is a system package that may involve an update
3926        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3927            if (ps != null && !ps.codePath.equals(scanFile)) {
3928                // The path has changed from what was last scanned...  check the
3929                // version of the new path against what we have stored to determine
3930                // what to do.
3931                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3932                if (pkg.mVersionCode < ps.versionCode) {
3933                    // The system package has been updated and the code path does not match
3934                    // Ignore entry. Skip it.
3935                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3936                            + " ignored: updated version " + ps.versionCode
3937                            + " better than this " + pkg.mVersionCode);
3938                    if (!updatedPkg.codePath.equals(scanFile)) {
3939                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3940                                + ps.name + " changing from " + updatedPkg.codePathString
3941                                + " to " + scanFile);
3942                        updatedPkg.codePath = scanFile;
3943                        updatedPkg.codePathString = scanFile.toString();
3944                        // This is the point at which we know that the system-disk APK
3945                        // for this package has moved during a reboot (e.g. due to an OTA),
3946                        // so we need to reevaluate it for privilege policy.
3947                        if (locationIsPrivileged(scanFile)) {
3948                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3949                        }
3950                    }
3951                    updatedPkg.pkg = pkg;
3952                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3953                    return null;
3954                } else {
3955                    // The current app on the system partion is better than
3956                    // what we have updated to on the data partition; switch
3957                    // back to the system partition version.
3958                    // At this point, its safely assumed that package installation for
3959                    // apps in system partition will go through. If not there won't be a working
3960                    // version of the app
3961                    // writer
3962                    synchronized (mPackages) {
3963                        // Just remove the loaded entries from package lists.
3964                        mPackages.remove(ps.name);
3965                    }
3966                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3967                            + "reverting from " + ps.codePathString
3968                            + ": new version " + pkg.mVersionCode
3969                            + " better than installed " + ps.versionCode);
3970
3971                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3972                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3973                    synchronized (mInstallLock) {
3974                        args.cleanUpResourcesLI();
3975                    }
3976                    synchronized (mPackages) {
3977                        mSettings.enableSystemPackageLPw(ps.name);
3978                    }
3979                    updatedPkgBetter = true;
3980                }
3981            }
3982        }
3983
3984        if (updatedPkg != null) {
3985            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3986            // initially
3987            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3988
3989            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
3990            // flag set initially
3991            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3992                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
3993            }
3994        }
3995        // Verify certificates against what was last scanned
3996        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3997            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3998            return null;
3999        }
4000
4001        /*
4002         * A new system app appeared, but we already had a non-system one of the
4003         * same name installed earlier.
4004         */
4005        boolean shouldHideSystemApp = false;
4006        if (updatedPkg == null && ps != null
4007                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4008            /*
4009             * Check to make sure the signatures match first. If they don't,
4010             * wipe the installed application and its data.
4011             */
4012            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4013                    != PackageManager.SIGNATURE_MATCH) {
4014                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4015                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4016                ps = null;
4017            } else {
4018                /*
4019                 * If the newly-added system app is an older version than the
4020                 * already installed version, hide it. It will be scanned later
4021                 * and re-added like an update.
4022                 */
4023                if (pkg.mVersionCode < ps.versionCode) {
4024                    shouldHideSystemApp = true;
4025                } else {
4026                    /*
4027                     * The newly found system app is a newer version that the
4028                     * one previously installed. Simply remove the
4029                     * already-installed application and replace it with our own
4030                     * while keeping the application data.
4031                     */
4032                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4033                            + ps.codePathString + ": new version " + pkg.mVersionCode
4034                            + " better than installed " + ps.versionCode);
4035                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4036                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
4037                    synchronized (mInstallLock) {
4038                        args.cleanUpResourcesLI();
4039                    }
4040                }
4041            }
4042        }
4043
4044        // The apk is forward locked (not public) if its code and resources
4045        // are kept in different files. (except for app in either system or
4046        // vendor path).
4047        // TODO grab this value from PackageSettings
4048        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4049            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4050                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4051            }
4052        }
4053
4054        String codePath = null;
4055        String resPath = null;
4056        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4057            if (ps != null && ps.resourcePathString != null) {
4058                resPath = ps.resourcePathString;
4059            } else {
4060                // Should not happen at all. Just log an error.
4061                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4062            }
4063        } else {
4064            resPath = pkg.mScanPath;
4065        }
4066
4067        codePath = pkg.mScanPath;
4068        // Set application objects path explicitly.
4069        setApplicationInfoPaths(pkg, codePath, resPath);
4070        // Applications can run with the primary Cpu Abi unless otherwise is specified
4071        pkg.applicationInfo.requiredCpuAbi = null;
4072        // Note that we invoke the following method only if we are about to unpack an application
4073        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4074                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4075
4076        /*
4077         * If the system app should be overridden by a previously installed
4078         * data, hide the system app now and let the /data/app scan pick it up
4079         * again.
4080         */
4081        if (shouldHideSystemApp) {
4082            synchronized (mPackages) {
4083                /*
4084                 * We have to grant systems permissions before we hide, because
4085                 * grantPermissions will assume the package update is trying to
4086                 * expand its permissions.
4087                 */
4088                grantPermissionsLPw(pkg, true);
4089                mSettings.disableSystemPackageLPw(pkg.packageName);
4090            }
4091        }
4092
4093        return scannedPkg;
4094    }
4095
4096    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4097            String destResPath) {
4098        pkg.mPath = pkg.mScanPath = destCodePath;
4099        pkg.applicationInfo.sourceDir = destCodePath;
4100        pkg.applicationInfo.publicSourceDir = destResPath;
4101    }
4102
4103    private static String fixProcessName(String defProcessName,
4104            String processName, int uid) {
4105        if (processName == null) {
4106            return defProcessName;
4107        }
4108        return processName;
4109    }
4110
4111    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4112        if (pkgSetting.signatures.mSignatures != null) {
4113            // Already existing package. Make sure signatures match
4114            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4115                    == PackageManager.SIGNATURE_MATCH;
4116            if (!match) {
4117                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4118                        == PackageManager.SIGNATURE_MATCH;
4119            }
4120            if (!match) {
4121                Slog.e(TAG, "Package " + pkg.packageName
4122                        + " signatures do not match the previously installed version; ignoring!");
4123                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4124                return false;
4125            }
4126        }
4127        // Check for shared user signatures
4128        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4129            // Already existing package. Make sure signatures match
4130            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4131                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4132            if (!match) {
4133                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4134                        == PackageManager.SIGNATURE_MATCH;
4135            }
4136            if (!match) {
4137                Slog.e(TAG, "Package " + pkg.packageName
4138                        + " has no signatures that match those in shared user "
4139                        + pkgSetting.sharedUser.name + "; ignoring!");
4140                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4141                return false;
4142            }
4143        }
4144        return true;
4145    }
4146
4147    /**
4148     * Enforces that only the system UID or root's UID can call a method exposed
4149     * via Binder.
4150     *
4151     * @param message used as message if SecurityException is thrown
4152     * @throws SecurityException if the caller is not system or root
4153     */
4154    private static final void enforceSystemOrRoot(String message) {
4155        final int uid = Binder.getCallingUid();
4156        if (uid != Process.SYSTEM_UID && uid != 0) {
4157            throw new SecurityException(message);
4158        }
4159    }
4160
4161    public void performBootDexOpt() {
4162        HashSet<PackageParser.Package> pkgs = null;
4163        synchronized (mPackages) {
4164            pkgs = mDeferredDexOpt;
4165            mDeferredDexOpt = null;
4166        }
4167        if (pkgs != null) {
4168            int i = 0;
4169            for (PackageParser.Package pkg : pkgs) {
4170                if (!isFirstBoot()) {
4171                    i++;
4172                    try {
4173                        ActivityManagerNative.getDefault().showBootMessage(
4174                                mContext.getResources().getString(
4175                                        com.android.internal.R.string.android_upgrading_apk,
4176                                        i, pkgs.size()), true);
4177                    } catch (RemoteException e) {
4178                    }
4179                }
4180                PackageParser.Package p = pkg;
4181                synchronized (mInstallLock) {
4182                    if (!p.mDidDexOpt) {
4183                        performDexOptLI(p, false, false, true);
4184                    }
4185                }
4186            }
4187        }
4188    }
4189
4190    public boolean performDexOpt(String packageName) {
4191        enforceSystemOrRoot("Only the system can request dexopt be performed");
4192
4193        if (!mNoDexOpt) {
4194            return false;
4195        }
4196
4197        PackageParser.Package p;
4198        synchronized (mPackages) {
4199            p = mPackages.get(packageName);
4200            if (p == null || p.mDidDexOpt) {
4201                return false;
4202            }
4203        }
4204        synchronized (mInstallLock) {
4205            return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED;
4206        }
4207    }
4208
4209    private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer,
4210            HashSet<String> done) {
4211        for (int i=0; i<libs.size(); i++) {
4212            PackageParser.Package libPkg;
4213            String libName;
4214            synchronized (mPackages) {
4215                libName = libs.get(i);
4216                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4217                if (lib != null && lib.apk != null) {
4218                    libPkg = mPackages.get(lib.apk);
4219                } else {
4220                    libPkg = null;
4221                }
4222            }
4223            if (libPkg != null && !done.contains(libName)) {
4224                performDexOptLI(libPkg, forceDex, defer, done);
4225            }
4226        }
4227    }
4228
4229    static final int DEX_OPT_SKIPPED = 0;
4230    static final int DEX_OPT_PERFORMED = 1;
4231    static final int DEX_OPT_DEFERRED = 2;
4232    static final int DEX_OPT_FAILED = -1;
4233
4234    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4235            HashSet<String> done) {
4236        boolean performed = false;
4237        if (done != null) {
4238            done.add(pkg.packageName);
4239            if (pkg.usesLibraries != null) {
4240                performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done);
4241            }
4242            if (pkg.usesOptionalLibraries != null) {
4243                performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done);
4244            }
4245        }
4246        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4247            String path = pkg.mScanPath;
4248            int ret = 0;
4249            try {
4250                if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, pkg.packageName,
4251                                                                             defer)) {
4252                    if (!forceDex && defer) {
4253                        if (mDeferredDexOpt == null) {
4254                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4255                        }
4256                        mDeferredDexOpt.add(pkg);
4257                        return DEX_OPT_DEFERRED;
4258                    } else {
4259                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4260                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4261                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4262                                                pkg.packageName);
4263                        pkg.mDidDexOpt = true;
4264                        performed = true;
4265                    }
4266                }
4267            } catch (FileNotFoundException e) {
4268                Slog.w(TAG, "Apk not found for dexopt: " + path);
4269                ret = -1;
4270            } catch (IOException e) {
4271                Slog.w(TAG, "IOException reading apk: " + path, e);
4272                ret = -1;
4273            } catch (dalvik.system.StaleDexCacheError e) {
4274                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4275                ret = -1;
4276            } catch (Exception e) {
4277                Slog.w(TAG, "Exception when doing dexopt : ", e);
4278                ret = -1;
4279            }
4280            if (ret < 0) {
4281                //error from installer
4282                return DEX_OPT_FAILED;
4283            }
4284        }
4285
4286        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4287    }
4288
4289    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4290            boolean inclDependencies) {
4291        HashSet<String> done;
4292        boolean performed = false;
4293        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4294            done = new HashSet<String>();
4295            done.add(pkg.packageName);
4296        } else {
4297            done = null;
4298        }
4299        return performDexOptLI(pkg, forceDex, defer, done);
4300    }
4301
4302    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4303        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4304            Slog.w(TAG, "Unable to update from " + oldPkg.name
4305                    + " to " + newPkg.packageName
4306                    + ": old package not in system partition");
4307            return false;
4308        } else if (mPackages.get(oldPkg.name) != null) {
4309            Slog.w(TAG, "Unable to update from " + oldPkg.name
4310                    + " to " + newPkg.packageName
4311                    + ": old package still exists");
4312            return false;
4313        }
4314        return true;
4315    }
4316
4317    File getDataPathForUser(int userId) {
4318        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4319    }
4320
4321    private File getDataPathForPackage(String packageName, int userId) {
4322        /*
4323         * Until we fully support multiple users, return the directory we
4324         * previously would have. The PackageManagerTests will need to be
4325         * revised when this is changed back..
4326         */
4327        if (userId == 0) {
4328            return new File(mAppDataDir, packageName);
4329        } else {
4330            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4331                + File.separator + packageName);
4332        }
4333    }
4334
4335    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4336        int[] users = sUserManager.getUserIds();
4337        int res = mInstaller.install(packageName, uid, uid, seinfo);
4338        if (res < 0) {
4339            return res;
4340        }
4341        for (int user : users) {
4342            if (user != 0) {
4343                res = mInstaller.createUserData(packageName,
4344                        UserHandle.getUid(user, uid), user, seinfo);
4345                if (res < 0) {
4346                    return res;
4347                }
4348            }
4349        }
4350        return res;
4351    }
4352
4353    private int removeDataDirsLI(String packageName) {
4354        int[] users = sUserManager.getUserIds();
4355        int res = 0;
4356        for (int user : users) {
4357            int resInner = mInstaller.remove(packageName, user);
4358            if (resInner < 0) {
4359                res = resInner;
4360            }
4361        }
4362
4363        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4364        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4365        if (!nativeLibraryFile.delete()) {
4366            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4367        }
4368
4369        return res;
4370    }
4371
4372    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4373            PackageParser.Package changingLib) {
4374        if (file.path != null) {
4375            mTmpSharedLibraries[num] = file.path;
4376            return num+1;
4377        }
4378        PackageParser.Package p = mPackages.get(file.apk);
4379        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4380            // If we are doing this while in the middle of updating a library apk,
4381            // then we need to make sure to use that new apk for determining the
4382            // dependencies here.  (We haven't yet finished committing the new apk
4383            // to the package manager state.)
4384            if (p == null || p.packageName.equals(changingLib.packageName)) {
4385                p = changingLib;
4386            }
4387        }
4388        if (p != null) {
4389            String path = p.mPath;
4390            for (int i=0; i<num; i++) {
4391                if (mTmpSharedLibraries[i].equals(path)) {
4392                    return num;
4393                }
4394            }
4395            mTmpSharedLibraries[num] = p.mPath;
4396            return num+1;
4397        }
4398        return num;
4399    }
4400
4401    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4402            PackageParser.Package changingLib) {
4403        // We might be upgrading from a version of the platform that did not
4404        // provide per-package native library directories for system apps.
4405        // Fix that up here.
4406        if (isSystemApp(pkg)) {
4407            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4408            setInternalAppNativeLibraryPath(pkg, ps);
4409        }
4410
4411        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4412            if (mTmpSharedLibraries == null ||
4413                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4414                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4415            }
4416            int num = 0;
4417            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4418            for (int i=0; i<N; i++) {
4419                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4420                if (file == null) {
4421                    Slog.e(TAG, "Package " + pkg.packageName
4422                            + " requires unavailable shared library "
4423                            + pkg.usesLibraries.get(i) + "; failing!");
4424                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4425                    return false;
4426                }
4427                num = addSharedLibraryLPw(file, num, changingLib);
4428            }
4429            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4430            for (int i=0; i<N; i++) {
4431                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4432                if (file == null) {
4433                    Slog.w(TAG, "Package " + pkg.packageName
4434                            + " desires unavailable shared library "
4435                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4436                } else {
4437                    num = addSharedLibraryLPw(file, num, changingLib);
4438                }
4439            }
4440            if (num > 0) {
4441                pkg.usesLibraryFiles = new String[num];
4442                System.arraycopy(mTmpSharedLibraries, 0,
4443                        pkg.usesLibraryFiles, 0, num);
4444            } else {
4445                pkg.usesLibraryFiles = null;
4446            }
4447        }
4448        return true;
4449    }
4450
4451    private static boolean hasString(List<String> list, List<String> which) {
4452        if (list == null) {
4453            return false;
4454        }
4455        for (int i=list.size()-1; i>=0; i--) {
4456            for (int j=which.size()-1; j>=0; j--) {
4457                if (which.get(j).equals(list.get(i))) {
4458                    return true;
4459                }
4460            }
4461        }
4462        return false;
4463    }
4464
4465    private void updateAllSharedLibrariesLPw() {
4466        for (PackageParser.Package pkg : mPackages.values()) {
4467            updateSharedLibrariesLPw(pkg, null);
4468        }
4469    }
4470
4471    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4472            PackageParser.Package changingPkg) {
4473        ArrayList<PackageParser.Package> res = null;
4474        for (PackageParser.Package pkg : mPackages.values()) {
4475            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4476                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4477                if (res == null) {
4478                    res = new ArrayList<PackageParser.Package>();
4479                }
4480                res.add(pkg);
4481                updateSharedLibrariesLPw(pkg, changingPkg);
4482            }
4483        }
4484        return res;
4485    }
4486
4487    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4488            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4489        File scanFile = new File(pkg.mScanPath);
4490        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4491                pkg.applicationInfo.publicSourceDir == null) {
4492            // Bail out. The resource and code paths haven't been set.
4493            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4494            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4495            return null;
4496        }
4497
4498        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4499            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4500        }
4501
4502        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4503            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4504        }
4505
4506        if (mCustomResolverComponentName != null &&
4507                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4508            setUpCustomResolverActivity(pkg);
4509        }
4510
4511        if (pkg.packageName.equals("android")) {
4512            synchronized (mPackages) {
4513                if (mAndroidApplication != null) {
4514                    Slog.w(TAG, "*************************************************");
4515                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4516                    Slog.w(TAG, " file=" + scanFile);
4517                    Slog.w(TAG, "*************************************************");
4518                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4519                    return null;
4520                }
4521
4522                // Set up information for our fall-back user intent resolution activity.
4523                mPlatformPackage = pkg;
4524                pkg.mVersionCode = mSdkVersion;
4525                mAndroidApplication = pkg.applicationInfo;
4526
4527                if (!mResolverReplaced) {
4528                    mResolveActivity.applicationInfo = mAndroidApplication;
4529                    mResolveActivity.name = ResolverActivity.class.getName();
4530                    mResolveActivity.packageName = mAndroidApplication.packageName;
4531                    mResolveActivity.processName = "system:ui";
4532                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4533                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4534                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4535                    mResolveActivity.exported = true;
4536                    mResolveActivity.enabled = true;
4537                    mResolveInfo.activityInfo = mResolveActivity;
4538                    mResolveInfo.priority = 0;
4539                    mResolveInfo.preferredOrder = 0;
4540                    mResolveInfo.match = 0;
4541                    mResolveComponentName = new ComponentName(
4542                            mAndroidApplication.packageName, mResolveActivity.name);
4543                }
4544            }
4545        }
4546
4547        if (DEBUG_PACKAGE_SCANNING) {
4548            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4549                Log.d(TAG, "Scanning package " + pkg.packageName);
4550        }
4551
4552        if (mPackages.containsKey(pkg.packageName)
4553                || mSharedLibraries.containsKey(pkg.packageName)) {
4554            Slog.w(TAG, "Application package " + pkg.packageName
4555                    + " already installed.  Skipping duplicate.");
4556            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4557            return null;
4558        }
4559
4560        // Initialize package source and resource directories
4561        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4562        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4563
4564        SharedUserSetting suid = null;
4565        PackageSetting pkgSetting = null;
4566
4567        if (!isSystemApp(pkg)) {
4568            // Only system apps can use these features.
4569            pkg.mOriginalPackages = null;
4570            pkg.mRealPackage = null;
4571            pkg.mAdoptPermissions = null;
4572        }
4573
4574        // writer
4575        synchronized (mPackages) {
4576            if (pkg.mSharedUserId != null) {
4577                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4578                if (suid == null) {
4579                    Slog.w(TAG, "Creating application package " + pkg.packageName
4580                            + " for shared user failed");
4581                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4582                    return null;
4583                }
4584                if (DEBUG_PACKAGE_SCANNING) {
4585                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4586                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4587                                + "): packages=" + suid.packages);
4588                }
4589            }
4590
4591            // Check if we are renaming from an original package name.
4592            PackageSetting origPackage = null;
4593            String realName = null;
4594            if (pkg.mOriginalPackages != null) {
4595                // This package may need to be renamed to a previously
4596                // installed name.  Let's check on that...
4597                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4598                if (pkg.mOriginalPackages.contains(renamed)) {
4599                    // This package had originally been installed as the
4600                    // original name, and we have already taken care of
4601                    // transitioning to the new one.  Just update the new
4602                    // one to continue using the old name.
4603                    realName = pkg.mRealPackage;
4604                    if (!pkg.packageName.equals(renamed)) {
4605                        // Callers into this function may have already taken
4606                        // care of renaming the package; only do it here if
4607                        // it is not already done.
4608                        pkg.setPackageName(renamed);
4609                    }
4610
4611                } else {
4612                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4613                        if ((origPackage = mSettings.peekPackageLPr(
4614                                pkg.mOriginalPackages.get(i))) != null) {
4615                            // We do have the package already installed under its
4616                            // original name...  should we use it?
4617                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4618                                // New package is not compatible with original.
4619                                origPackage = null;
4620                                continue;
4621                            } else if (origPackage.sharedUser != null) {
4622                                // Make sure uid is compatible between packages.
4623                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4624                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4625                                            + " to " + pkg.packageName + ": old uid "
4626                                            + origPackage.sharedUser.name
4627                                            + " differs from " + pkg.mSharedUserId);
4628                                    origPackage = null;
4629                                    continue;
4630                                }
4631                            } else {
4632                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4633                                        + pkg.packageName + " to old name " + origPackage.name);
4634                            }
4635                            break;
4636                        }
4637                    }
4638                }
4639            }
4640
4641            if (mTransferedPackages.contains(pkg.packageName)) {
4642                Slog.w(TAG, "Package " + pkg.packageName
4643                        + " was transferred to another, but its .apk remains");
4644            }
4645
4646            // Just create the setting, don't add it yet. For already existing packages
4647            // the PkgSetting exists already and doesn't have to be created.
4648            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4649                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4650                    pkg.applicationInfo.requiredCpuAbi,
4651                    pkg.applicationInfo.flags, user, false);
4652            if (pkgSetting == null) {
4653                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4654                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4655                return null;
4656            }
4657
4658            if (pkgSetting.origPackage != null) {
4659                // If we are first transitioning from an original package,
4660                // fix up the new package's name now.  We need to do this after
4661                // looking up the package under its new name, so getPackageLP
4662                // can take care of fiddling things correctly.
4663                pkg.setPackageName(origPackage.name);
4664
4665                // File a report about this.
4666                String msg = "New package " + pkgSetting.realName
4667                        + " renamed to replace old package " + pkgSetting.name;
4668                reportSettingsProblem(Log.WARN, msg);
4669
4670                // Make a note of it.
4671                mTransferedPackages.add(origPackage.name);
4672
4673                // No longer need to retain this.
4674                pkgSetting.origPackage = null;
4675            }
4676
4677            if (realName != null) {
4678                // Make a note of it.
4679                mTransferedPackages.add(pkg.packageName);
4680            }
4681
4682            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4683                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4684            }
4685
4686            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4687                // Check all shared libraries and map to their actual file path.
4688                // We only do this here for apps not on a system dir, because those
4689                // are the only ones that can fail an install due to this.  We
4690                // will take care of the system apps by updating all of their
4691                // library paths after the scan is done.
4692                if (!updateSharedLibrariesLPw(pkg, null)) {
4693                    return null;
4694                }
4695            }
4696
4697            if (mFoundPolicyFile) {
4698                SELinuxMMAC.assignSeinfoValue(pkg);
4699            }
4700
4701            pkg.applicationInfo.uid = pkgSetting.appId;
4702            pkg.mExtras = pkgSetting;
4703
4704            if (!verifySignaturesLP(pkgSetting, pkg)) {
4705                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4706                    return null;
4707                }
4708                // The signature has changed, but this package is in the system
4709                // image...  let's recover!
4710                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4711                // However...  if this package is part of a shared user, but it
4712                // doesn't match the signature of the shared user, let's fail.
4713                // What this means is that you can't change the signatures
4714                // associated with an overall shared user, which doesn't seem all
4715                // that unreasonable.
4716                if (pkgSetting.sharedUser != null) {
4717                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4718                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4719                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4720                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4721                        return null;
4722                    }
4723                }
4724                // File a report about this.
4725                String msg = "System package " + pkg.packageName
4726                        + " signature changed; retaining data.";
4727                reportSettingsProblem(Log.WARN, msg);
4728            }
4729
4730            // Verify that this new package doesn't have any content providers
4731            // that conflict with existing packages.  Only do this if the
4732            // package isn't already installed, since we don't want to break
4733            // things that are installed.
4734            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4735                final int N = pkg.providers.size();
4736                int i;
4737                for (i=0; i<N; i++) {
4738                    PackageParser.Provider p = pkg.providers.get(i);
4739                    if (p.info.authority != null) {
4740                        String names[] = p.info.authority.split(";");
4741                        for (int j = 0; j < names.length; j++) {
4742                            if (mProvidersByAuthority.containsKey(names[j])) {
4743                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4744                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4745                                        " (in package " + pkg.applicationInfo.packageName +
4746                                        ") is already used by "
4747                                        + ((other != null && other.getComponentName() != null)
4748                                                ? other.getComponentName().getPackageName() : "?"));
4749                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4750                                return null;
4751                            }
4752                        }
4753                    }
4754                }
4755            }
4756
4757            if (pkg.mAdoptPermissions != null) {
4758                // This package wants to adopt ownership of permissions from
4759                // another package.
4760                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4761                    final String origName = pkg.mAdoptPermissions.get(i);
4762                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4763                    if (orig != null) {
4764                        if (verifyPackageUpdateLPr(orig, pkg)) {
4765                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4766                                    + pkg.packageName);
4767                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4768                        }
4769                    }
4770                }
4771            }
4772        }
4773
4774        final String pkgName = pkg.packageName;
4775
4776        final long scanFileTime = scanFile.lastModified();
4777        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4778        pkg.applicationInfo.processName = fixProcessName(
4779                pkg.applicationInfo.packageName,
4780                pkg.applicationInfo.processName,
4781                pkg.applicationInfo.uid);
4782
4783        File dataPath;
4784        if (mPlatformPackage == pkg) {
4785            // The system package is special.
4786            dataPath = new File (Environment.getDataDirectory(), "system");
4787            pkg.applicationInfo.dataDir = dataPath.getPath();
4788        } else {
4789            // This is a normal package, need to make its data directory.
4790            dataPath = getDataPathForPackage(pkg.packageName, 0);
4791
4792            boolean uidError = false;
4793
4794            if (dataPath.exists()) {
4795                int currentUid = 0;
4796                try {
4797                    StructStat stat = Os.stat(dataPath.getPath());
4798                    currentUid = stat.st_uid;
4799                } catch (ErrnoException e) {
4800                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4801                }
4802
4803                // If we have mismatched owners for the data path, we have a problem.
4804                if (currentUid != pkg.applicationInfo.uid) {
4805                    boolean recovered = false;
4806                    if (currentUid == 0) {
4807                        // The directory somehow became owned by root.  Wow.
4808                        // This is probably because the system was stopped while
4809                        // installd was in the middle of messing with its libs
4810                        // directory.  Ask installd to fix that.
4811                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4812                                pkg.applicationInfo.uid);
4813                        if (ret >= 0) {
4814                            recovered = true;
4815                            String msg = "Package " + pkg.packageName
4816                                    + " unexpectedly changed to uid 0; recovered to " +
4817                                    + pkg.applicationInfo.uid;
4818                            reportSettingsProblem(Log.WARN, msg);
4819                        }
4820                    }
4821                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4822                            || (scanMode&SCAN_BOOTING) != 0)) {
4823                        // If this is a system app, we can at least delete its
4824                        // current data so the application will still work.
4825                        int ret = removeDataDirsLI(pkgName);
4826                        if (ret >= 0) {
4827                            // TODO: Kill the processes first
4828                            // Old data gone!
4829                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4830                                    ? "System package " : "Third party package ";
4831                            String msg = prefix + pkg.packageName
4832                                    + " has changed from uid: "
4833                                    + currentUid + " to "
4834                                    + pkg.applicationInfo.uid + "; old data erased";
4835                            reportSettingsProblem(Log.WARN, msg);
4836                            recovered = true;
4837
4838                            // And now re-install the app.
4839                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4840                                                   pkg.applicationInfo.seinfo);
4841                            if (ret == -1) {
4842                                // Ack should not happen!
4843                                msg = prefix + pkg.packageName
4844                                        + " could not have data directory re-created after delete.";
4845                                reportSettingsProblem(Log.WARN, msg);
4846                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4847                                return null;
4848                            }
4849                        }
4850                        if (!recovered) {
4851                            mHasSystemUidErrors = true;
4852                        }
4853                    } else if (!recovered) {
4854                        // If we allow this install to proceed, we will be broken.
4855                        // Abort, abort!
4856                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4857                        return null;
4858                    }
4859                    if (!recovered) {
4860                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4861                            + pkg.applicationInfo.uid + "/fs_"
4862                            + currentUid;
4863                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4864                        String msg = "Package " + pkg.packageName
4865                                + " has mismatched uid: "
4866                                + currentUid + " on disk, "
4867                                + pkg.applicationInfo.uid + " in settings";
4868                        // writer
4869                        synchronized (mPackages) {
4870                            mSettings.mReadMessages.append(msg);
4871                            mSettings.mReadMessages.append('\n');
4872                            uidError = true;
4873                            if (!pkgSetting.uidError) {
4874                                reportSettingsProblem(Log.ERROR, msg);
4875                            }
4876                        }
4877                    }
4878                }
4879                pkg.applicationInfo.dataDir = dataPath.getPath();
4880                if (mShouldRestoreconData) {
4881                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
4882                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
4883                                pkg.applicationInfo.uid);
4884                }
4885            } else {
4886                if (DEBUG_PACKAGE_SCANNING) {
4887                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4888                        Log.v(TAG, "Want this data dir: " + dataPath);
4889                }
4890                //invoke installer to do the actual installation
4891                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4892                                           pkg.applicationInfo.seinfo);
4893                if (ret < 0) {
4894                    // Error from installer
4895                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4896                    return null;
4897                }
4898
4899                if (dataPath.exists()) {
4900                    pkg.applicationInfo.dataDir = dataPath.getPath();
4901                } else {
4902                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4903                    pkg.applicationInfo.dataDir = null;
4904                }
4905            }
4906
4907            /*
4908             * Set the data dir to the default "/data/data/<package name>/lib"
4909             * if we got here without anyone telling us different (e.g., apps
4910             * stored on SD card have their native libraries stored in the ASEC
4911             * container with the APK).
4912             *
4913             * This happens during an upgrade from a package settings file that
4914             * doesn't have a native library path attribute at all.
4915             */
4916            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4917                if (pkgSetting.nativeLibraryPathString == null) {
4918                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4919                } else {
4920                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4921                }
4922            }
4923            pkgSetting.uidError = uidError;
4924        }
4925
4926        String path = scanFile.getPath();
4927        /* Note: We don't want to unpack the native binaries for
4928         *        system applications, unless they have been updated
4929         *        (the binaries are already under /system/lib).
4930         *        Also, don't unpack libs for apps on the external card
4931         *        since they should have their libraries in the ASEC
4932         *        container already.
4933         *
4934         *        In other words, we're going to unpack the binaries
4935         *        only for non-system apps and system app upgrades.
4936         */
4937        if (pkg.applicationInfo.nativeLibraryDir != null) {
4938            try {
4939                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4940                final String dataPathString = dataPath.getCanonicalPath();
4941
4942                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4943                    /*
4944                     * Upgrading from a previous version of the OS sometimes
4945                     * leaves native libraries in the /data/data/<app>/lib
4946                     * directory for system apps even when they shouldn't be.
4947                     * Recent changes in the JNI library search path
4948                     * necessitates we remove those to match previous behavior.
4949                     */
4950                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4951                        Log.i(TAG, "removed obsolete native libraries for system package "
4952                                + path);
4953                    }
4954                } else {
4955                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4956                        /*
4957                         * Update native library dir if it starts with
4958                         * /data/data
4959                         */
4960                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4961                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
4962                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4963                        }
4964
4965                        try {
4966                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
4967                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
4968                                Slog.e(TAG, "Unable to copy native libraries");
4969                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4970                                return null;
4971                            }
4972
4973                            // We've successfully copied native libraries across, so we make a
4974                            // note of what ABI we're using
4975                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
4976                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
4977                            } else {
4978                                pkg.applicationInfo.requiredCpuAbi = null;
4979                            }
4980                        } catch (IOException e) {
4981                            Slog.e(TAG, "Unable to copy native libraries", e);
4982                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4983                            return null;
4984                        }
4985                    }
4986
4987                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4988                    final int[] userIds = sUserManager.getUserIds();
4989                    synchronized (mInstallLock) {
4990                        for (int userId : userIds) {
4991                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4992                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4993                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4994                                        + ")");
4995                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4996                                return null;
4997                            }
4998                        }
4999                    }
5000                }
5001            } catch (IOException ioe) {
5002                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5003            }
5004        }
5005        pkg.mScanPath = path;
5006
5007        if ((scanMode&SCAN_NO_DEX) == 0) {
5008            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5009                    == DEX_OPT_FAILED) {
5010                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5011                    removeDataDirsLI(pkg.packageName);
5012                }
5013
5014                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5015                return null;
5016            }
5017        }
5018
5019        if (mFactoryTest && pkg.requestedPermissions.contains(
5020                android.Manifest.permission.FACTORY_TEST)) {
5021            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5022        }
5023
5024        ArrayList<PackageParser.Package> clientLibPkgs = null;
5025
5026        // writer
5027        synchronized (mPackages) {
5028            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5029                // Only system apps can add new shared libraries.
5030                if (pkg.libraryNames != null) {
5031                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5032                        String name = pkg.libraryNames.get(i);
5033                        boolean allowed = false;
5034                        if (isUpdatedSystemApp(pkg)) {
5035                            // New library entries can only be added through the
5036                            // system image.  This is important to get rid of a lot
5037                            // of nasty edge cases: for example if we allowed a non-
5038                            // system update of the app to add a library, then uninstalling
5039                            // the update would make the library go away, and assumptions
5040                            // we made such as through app install filtering would now
5041                            // have allowed apps on the device which aren't compatible
5042                            // with it.  Better to just have the restriction here, be
5043                            // conservative, and create many fewer cases that can negatively
5044                            // impact the user experience.
5045                            final PackageSetting sysPs = mSettings
5046                                    .getDisabledSystemPkgLPr(pkg.packageName);
5047                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5048                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5049                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5050                                        allowed = true;
5051                                        allowed = true;
5052                                        break;
5053                                    }
5054                                }
5055                            }
5056                        } else {
5057                            allowed = true;
5058                        }
5059                        if (allowed) {
5060                            if (!mSharedLibraries.containsKey(name)) {
5061                                mSharedLibraries.put(name, new SharedLibraryEntry(null,
5062                                        pkg.packageName));
5063                            } else if (!name.equals(pkg.packageName)) {
5064                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5065                                        + name + " already exists; skipping");
5066                            }
5067                        } else {
5068                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5069                                    + name + " that is not declared on system image; skipping");
5070                        }
5071                    }
5072                    if ((scanMode&SCAN_BOOTING) == 0) {
5073                        // If we are not booting, we need to update any applications
5074                        // that are clients of our shared library.  If we are booting,
5075                        // this will all be done once the scan is complete.
5076                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5077                    }
5078                }
5079            }
5080        }
5081
5082        // We also need to dexopt any apps that are dependent on this library.  Note that
5083        // if these fail, we should abort the install since installing the library will
5084        // result in some apps being broken.
5085        if (clientLibPkgs != null) {
5086            if ((scanMode&SCAN_NO_DEX) == 0) {
5087                for (int i=0; i<clientLibPkgs.size(); i++) {
5088                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5089                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5090                            == DEX_OPT_FAILED) {
5091                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5092                            removeDataDirsLI(pkg.packageName);
5093                        }
5094
5095                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5096                        return null;
5097                    }
5098                }
5099            }
5100        }
5101
5102        // Request the ActivityManager to kill the process(only for existing packages)
5103        // so that we do not end up in a confused state while the user is still using the older
5104        // version of the application while the new one gets installed.
5105        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5106            // If the package lives in an asec, tell everyone that the container is going
5107            // away so they can clean up any references to its resources (which would prevent
5108            // vold from being able to unmount the asec)
5109            if (isForwardLocked(pkg) || isExternal(pkg)) {
5110                if (DEBUG_INSTALL) {
5111                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5112                }
5113                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5114                final ArrayList<String> pkgList = new ArrayList<String>(1);
5115                pkgList.add(pkg.applicationInfo.packageName);
5116                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5117            }
5118
5119            // Post the request that it be killed now that the going-away broadcast is en route
5120            killApplication(pkg.applicationInfo.packageName,
5121                        pkg.applicationInfo.uid, "update pkg");
5122        }
5123
5124        // Also need to kill any apps that are dependent on the library.
5125        if (clientLibPkgs != null) {
5126            for (int i=0; i<clientLibPkgs.size(); i++) {
5127                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5128                killApplication(clientPkg.applicationInfo.packageName,
5129                        clientPkg.applicationInfo.uid, "update lib");
5130            }
5131        }
5132
5133        // writer
5134        synchronized (mPackages) {
5135            // We don't expect installation to fail beyond this point,
5136            if ((scanMode&SCAN_MONITOR) != 0) {
5137                mAppDirs.put(pkg.mPath, pkg);
5138            }
5139            // Add the new setting to mSettings
5140            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5141            // Add the new setting to mPackages
5142            mPackages.put(pkg.applicationInfo.packageName, pkg);
5143            // Make sure we don't accidentally delete its data.
5144            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5145            while (iter.hasNext()) {
5146                PackageCleanItem item = iter.next();
5147                if (pkgName.equals(item.packageName)) {
5148                    iter.remove();
5149                }
5150            }
5151
5152            // Take care of first install / last update times.
5153            if (currentTime != 0) {
5154                if (pkgSetting.firstInstallTime == 0) {
5155                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5156                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5157                    pkgSetting.lastUpdateTime = currentTime;
5158                }
5159            } else if (pkgSetting.firstInstallTime == 0) {
5160                // We need *something*.  Take time time stamp of the file.
5161                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5162            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5163                if (scanFileTime != pkgSetting.timeStamp) {
5164                    // A package on the system image has changed; consider this
5165                    // to be an update.
5166                    pkgSetting.lastUpdateTime = scanFileTime;
5167                }
5168            }
5169
5170            // Add the package's KeySets to the global KeySetManager
5171            KeySetManager ksm = mSettings.mKeySetManager;
5172            try {
5173                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5174                if (pkg.mKeySetMapping != null) {
5175                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5176                        if (entry.getValue() != null) {
5177                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5178                                entry.getValue(), entry.getKey());
5179                        }
5180                    }
5181                }
5182            } catch (NullPointerException e) {
5183                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5184            } catch (IllegalArgumentException e) {
5185                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5186            }
5187
5188            int N = pkg.providers.size();
5189            StringBuilder r = null;
5190            int i;
5191            for (i=0; i<N; i++) {
5192                PackageParser.Provider p = pkg.providers.get(i);
5193                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5194                        p.info.processName, pkg.applicationInfo.uid);
5195                mProviders.addProvider(p);
5196                p.syncable = p.info.isSyncable;
5197                if (p.info.authority != null) {
5198                    String names[] = p.info.authority.split(";");
5199                    p.info.authority = null;
5200                    for (int j = 0; j < names.length; j++) {
5201                        if (j == 1 && p.syncable) {
5202                            // We only want the first authority for a provider to possibly be
5203                            // syncable, so if we already added this provider using a different
5204                            // authority clear the syncable flag. We copy the provider before
5205                            // changing it because the mProviders object contains a reference
5206                            // to a provider that we don't want to change.
5207                            // Only do this for the second authority since the resulting provider
5208                            // object can be the same for all future authorities for this provider.
5209                            p = new PackageParser.Provider(p);
5210                            p.syncable = false;
5211                        }
5212                        if (!mProvidersByAuthority.containsKey(names[j])) {
5213                            mProvidersByAuthority.put(names[j], p);
5214                            if (p.info.authority == null) {
5215                                p.info.authority = names[j];
5216                            } else {
5217                                p.info.authority = p.info.authority + ";" + names[j];
5218                            }
5219                            if (DEBUG_PACKAGE_SCANNING) {
5220                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5221                                    Log.d(TAG, "Registered content provider: " + names[j]
5222                                            + ", className = " + p.info.name + ", isSyncable = "
5223                                            + p.info.isSyncable);
5224                            }
5225                        } else {
5226                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5227                            Slog.w(TAG, "Skipping provider name " + names[j] +
5228                                    " (in package " + pkg.applicationInfo.packageName +
5229                                    "): name already used by "
5230                                    + ((other != null && other.getComponentName() != null)
5231                                            ? other.getComponentName().getPackageName() : "?"));
5232                        }
5233                    }
5234                }
5235                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5236                    if (r == null) {
5237                        r = new StringBuilder(256);
5238                    } else {
5239                        r.append(' ');
5240                    }
5241                    r.append(p.info.name);
5242                }
5243            }
5244            if (r != null) {
5245                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5246            }
5247
5248            N = pkg.services.size();
5249            r = null;
5250            for (i=0; i<N; i++) {
5251                PackageParser.Service s = pkg.services.get(i);
5252                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5253                        s.info.processName, pkg.applicationInfo.uid);
5254                mServices.addService(s);
5255                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5256                    if (r == null) {
5257                        r = new StringBuilder(256);
5258                    } else {
5259                        r.append(' ');
5260                    }
5261                    r.append(s.info.name);
5262                }
5263            }
5264            if (r != null) {
5265                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5266            }
5267
5268            N = pkg.receivers.size();
5269            r = null;
5270            for (i=0; i<N; i++) {
5271                PackageParser.Activity a = pkg.receivers.get(i);
5272                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5273                        a.info.processName, pkg.applicationInfo.uid);
5274                mReceivers.addActivity(a, "receiver");
5275                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5276                    if (r == null) {
5277                        r = new StringBuilder(256);
5278                    } else {
5279                        r.append(' ');
5280                    }
5281                    r.append(a.info.name);
5282                }
5283            }
5284            if (r != null) {
5285                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5286            }
5287
5288            N = pkg.activities.size();
5289            r = null;
5290            for (i=0; i<N; i++) {
5291                PackageParser.Activity a = pkg.activities.get(i);
5292                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5293                        a.info.processName, pkg.applicationInfo.uid);
5294                mActivities.addActivity(a, "activity");
5295                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5296                    if (r == null) {
5297                        r = new StringBuilder(256);
5298                    } else {
5299                        r.append(' ');
5300                    }
5301                    r.append(a.info.name);
5302                }
5303            }
5304            if (r != null) {
5305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5306            }
5307
5308            N = pkg.permissionGroups.size();
5309            r = null;
5310            for (i=0; i<N; i++) {
5311                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5312                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5313                if (cur == null) {
5314                    mPermissionGroups.put(pg.info.name, pg);
5315                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5316                        if (r == null) {
5317                            r = new StringBuilder(256);
5318                        } else {
5319                            r.append(' ');
5320                        }
5321                        r.append(pg.info.name);
5322                    }
5323                } else {
5324                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5325                            + pg.info.packageName + " ignored: original from "
5326                            + cur.info.packageName);
5327                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5328                        if (r == null) {
5329                            r = new StringBuilder(256);
5330                        } else {
5331                            r.append(' ');
5332                        }
5333                        r.append("DUP:");
5334                        r.append(pg.info.name);
5335                    }
5336                }
5337            }
5338            if (r != null) {
5339                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5340            }
5341
5342            N = pkg.permissions.size();
5343            r = null;
5344            for (i=0; i<N; i++) {
5345                PackageParser.Permission p = pkg.permissions.get(i);
5346                HashMap<String, BasePermission> permissionMap =
5347                        p.tree ? mSettings.mPermissionTrees
5348                        : mSettings.mPermissions;
5349                p.group = mPermissionGroups.get(p.info.group);
5350                if (p.info.group == null || p.group != null) {
5351                    BasePermission bp = permissionMap.get(p.info.name);
5352                    if (bp == null) {
5353                        bp = new BasePermission(p.info.name, p.info.packageName,
5354                                BasePermission.TYPE_NORMAL);
5355                        permissionMap.put(p.info.name, bp);
5356                    }
5357                    if (bp.perm == null) {
5358                        if (bp.sourcePackage != null
5359                                && !bp.sourcePackage.equals(p.info.packageName)) {
5360                            // If this is a permission that was formerly defined by a non-system
5361                            // app, but is now defined by a system app (following an upgrade),
5362                            // discard the previous declaration and consider the system's to be
5363                            // canonical.
5364                            if (isSystemApp(p.owner)) {
5365                                String msg = "New decl " + p.owner + " of permission  "
5366                                        + p.info.name + " is system";
5367                                reportSettingsProblem(Log.WARN, msg);
5368                                bp.sourcePackage = null;
5369                            }
5370                        }
5371                        if (bp.sourcePackage == null
5372                                || bp.sourcePackage.equals(p.info.packageName)) {
5373                            BasePermission tree = findPermissionTreeLP(p.info.name);
5374                            if (tree == null
5375                                    || tree.sourcePackage.equals(p.info.packageName)) {
5376                                bp.packageSetting = pkgSetting;
5377                                bp.perm = p;
5378                                bp.uid = pkg.applicationInfo.uid;
5379                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5380                                    if (r == null) {
5381                                        r = new StringBuilder(256);
5382                                    } else {
5383                                        r.append(' ');
5384                                    }
5385                                    r.append(p.info.name);
5386                                }
5387                            } else {
5388                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5389                                        + p.info.packageName + " ignored: base tree "
5390                                        + tree.name + " is from package "
5391                                        + tree.sourcePackage);
5392                            }
5393                        } else {
5394                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5395                                    + p.info.packageName + " ignored: original from "
5396                                    + bp.sourcePackage);
5397                        }
5398                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5399                        if (r == null) {
5400                            r = new StringBuilder(256);
5401                        } else {
5402                            r.append(' ');
5403                        }
5404                        r.append("DUP:");
5405                        r.append(p.info.name);
5406                    }
5407                    if (bp.perm == p) {
5408                        bp.protectionLevel = p.info.protectionLevel;
5409                    }
5410                } else {
5411                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5412                            + p.info.packageName + " ignored: no group "
5413                            + p.group);
5414                }
5415            }
5416            if (r != null) {
5417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5418            }
5419
5420            N = pkg.instrumentation.size();
5421            r = null;
5422            for (i=0; i<N; i++) {
5423                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5424                a.info.packageName = pkg.applicationInfo.packageName;
5425                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5426                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5427                a.info.dataDir = pkg.applicationInfo.dataDir;
5428                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5429                mInstrumentation.put(a.getComponentName(), a);
5430                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5431                    if (r == null) {
5432                        r = new StringBuilder(256);
5433                    } else {
5434                        r.append(' ');
5435                    }
5436                    r.append(a.info.name);
5437                }
5438            }
5439            if (r != null) {
5440                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5441            }
5442
5443            if (pkg.protectedBroadcasts != null) {
5444                N = pkg.protectedBroadcasts.size();
5445                for (i=0; i<N; i++) {
5446                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5447                }
5448            }
5449
5450            pkgSetting.setTimeStamp(scanFileTime);
5451
5452            // Create idmap files for pairs of (packages, overlay packages).
5453            // Note: "android", ie framework-res.apk, is handled by native layers.
5454            if (pkg.mOverlayTarget != null) {
5455                // This is an overlay package.
5456                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5457                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5458                        mOverlays.put(pkg.mOverlayTarget,
5459                                new HashMap<String, PackageParser.Package>());
5460                    }
5461                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5462                    map.put(pkg.packageName, pkg);
5463                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5464                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5465                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5466                        return null;
5467                    }
5468                }
5469            } else if (mOverlays.containsKey(pkg.packageName) &&
5470                    !pkg.packageName.equals("android")) {
5471                // This is a regular package, with one or more known overlay packages.
5472                createIdmapsForPackageLI(pkg);
5473            }
5474        }
5475
5476        return pkg;
5477    }
5478
5479    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5480        synchronized (mPackages) {
5481            mResolverReplaced = true;
5482            // Set up information for custom user intent resolution activity.
5483            mResolveActivity.applicationInfo = pkg.applicationInfo;
5484            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5485            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5486            mResolveActivity.processName = null;
5487            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5488            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5489                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5490            mResolveActivity.theme = 0;
5491            mResolveActivity.exported = true;
5492            mResolveActivity.enabled = true;
5493            mResolveInfo.activityInfo = mResolveActivity;
5494            mResolveInfo.priority = 0;
5495            mResolveInfo.preferredOrder = 0;
5496            mResolveInfo.match = 0;
5497            mResolveComponentName = mCustomResolverComponentName;
5498            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5499                    mResolveComponentName);
5500        }
5501    }
5502
5503    private String calculateApkRoot(final String codePathString) {
5504        final File codePath = new File(codePathString);
5505        final File codeRoot;
5506        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5507            codeRoot = Environment.getRootDirectory();
5508        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5509            codeRoot = Environment.getOemDirectory();
5510        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5511            codeRoot = Environment.getVendorDirectory();
5512        } else {
5513            // Unrecognized code path; take its top real segment as the apk root:
5514            // e.g. /something/app/blah.apk => /something
5515            try {
5516                File f = codePath.getCanonicalFile();
5517                File parent = f.getParentFile();    // non-null because codePath is a file
5518                File tmp;
5519                while ((tmp = parent.getParentFile()) != null) {
5520                    f = parent;
5521                    parent = tmp;
5522                }
5523                codeRoot = f;
5524                Slog.w(TAG, "Unrecognized code path "
5525                        + codePath + " - using " + codeRoot);
5526            } catch (IOException e) {
5527                // Can't canonicalize the lib path -- shenanigans?
5528                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5529                return Environment.getRootDirectory().getPath();
5530            }
5531        }
5532        return codeRoot.getPath();
5533    }
5534
5535    // This is the initial scan-time determination of how to handle a given
5536    // package for purposes of native library location.
5537    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5538            PackageSetting pkgSetting) {
5539        // "bundled" here means system-installed with no overriding update
5540        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5541        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5542        final File libDir;
5543        if (bundledApk) {
5544            // If "/system/lib64/apkname" exists, assume that is the per-package
5545            // native library directory to use; otherwise use "/system/lib/apkname".
5546            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5547            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5548            File packLib64 = new File(lib64, apkName);
5549            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5550        } else {
5551            libDir = mAppLibInstallDir;
5552        }
5553        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5554        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5555        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5556    }
5557
5558    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5559            throws IOException {
5560        if (!nativeLibraryDir.isDirectory()) {
5561            nativeLibraryDir.delete();
5562
5563            if (!nativeLibraryDir.mkdir()) {
5564                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5565            }
5566
5567            try {
5568                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5569            } catch (ErrnoException e) {
5570                throw new IOException("Cannot chmod native library directory "
5571                        + nativeLibraryDir.getPath(), e);
5572            }
5573        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5574            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5575        }
5576
5577        /*
5578         * If this is an internal application or our nativeLibraryPath points to
5579         * the app-lib directory, unpack the libraries if necessary.
5580         */
5581        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5582        try {
5583            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5584            if (abi >= 0) {
5585                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5586                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5587                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5588                    return copyRet;
5589                }
5590            }
5591
5592            return abi;
5593        } finally {
5594            handle.close();
5595        }
5596    }
5597
5598    private void killApplication(String pkgName, int appId, String reason) {
5599        // Request the ActivityManager to kill the process(only for existing packages)
5600        // so that we do not end up in a confused state while the user is still using the older
5601        // version of the application while the new one gets installed.
5602        IActivityManager am = ActivityManagerNative.getDefault();
5603        if (am != null) {
5604            try {
5605                am.killApplicationWithAppId(pkgName, appId, reason);
5606            } catch (RemoteException e) {
5607            }
5608        }
5609    }
5610
5611    void removePackageLI(PackageSetting ps, boolean chatty) {
5612        if (DEBUG_INSTALL) {
5613            if (chatty)
5614                Log.d(TAG, "Removing package " + ps.name);
5615        }
5616
5617        // writer
5618        synchronized (mPackages) {
5619            mPackages.remove(ps.name);
5620            if (ps.codePathString != null) {
5621                mAppDirs.remove(ps.codePathString);
5622            }
5623
5624            final PackageParser.Package pkg = ps.pkg;
5625            if (pkg != null) {
5626                cleanPackageDataStructuresLILPw(pkg, chatty);
5627            }
5628        }
5629    }
5630
5631    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5632        if (DEBUG_INSTALL) {
5633            if (chatty)
5634                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5635        }
5636
5637        // writer
5638        synchronized (mPackages) {
5639            mPackages.remove(pkg.applicationInfo.packageName);
5640            if (pkg.mPath != null) {
5641                mAppDirs.remove(pkg.mPath);
5642            }
5643            cleanPackageDataStructuresLILPw(pkg, chatty);
5644        }
5645    }
5646
5647    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5648        int N = pkg.providers.size();
5649        StringBuilder r = null;
5650        int i;
5651        for (i=0; i<N; i++) {
5652            PackageParser.Provider p = pkg.providers.get(i);
5653            mProviders.removeProvider(p);
5654            if (p.info.authority == null) {
5655
5656                /* There was another ContentProvider with this authority when
5657                 * this app was installed so this authority is null,
5658                 * Ignore it as we don't have to unregister the provider.
5659                 */
5660                continue;
5661            }
5662            String names[] = p.info.authority.split(";");
5663            for (int j = 0; j < names.length; j++) {
5664                if (mProvidersByAuthority.get(names[j]) == p) {
5665                    mProvidersByAuthority.remove(names[j]);
5666                    if (DEBUG_REMOVE) {
5667                        if (chatty)
5668                            Log.d(TAG, "Unregistered content provider: " + names[j]
5669                                    + ", className = " + p.info.name + ", isSyncable = "
5670                                    + p.info.isSyncable);
5671                    }
5672                }
5673            }
5674            if (DEBUG_REMOVE && chatty) {
5675                if (r == null) {
5676                    r = new StringBuilder(256);
5677                } else {
5678                    r.append(' ');
5679                }
5680                r.append(p.info.name);
5681            }
5682        }
5683        if (r != null) {
5684            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5685        }
5686
5687        N = pkg.services.size();
5688        r = null;
5689        for (i=0; i<N; i++) {
5690            PackageParser.Service s = pkg.services.get(i);
5691            mServices.removeService(s);
5692            if (chatty) {
5693                if (r == null) {
5694                    r = new StringBuilder(256);
5695                } else {
5696                    r.append(' ');
5697                }
5698                r.append(s.info.name);
5699            }
5700        }
5701        if (r != null) {
5702            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5703        }
5704
5705        N = pkg.receivers.size();
5706        r = null;
5707        for (i=0; i<N; i++) {
5708            PackageParser.Activity a = pkg.receivers.get(i);
5709            mReceivers.removeActivity(a, "receiver");
5710            if (DEBUG_REMOVE && chatty) {
5711                if (r == null) {
5712                    r = new StringBuilder(256);
5713                } else {
5714                    r.append(' ');
5715                }
5716                r.append(a.info.name);
5717            }
5718        }
5719        if (r != null) {
5720            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5721        }
5722
5723        N = pkg.activities.size();
5724        r = null;
5725        for (i=0; i<N; i++) {
5726            PackageParser.Activity a = pkg.activities.get(i);
5727            mActivities.removeActivity(a, "activity");
5728            if (DEBUG_REMOVE && chatty) {
5729                if (r == null) {
5730                    r = new StringBuilder(256);
5731                } else {
5732                    r.append(' ');
5733                }
5734                r.append(a.info.name);
5735            }
5736        }
5737        if (r != null) {
5738            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5739        }
5740
5741        N = pkg.permissions.size();
5742        r = null;
5743        for (i=0; i<N; i++) {
5744            PackageParser.Permission p = pkg.permissions.get(i);
5745            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5746            if (bp == null) {
5747                bp = mSettings.mPermissionTrees.get(p.info.name);
5748            }
5749            if (bp != null && bp.perm == p) {
5750                bp.perm = null;
5751                if (DEBUG_REMOVE && chatty) {
5752                    if (r == null) {
5753                        r = new StringBuilder(256);
5754                    } else {
5755                        r.append(' ');
5756                    }
5757                    r.append(p.info.name);
5758                }
5759            }
5760        }
5761        if (r != null) {
5762            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5763        }
5764
5765        N = pkg.instrumentation.size();
5766        r = null;
5767        for (i=0; i<N; i++) {
5768            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5769            mInstrumentation.remove(a.getComponentName());
5770            if (DEBUG_REMOVE && chatty) {
5771                if (r == null) {
5772                    r = new StringBuilder(256);
5773                } else {
5774                    r.append(' ');
5775                }
5776                r.append(a.info.name);
5777            }
5778        }
5779        if (r != null) {
5780            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5781        }
5782
5783        r = null;
5784        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5785            // Only system apps can hold shared libraries.
5786            if (pkg.libraryNames != null) {
5787                for (i=0; i<pkg.libraryNames.size(); i++) {
5788                    String name = pkg.libraryNames.get(i);
5789                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5790                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5791                        mSharedLibraries.remove(name);
5792                        if (DEBUG_REMOVE && chatty) {
5793                            if (r == null) {
5794                                r = new StringBuilder(256);
5795                            } else {
5796                                r.append(' ');
5797                            }
5798                            r.append(name);
5799                        }
5800                    }
5801                }
5802            }
5803        }
5804        if (r != null) {
5805            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5806        }
5807    }
5808
5809    private static final boolean isPackageFilename(String name) {
5810        return name != null && name.endsWith(".apk");
5811    }
5812
5813    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5814        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5815            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5816                return true;
5817            }
5818        }
5819        return false;
5820    }
5821
5822    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5823    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5824    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5825
5826    private void updatePermissionsLPw(String changingPkg,
5827            PackageParser.Package pkgInfo, int flags) {
5828        // Make sure there are no dangling permission trees.
5829        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5830        while (it.hasNext()) {
5831            final BasePermission bp = it.next();
5832            if (bp.packageSetting == null) {
5833                // We may not yet have parsed the package, so just see if
5834                // we still know about its settings.
5835                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5836            }
5837            if (bp.packageSetting == null) {
5838                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5839                        + " from package " + bp.sourcePackage);
5840                it.remove();
5841            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5842                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5843                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5844                            + " from package " + bp.sourcePackage);
5845                    flags |= UPDATE_PERMISSIONS_ALL;
5846                    it.remove();
5847                }
5848            }
5849        }
5850
5851        // Make sure all dynamic permissions have been assigned to a package,
5852        // and make sure there are no dangling permissions.
5853        it = mSettings.mPermissions.values().iterator();
5854        while (it.hasNext()) {
5855            final BasePermission bp = it.next();
5856            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5857                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5858                        + bp.name + " pkg=" + bp.sourcePackage
5859                        + " info=" + bp.pendingInfo);
5860                if (bp.packageSetting == null && bp.pendingInfo != null) {
5861                    final BasePermission tree = findPermissionTreeLP(bp.name);
5862                    if (tree != null && tree.perm != null) {
5863                        bp.packageSetting = tree.packageSetting;
5864                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5865                                new PermissionInfo(bp.pendingInfo));
5866                        bp.perm.info.packageName = tree.perm.info.packageName;
5867                        bp.perm.info.name = bp.name;
5868                        bp.uid = tree.uid;
5869                    }
5870                }
5871            }
5872            if (bp.packageSetting == null) {
5873                // We may not yet have parsed the package, so just see if
5874                // we still know about its settings.
5875                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5876            }
5877            if (bp.packageSetting == null) {
5878                Slog.w(TAG, "Removing dangling permission: " + bp.name
5879                        + " from package " + bp.sourcePackage);
5880                it.remove();
5881            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5882                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5883                    Slog.i(TAG, "Removing old permission: " + bp.name
5884                            + " from package " + bp.sourcePackage);
5885                    flags |= UPDATE_PERMISSIONS_ALL;
5886                    it.remove();
5887                }
5888            }
5889        }
5890
5891        // Now update the permissions for all packages, in particular
5892        // replace the granted permissions of the system packages.
5893        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5894            for (PackageParser.Package pkg : mPackages.values()) {
5895                if (pkg != pkgInfo) {
5896                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5897                }
5898            }
5899        }
5900
5901        if (pkgInfo != null) {
5902            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5903        }
5904    }
5905
5906    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5907        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5908        if (ps == null) {
5909            return;
5910        }
5911        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5912        HashSet<String> origPermissions = gp.grantedPermissions;
5913        boolean changedPermission = false;
5914
5915        if (replace) {
5916            ps.permissionsFixed = false;
5917            if (gp == ps) {
5918                origPermissions = new HashSet<String>(gp.grantedPermissions);
5919                gp.grantedPermissions.clear();
5920                gp.gids = mGlobalGids;
5921            }
5922        }
5923
5924        if (gp.gids == null) {
5925            gp.gids = mGlobalGids;
5926        }
5927
5928        final int N = pkg.requestedPermissions.size();
5929        for (int i=0; i<N; i++) {
5930            final String name = pkg.requestedPermissions.get(i);
5931            final boolean required = pkg.requestedPermissionsRequired.get(i);
5932            final BasePermission bp = mSettings.mPermissions.get(name);
5933            if (DEBUG_INSTALL) {
5934                if (gp != ps) {
5935                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5936                }
5937            }
5938
5939            if (bp == null || bp.packageSetting == null) {
5940                Slog.w(TAG, "Unknown permission " + name
5941                        + " in package " + pkg.packageName);
5942                continue;
5943            }
5944
5945            final String perm = bp.name;
5946            boolean allowed;
5947            boolean allowedSig = false;
5948            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5949            if (level == PermissionInfo.PROTECTION_NORMAL
5950                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5951                // We grant a normal or dangerous permission if any of the following
5952                // are true:
5953                // 1) The permission is required
5954                // 2) The permission is optional, but was granted in the past
5955                // 3) The permission is optional, but was requested by an
5956                //    app in /system (not /data)
5957                //
5958                // Otherwise, reject the permission.
5959                allowed = (required || origPermissions.contains(perm)
5960                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5961            } else if (bp.packageSetting == null) {
5962                // This permission is invalid; skip it.
5963                allowed = false;
5964            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5965                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5966                if (allowed) {
5967                    allowedSig = true;
5968                }
5969            } else {
5970                allowed = false;
5971            }
5972            if (DEBUG_INSTALL) {
5973                if (gp != ps) {
5974                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5975                }
5976            }
5977            if (allowed) {
5978                if (!isSystemApp(ps) && ps.permissionsFixed) {
5979                    // If this is an existing, non-system package, then
5980                    // we can't add any new permissions to it.
5981                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5982                        // Except...  if this is a permission that was added
5983                        // to the platform (note: need to only do this when
5984                        // updating the platform).
5985                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5986                    }
5987                }
5988                if (allowed) {
5989                    if (!gp.grantedPermissions.contains(perm)) {
5990                        changedPermission = true;
5991                        gp.grantedPermissions.add(perm);
5992                        gp.gids = appendInts(gp.gids, bp.gids);
5993                    } else if (!ps.haveGids) {
5994                        gp.gids = appendInts(gp.gids, bp.gids);
5995                    }
5996                } else {
5997                    Slog.w(TAG, "Not granting permission " + perm
5998                            + " to package " + pkg.packageName
5999                            + " because it was previously installed without");
6000                }
6001            } else {
6002                if (gp.grantedPermissions.remove(perm)) {
6003                    changedPermission = true;
6004                    gp.gids = removeInts(gp.gids, bp.gids);
6005                    Slog.i(TAG, "Un-granting permission " + perm
6006                            + " from package " + pkg.packageName
6007                            + " (protectionLevel=" + bp.protectionLevel
6008                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6009                            + ")");
6010                } else {
6011                    Slog.w(TAG, "Not granting permission " + perm
6012                            + " to package " + pkg.packageName
6013                            + " (protectionLevel=" + bp.protectionLevel
6014                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6015                            + ")");
6016                }
6017            }
6018        }
6019
6020        if ((changedPermission || replace) && !ps.permissionsFixed &&
6021                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6022            // This is the first that we have heard about this package, so the
6023            // permissions we have now selected are fixed until explicitly
6024            // changed.
6025            ps.permissionsFixed = true;
6026        }
6027        ps.haveGids = true;
6028    }
6029
6030    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6031        boolean allowed = false;
6032        final int NP = PackageParser.NEW_PERMISSIONS.length;
6033        for (int ip=0; ip<NP; ip++) {
6034            final PackageParser.NewPermissionInfo npi
6035                    = PackageParser.NEW_PERMISSIONS[ip];
6036            if (npi.name.equals(perm)
6037                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6038                allowed = true;
6039                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6040                        + pkg.packageName);
6041                break;
6042            }
6043        }
6044        return allowed;
6045    }
6046
6047    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6048                                          BasePermission bp, HashSet<String> origPermissions) {
6049        boolean allowed;
6050        allowed = (compareSignatures(
6051                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6052                        == PackageManager.SIGNATURE_MATCH)
6053                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6054                        == PackageManager.SIGNATURE_MATCH);
6055        if (!allowed && (bp.protectionLevel
6056                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6057            if (isSystemApp(pkg)) {
6058                // For updated system applications, a system permission
6059                // is granted only if it had been defined by the original application.
6060                if (isUpdatedSystemApp(pkg)) {
6061                    final PackageSetting sysPs = mSettings
6062                            .getDisabledSystemPkgLPr(pkg.packageName);
6063                    final GrantedPermissions origGp = sysPs.sharedUser != null
6064                            ? sysPs.sharedUser : sysPs;
6065
6066                    if (origGp.grantedPermissions.contains(perm)) {
6067                        // If the original was granted this permission, we take
6068                        // that grant decision as read and propagate it to the
6069                        // update.
6070                        allowed = true;
6071                    } else {
6072                        // The system apk may have been updated with an older
6073                        // version of the one on the data partition, but which
6074                        // granted a new system permission that it didn't have
6075                        // before.  In this case we do want to allow the app to
6076                        // now get the new permission if the ancestral apk is
6077                        // privileged to get it.
6078                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6079                            for (int j=0;
6080                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6081                                if (perm.equals(
6082                                        sysPs.pkg.requestedPermissions.get(j))) {
6083                                    allowed = true;
6084                                    break;
6085                                }
6086                            }
6087                        }
6088                    }
6089                } else {
6090                    allowed = isPrivilegedApp(pkg);
6091                }
6092            }
6093        }
6094        if (!allowed && (bp.protectionLevel
6095                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6096            // For development permissions, a development permission
6097            // is granted only if it was already granted.
6098            allowed = origPermissions.contains(perm);
6099        }
6100        return allowed;
6101    }
6102
6103    final class ActivityIntentResolver
6104            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6105        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6106                boolean defaultOnly, int userId) {
6107            if (!sUserManager.exists(userId)) return null;
6108            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6109            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6110        }
6111
6112        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6113                int userId) {
6114            if (!sUserManager.exists(userId)) return null;
6115            mFlags = flags;
6116            return super.queryIntent(intent, resolvedType,
6117                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6118        }
6119
6120        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6121                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6122            if (!sUserManager.exists(userId)) return null;
6123            if (packageActivities == null) {
6124                return null;
6125            }
6126            mFlags = flags;
6127            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6128            final int N = packageActivities.size();
6129            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6130                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6131
6132            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6133            for (int i = 0; i < N; ++i) {
6134                intentFilters = packageActivities.get(i).intents;
6135                if (intentFilters != null && intentFilters.size() > 0) {
6136                    PackageParser.ActivityIntentInfo[] array =
6137                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6138                    intentFilters.toArray(array);
6139                    listCut.add(array);
6140                }
6141            }
6142            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6143        }
6144
6145        public final void addActivity(PackageParser.Activity a, String type) {
6146            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6147            mActivities.put(a.getComponentName(), a);
6148            if (DEBUG_SHOW_INFO)
6149                Log.v(
6150                TAG, "  " + type + " " +
6151                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6152            if (DEBUG_SHOW_INFO)
6153                Log.v(TAG, "    Class=" + a.info.name);
6154            final int NI = a.intents.size();
6155            for (int j=0; j<NI; j++) {
6156                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6157                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6158                    intent.setPriority(0);
6159                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6160                            + a.className + " with priority > 0, forcing to 0");
6161                }
6162                if (DEBUG_SHOW_INFO) {
6163                    Log.v(TAG, "    IntentFilter:");
6164                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6165                }
6166                if (!intent.debugCheck()) {
6167                    Log.w(TAG, "==> For Activity " + a.info.name);
6168                }
6169                addFilter(intent);
6170            }
6171        }
6172
6173        public final void removeActivity(PackageParser.Activity a, String type) {
6174            mActivities.remove(a.getComponentName());
6175            if (DEBUG_SHOW_INFO) {
6176                Log.v(TAG, "  " + type + " "
6177                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6178                                : a.info.name) + ":");
6179                Log.v(TAG, "    Class=" + a.info.name);
6180            }
6181            final int NI = a.intents.size();
6182            for (int j=0; j<NI; j++) {
6183                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6184                if (DEBUG_SHOW_INFO) {
6185                    Log.v(TAG, "    IntentFilter:");
6186                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6187                }
6188                removeFilter(intent);
6189            }
6190        }
6191
6192        @Override
6193        protected boolean allowFilterResult(
6194                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6195            ActivityInfo filterAi = filter.activity.info;
6196            for (int i=dest.size()-1; i>=0; i--) {
6197                ActivityInfo destAi = dest.get(i).activityInfo;
6198                if (destAi.name == filterAi.name
6199                        && destAi.packageName == filterAi.packageName) {
6200                    return false;
6201                }
6202            }
6203            return true;
6204        }
6205
6206        @Override
6207        protected ActivityIntentInfo[] newArray(int size) {
6208            return new ActivityIntentInfo[size];
6209        }
6210
6211        @Override
6212        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6213            if (!sUserManager.exists(userId)) return true;
6214            PackageParser.Package p = filter.activity.owner;
6215            if (p != null) {
6216                PackageSetting ps = (PackageSetting)p.mExtras;
6217                if (ps != null) {
6218                    // System apps are never considered stopped for purposes of
6219                    // filtering, because there may be no way for the user to
6220                    // actually re-launch them.
6221                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6222                            && ps.getStopped(userId);
6223                }
6224            }
6225            return false;
6226        }
6227
6228        @Override
6229        protected boolean isPackageForFilter(String packageName,
6230                PackageParser.ActivityIntentInfo info) {
6231            return packageName.equals(info.activity.owner.packageName);
6232        }
6233
6234        @Override
6235        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6236                int match, int userId) {
6237            if (!sUserManager.exists(userId)) return null;
6238            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6239                return null;
6240            }
6241            final PackageParser.Activity activity = info.activity;
6242            if (mSafeMode && (activity.info.applicationInfo.flags
6243                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6244                return null;
6245            }
6246            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6247            if (ps == null) {
6248                return null;
6249            }
6250            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6251                    ps.readUserState(userId), userId);
6252            if (ai == null) {
6253                return null;
6254            }
6255            final ResolveInfo res = new ResolveInfo();
6256            res.activityInfo = ai;
6257            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6258                res.filter = info;
6259            }
6260            res.priority = info.getPriority();
6261            res.preferredOrder = activity.owner.mPreferredOrder;
6262            //System.out.println("Result: " + res.activityInfo.className +
6263            //                   " = " + res.priority);
6264            res.match = match;
6265            res.isDefault = info.hasDefault;
6266            res.labelRes = info.labelRes;
6267            res.nonLocalizedLabel = info.nonLocalizedLabel;
6268            res.icon = info.icon;
6269            res.system = isSystemApp(res.activityInfo.applicationInfo);
6270            return res;
6271        }
6272
6273        @Override
6274        protected void sortResults(List<ResolveInfo> results) {
6275            Collections.sort(results, mResolvePrioritySorter);
6276        }
6277
6278        @Override
6279        protected void dumpFilter(PrintWriter out, String prefix,
6280                PackageParser.ActivityIntentInfo filter) {
6281            out.print(prefix); out.print(
6282                    Integer.toHexString(System.identityHashCode(filter.activity)));
6283                    out.print(' ');
6284                    filter.activity.printComponentShortName(out);
6285                    out.print(" filter ");
6286                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6287        }
6288
6289//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6290//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6291//            final List<ResolveInfo> retList = Lists.newArrayList();
6292//            while (i.hasNext()) {
6293//                final ResolveInfo resolveInfo = i.next();
6294//                if (isEnabledLP(resolveInfo.activityInfo)) {
6295//                    retList.add(resolveInfo);
6296//                }
6297//            }
6298//            return retList;
6299//        }
6300
6301        // Keys are String (activity class name), values are Activity.
6302        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6303                = new HashMap<ComponentName, PackageParser.Activity>();
6304        private int mFlags;
6305    }
6306
6307    private final class ServiceIntentResolver
6308            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6309        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6310                boolean defaultOnly, int userId) {
6311            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6312            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6313        }
6314
6315        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6316                int userId) {
6317            if (!sUserManager.exists(userId)) return null;
6318            mFlags = flags;
6319            return super.queryIntent(intent, resolvedType,
6320                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6321        }
6322
6323        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6324                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6325            if (!sUserManager.exists(userId)) return null;
6326            if (packageServices == null) {
6327                return null;
6328            }
6329            mFlags = flags;
6330            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6331            final int N = packageServices.size();
6332            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6333                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6334
6335            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6336            for (int i = 0; i < N; ++i) {
6337                intentFilters = packageServices.get(i).intents;
6338                if (intentFilters != null && intentFilters.size() > 0) {
6339                    PackageParser.ServiceIntentInfo[] array =
6340                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6341                    intentFilters.toArray(array);
6342                    listCut.add(array);
6343                }
6344            }
6345            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6346        }
6347
6348        public final void addService(PackageParser.Service s) {
6349            mServices.put(s.getComponentName(), s);
6350            if (DEBUG_SHOW_INFO) {
6351                Log.v(TAG, "  "
6352                        + (s.info.nonLocalizedLabel != null
6353                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6354                Log.v(TAG, "    Class=" + s.info.name);
6355            }
6356            final int NI = s.intents.size();
6357            int j;
6358            for (j=0; j<NI; j++) {
6359                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6360                if (DEBUG_SHOW_INFO) {
6361                    Log.v(TAG, "    IntentFilter:");
6362                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6363                }
6364                if (!intent.debugCheck()) {
6365                    Log.w(TAG, "==> For Service " + s.info.name);
6366                }
6367                addFilter(intent);
6368            }
6369        }
6370
6371        public final void removeService(PackageParser.Service s) {
6372            mServices.remove(s.getComponentName());
6373            if (DEBUG_SHOW_INFO) {
6374                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6375                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6376                Log.v(TAG, "    Class=" + s.info.name);
6377            }
6378            final int NI = s.intents.size();
6379            int j;
6380            for (j=0; j<NI; j++) {
6381                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6382                if (DEBUG_SHOW_INFO) {
6383                    Log.v(TAG, "    IntentFilter:");
6384                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6385                }
6386                removeFilter(intent);
6387            }
6388        }
6389
6390        @Override
6391        protected boolean allowFilterResult(
6392                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6393            ServiceInfo filterSi = filter.service.info;
6394            for (int i=dest.size()-1; i>=0; i--) {
6395                ServiceInfo destAi = dest.get(i).serviceInfo;
6396                if (destAi.name == filterSi.name
6397                        && destAi.packageName == filterSi.packageName) {
6398                    return false;
6399                }
6400            }
6401            return true;
6402        }
6403
6404        @Override
6405        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6406            return new PackageParser.ServiceIntentInfo[size];
6407        }
6408
6409        @Override
6410        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6411            if (!sUserManager.exists(userId)) return true;
6412            PackageParser.Package p = filter.service.owner;
6413            if (p != null) {
6414                PackageSetting ps = (PackageSetting)p.mExtras;
6415                if (ps != null) {
6416                    // System apps are never considered stopped for purposes of
6417                    // filtering, because there may be no way for the user to
6418                    // actually re-launch them.
6419                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6420                            && ps.getStopped(userId);
6421                }
6422            }
6423            return false;
6424        }
6425
6426        @Override
6427        protected boolean isPackageForFilter(String packageName,
6428                PackageParser.ServiceIntentInfo info) {
6429            return packageName.equals(info.service.owner.packageName);
6430        }
6431
6432        @Override
6433        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6434                int match, int userId) {
6435            if (!sUserManager.exists(userId)) return null;
6436            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6437            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6438                return null;
6439            }
6440            final PackageParser.Service service = info.service;
6441            if (mSafeMode && (service.info.applicationInfo.flags
6442                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6443                return null;
6444            }
6445            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6446            if (ps == null) {
6447                return null;
6448            }
6449            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6450                    ps.readUserState(userId), userId);
6451            if (si == null) {
6452                return null;
6453            }
6454            final ResolveInfo res = new ResolveInfo();
6455            res.serviceInfo = si;
6456            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6457                res.filter = filter;
6458            }
6459            res.priority = info.getPriority();
6460            res.preferredOrder = service.owner.mPreferredOrder;
6461            //System.out.println("Result: " + res.activityInfo.className +
6462            //                   " = " + res.priority);
6463            res.match = match;
6464            res.isDefault = info.hasDefault;
6465            res.labelRes = info.labelRes;
6466            res.nonLocalizedLabel = info.nonLocalizedLabel;
6467            res.icon = info.icon;
6468            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6469            return res;
6470        }
6471
6472        @Override
6473        protected void sortResults(List<ResolveInfo> results) {
6474            Collections.sort(results, mResolvePrioritySorter);
6475        }
6476
6477        @Override
6478        protected void dumpFilter(PrintWriter out, String prefix,
6479                PackageParser.ServiceIntentInfo filter) {
6480            out.print(prefix); out.print(
6481                    Integer.toHexString(System.identityHashCode(filter.service)));
6482                    out.print(' ');
6483                    filter.service.printComponentShortName(out);
6484                    out.print(" filter ");
6485                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6486        }
6487
6488//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6489//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6490//            final List<ResolveInfo> retList = Lists.newArrayList();
6491//            while (i.hasNext()) {
6492//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6493//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6494//                    retList.add(resolveInfo);
6495//                }
6496//            }
6497//            return retList;
6498//        }
6499
6500        // Keys are String (activity class name), values are Activity.
6501        private final HashMap<ComponentName, PackageParser.Service> mServices
6502                = new HashMap<ComponentName, PackageParser.Service>();
6503        private int mFlags;
6504    };
6505
6506    private final class ProviderIntentResolver
6507            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6508        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6509                boolean defaultOnly, int userId) {
6510            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6511            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6512        }
6513
6514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6515                int userId) {
6516            if (!sUserManager.exists(userId))
6517                return null;
6518            mFlags = flags;
6519            return super.queryIntent(intent, resolvedType,
6520                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6521        }
6522
6523        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6524                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6525            if (!sUserManager.exists(userId))
6526                return null;
6527            if (packageProviders == null) {
6528                return null;
6529            }
6530            mFlags = flags;
6531            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6532            final int N = packageProviders.size();
6533            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6534                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6535
6536            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6537            for (int i = 0; i < N; ++i) {
6538                intentFilters = packageProviders.get(i).intents;
6539                if (intentFilters != null && intentFilters.size() > 0) {
6540                    PackageParser.ProviderIntentInfo[] array =
6541                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6542                    intentFilters.toArray(array);
6543                    listCut.add(array);
6544                }
6545            }
6546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6547        }
6548
6549        public final void addProvider(PackageParser.Provider p) {
6550            if (mProviders.containsKey(p.getComponentName())) {
6551                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6552                return;
6553            }
6554
6555            mProviders.put(p.getComponentName(), p);
6556            if (DEBUG_SHOW_INFO) {
6557                Log.v(TAG, "  "
6558                        + (p.info.nonLocalizedLabel != null
6559                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6560                Log.v(TAG, "    Class=" + p.info.name);
6561            }
6562            final int NI = p.intents.size();
6563            int j;
6564            for (j = 0; j < NI; j++) {
6565                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6566                if (DEBUG_SHOW_INFO) {
6567                    Log.v(TAG, "    IntentFilter:");
6568                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6569                }
6570                if (!intent.debugCheck()) {
6571                    Log.w(TAG, "==> For Provider " + p.info.name);
6572                }
6573                addFilter(intent);
6574            }
6575        }
6576
6577        public final void removeProvider(PackageParser.Provider p) {
6578            mProviders.remove(p.getComponentName());
6579            if (DEBUG_SHOW_INFO) {
6580                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6581                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6582                Log.v(TAG, "    Class=" + p.info.name);
6583            }
6584            final int NI = p.intents.size();
6585            int j;
6586            for (j = 0; j < NI; j++) {
6587                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6588                if (DEBUG_SHOW_INFO) {
6589                    Log.v(TAG, "    IntentFilter:");
6590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6591                }
6592                removeFilter(intent);
6593            }
6594        }
6595
6596        @Override
6597        protected boolean allowFilterResult(
6598                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6599            ProviderInfo filterPi = filter.provider.info;
6600            for (int i = dest.size() - 1; i >= 0; i--) {
6601                ProviderInfo destPi = dest.get(i).providerInfo;
6602                if (destPi.name == filterPi.name
6603                        && destPi.packageName == filterPi.packageName) {
6604                    return false;
6605                }
6606            }
6607            return true;
6608        }
6609
6610        @Override
6611        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6612            return new PackageParser.ProviderIntentInfo[size];
6613        }
6614
6615        @Override
6616        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6617            if (!sUserManager.exists(userId))
6618                return true;
6619            PackageParser.Package p = filter.provider.owner;
6620            if (p != null) {
6621                PackageSetting ps = (PackageSetting) p.mExtras;
6622                if (ps != null) {
6623                    // System apps are never considered stopped for purposes of
6624                    // filtering, because there may be no way for the user to
6625                    // actually re-launch them.
6626                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6627                            && ps.getStopped(userId);
6628                }
6629            }
6630            return false;
6631        }
6632
6633        @Override
6634        protected boolean isPackageForFilter(String packageName,
6635                PackageParser.ProviderIntentInfo info) {
6636            return packageName.equals(info.provider.owner.packageName);
6637        }
6638
6639        @Override
6640        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6641                int match, int userId) {
6642            if (!sUserManager.exists(userId))
6643                return null;
6644            final PackageParser.ProviderIntentInfo info = filter;
6645            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6646                return null;
6647            }
6648            final PackageParser.Provider provider = info.provider;
6649            if (mSafeMode && (provider.info.applicationInfo.flags
6650                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6651                return null;
6652            }
6653            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6654            if (ps == null) {
6655                return null;
6656            }
6657            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6658                    ps.readUserState(userId), userId);
6659            if (pi == null) {
6660                return null;
6661            }
6662            final ResolveInfo res = new ResolveInfo();
6663            res.providerInfo = pi;
6664            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6665                res.filter = filter;
6666            }
6667            res.priority = info.getPriority();
6668            res.preferredOrder = provider.owner.mPreferredOrder;
6669            res.match = match;
6670            res.isDefault = info.hasDefault;
6671            res.labelRes = info.labelRes;
6672            res.nonLocalizedLabel = info.nonLocalizedLabel;
6673            res.icon = info.icon;
6674            res.system = isSystemApp(res.providerInfo.applicationInfo);
6675            return res;
6676        }
6677
6678        @Override
6679        protected void sortResults(List<ResolveInfo> results) {
6680            Collections.sort(results, mResolvePrioritySorter);
6681        }
6682
6683        @Override
6684        protected void dumpFilter(PrintWriter out, String prefix,
6685                PackageParser.ProviderIntentInfo filter) {
6686            out.print(prefix);
6687            out.print(
6688                    Integer.toHexString(System.identityHashCode(filter.provider)));
6689            out.print(' ');
6690            filter.provider.printComponentShortName(out);
6691            out.print(" filter ");
6692            out.println(Integer.toHexString(System.identityHashCode(filter)));
6693        }
6694
6695        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6696                = new HashMap<ComponentName, PackageParser.Provider>();
6697        private int mFlags;
6698    };
6699
6700    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6701            new Comparator<ResolveInfo>() {
6702        public int compare(ResolveInfo r1, ResolveInfo r2) {
6703            int v1 = r1.priority;
6704            int v2 = r2.priority;
6705            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6706            if (v1 != v2) {
6707                return (v1 > v2) ? -1 : 1;
6708            }
6709            v1 = r1.preferredOrder;
6710            v2 = r2.preferredOrder;
6711            if (v1 != v2) {
6712                return (v1 > v2) ? -1 : 1;
6713            }
6714            if (r1.isDefault != r2.isDefault) {
6715                return r1.isDefault ? -1 : 1;
6716            }
6717            v1 = r1.match;
6718            v2 = r2.match;
6719            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6720            if (v1 != v2) {
6721                return (v1 > v2) ? -1 : 1;
6722            }
6723            if (r1.system != r2.system) {
6724                return r1.system ? -1 : 1;
6725            }
6726            return 0;
6727        }
6728    };
6729
6730    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6731            new Comparator<ProviderInfo>() {
6732        public int compare(ProviderInfo p1, ProviderInfo p2) {
6733            final int v1 = p1.initOrder;
6734            final int v2 = p2.initOrder;
6735            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6736        }
6737    };
6738
6739    static final void sendPackageBroadcast(String action, String pkg,
6740            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6741            int[] userIds) {
6742        IActivityManager am = ActivityManagerNative.getDefault();
6743        if (am != null) {
6744            try {
6745                if (userIds == null) {
6746                    userIds = am.getRunningUserIds();
6747                }
6748                for (int id : userIds) {
6749                    final Intent intent = new Intent(action,
6750                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6751                    if (extras != null) {
6752                        intent.putExtras(extras);
6753                    }
6754                    if (targetPkg != null) {
6755                        intent.setPackage(targetPkg);
6756                    }
6757                    // Modify the UID when posting to other users
6758                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6759                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6760                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6761                        intent.putExtra(Intent.EXTRA_UID, uid);
6762                    }
6763                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6764                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6765                    if (DEBUG_BROADCASTS) {
6766                        RuntimeException here = new RuntimeException("here");
6767                        here.fillInStackTrace();
6768                        Slog.d(TAG, "Sending to user " + id + ": "
6769                                + intent.toShortString(false, true, false, false)
6770                                + " " + intent.getExtras(), here);
6771                    }
6772                    am.broadcastIntent(null, intent, null, finishedReceiver,
6773                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6774                            finishedReceiver != null, false, id);
6775                }
6776            } catch (RemoteException ex) {
6777            }
6778        }
6779    }
6780
6781    /**
6782     * Check if the external storage media is available. This is true if there
6783     * is a mounted external storage medium or if the external storage is
6784     * emulated.
6785     */
6786    private boolean isExternalMediaAvailable() {
6787        return mMediaMounted || Environment.isExternalStorageEmulated();
6788    }
6789
6790    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6791        // writer
6792        synchronized (mPackages) {
6793            if (!isExternalMediaAvailable()) {
6794                // If the external storage is no longer mounted at this point,
6795                // the caller may not have been able to delete all of this
6796                // packages files and can not delete any more.  Bail.
6797                return null;
6798            }
6799            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6800            if (lastPackage != null) {
6801                pkgs.remove(lastPackage);
6802            }
6803            if (pkgs.size() > 0) {
6804                return pkgs.get(0);
6805            }
6806        }
6807        return null;
6808    }
6809
6810    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6811        if (false) {
6812            RuntimeException here = new RuntimeException("here");
6813            here.fillInStackTrace();
6814            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6815                    + " andCode=" + andCode, here);
6816        }
6817        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6818                userId, andCode ? 1 : 0, packageName));
6819    }
6820
6821    void startCleaningPackages() {
6822        // reader
6823        synchronized (mPackages) {
6824            if (!isExternalMediaAvailable()) {
6825                return;
6826            }
6827            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6828                return;
6829            }
6830        }
6831        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6832        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6833        IActivityManager am = ActivityManagerNative.getDefault();
6834        if (am != null) {
6835            try {
6836                am.startService(null, intent, null, UserHandle.USER_OWNER);
6837            } catch (RemoteException e) {
6838            }
6839        }
6840    }
6841
6842    private final class AppDirObserver extends FileObserver {
6843        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6844            super(path, mask);
6845            mRootDir = path;
6846            mIsRom = isrom;
6847            mIsPrivileged = isPrivileged;
6848        }
6849
6850        public void onEvent(int event, String path) {
6851            String removedPackage = null;
6852            int removedAppId = -1;
6853            int[] removedUsers = null;
6854            String addedPackage = null;
6855            int addedAppId = -1;
6856            int[] addedUsers = null;
6857
6858            // TODO post a message to the handler to obtain serial ordering
6859            synchronized (mInstallLock) {
6860                String fullPathStr = null;
6861                File fullPath = null;
6862                if (path != null) {
6863                    fullPath = new File(mRootDir, path);
6864                    fullPathStr = fullPath.getPath();
6865                }
6866
6867                if (DEBUG_APP_DIR_OBSERVER)
6868                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6869
6870                if (!isPackageFilename(path)) {
6871                    if (DEBUG_APP_DIR_OBSERVER)
6872                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6873                    return;
6874                }
6875
6876                // Ignore packages that are being installed or
6877                // have just been installed.
6878                if (ignoreCodePath(fullPathStr)) {
6879                    return;
6880                }
6881                PackageParser.Package p = null;
6882                PackageSetting ps = null;
6883                // reader
6884                synchronized (mPackages) {
6885                    p = mAppDirs.get(fullPathStr);
6886                    if (p != null) {
6887                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6888                        if (ps != null) {
6889                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6890                        } else {
6891                            removedUsers = sUserManager.getUserIds();
6892                        }
6893                    }
6894                    addedUsers = sUserManager.getUserIds();
6895                }
6896                if ((event&REMOVE_EVENTS) != 0) {
6897                    if (ps != null) {
6898                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6899                        removePackageLI(ps, true);
6900                        removedPackage = ps.name;
6901                        removedAppId = ps.appId;
6902                    }
6903                }
6904
6905                if ((event&ADD_EVENTS) != 0) {
6906                    if (p == null) {
6907                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6908                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6909                        if (mIsRom) {
6910                            flags |= PackageParser.PARSE_IS_SYSTEM
6911                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6912                            if (mIsPrivileged) {
6913                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6914                            }
6915                        }
6916                        p = scanPackageLI(fullPath, flags,
6917                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6918                                System.currentTimeMillis(), UserHandle.ALL);
6919                        if (p != null) {
6920                            /*
6921                             * TODO this seems dangerous as the package may have
6922                             * changed since we last acquired the mPackages
6923                             * lock.
6924                             */
6925                            // writer
6926                            synchronized (mPackages) {
6927                                updatePermissionsLPw(p.packageName, p,
6928                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6929                            }
6930                            addedPackage = p.applicationInfo.packageName;
6931                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6932                        }
6933                    }
6934                }
6935
6936                // reader
6937                synchronized (mPackages) {
6938                    mSettings.writeLPr();
6939                }
6940            }
6941
6942            if (removedPackage != null) {
6943                Bundle extras = new Bundle(1);
6944                extras.putInt(Intent.EXTRA_UID, removedAppId);
6945                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6946                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6947                        extras, null, null, removedUsers);
6948            }
6949            if (addedPackage != null) {
6950                Bundle extras = new Bundle(1);
6951                extras.putInt(Intent.EXTRA_UID, addedAppId);
6952                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6953                        extras, null, null, addedUsers);
6954            }
6955        }
6956
6957        private final String mRootDir;
6958        private final boolean mIsRom;
6959        private final boolean mIsPrivileged;
6960    }
6961
6962    /*
6963     * The old-style observer methods all just trampoline to the newer signature with
6964     * expanded install observer API.  The older API continues to work but does not
6965     * supply the additional details of the Observer2 API.
6966     */
6967
6968    /* Called when a downloaded package installation has been confirmed by the user */
6969    public void installPackage(
6970            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6971        installPackageEtc(packageURI, observer, null, flags, null);
6972    }
6973
6974    /* Called when a downloaded package installation has been confirmed by the user */
6975    public void installPackage(
6976            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6977            final String installerPackageName) {
6978        installPackageWithVerificationEtc(packageURI, observer, null, flags,
6979                installerPackageName, null, null, null);
6980    }
6981
6982    @Override
6983    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6984            int flags, String installerPackageName, Uri verificationURI,
6985            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6986        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6987                VerificationParams.NO_UID, manifestDigest);
6988        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6989                installerPackageName, verificationParams, encryptionParams);
6990    }
6991
6992    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6993            IPackageInstallObserver observer, int flags, String installerPackageName,
6994            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6995        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6996                installerPackageName, verificationParams, encryptionParams);
6997    }
6998
6999    /*
7000     * And here are the "live" versions that take both observer arguments
7001     */
7002    public void installPackageEtc(
7003            final Uri packageURI, final IPackageInstallObserver observer,
7004            IPackageInstallObserver2 observer2, final int flags) {
7005        installPackageEtc(packageURI, observer, observer2, flags, null);
7006    }
7007
7008    public void installPackageEtc(
7009            final Uri packageURI, final IPackageInstallObserver observer,
7010            final IPackageInstallObserver2 observer2, final int flags,
7011            final String installerPackageName) {
7012        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7013                installerPackageName, null, null, null);
7014    }
7015
7016    @Override
7017    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7018            IPackageInstallObserver2 observer2,
7019            int flags, String installerPackageName, Uri verificationURI,
7020            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7021        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7022                VerificationParams.NO_UID, manifestDigest);
7023        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7024                installerPackageName, verificationParams, encryptionParams);
7025    }
7026
7027    /*
7028     * All of the installPackage...*() methods redirect to this one for the master implementation
7029     */
7030    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7031            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7032            int flags, String installerPackageName,
7033            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7034        if (observer == null && observer2 == null) {
7035            throw new IllegalArgumentException("No install observer supplied");
7036        }
7037        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7038                null);
7039
7040        final int uid = Binder.getCallingUid();
7041        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7042            try {
7043                if (observer != null) {
7044                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7045                }
7046                if (observer2 != null) {
7047                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7048                }
7049            } catch (RemoteException re) {
7050            }
7051            return;
7052        }
7053
7054        UserHandle user;
7055        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7056            user = UserHandle.ALL;
7057        } else {
7058            user = new UserHandle(UserHandle.getUserId(uid));
7059        }
7060
7061        final int filteredFlags;
7062
7063        if (uid == Process.SHELL_UID || uid == 0) {
7064            if (DEBUG_INSTALL) {
7065                Slog.v(TAG, "Install from ADB");
7066            }
7067            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7068        } else {
7069            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7070        }
7071
7072        verificationParams.setInstallerUid(uid);
7073
7074        final Message msg = mHandler.obtainMessage(INIT_COPY);
7075        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7076                installerPackageName, verificationParams, encryptionParams, user);
7077        mHandler.sendMessage(msg);
7078    }
7079
7080    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7081        Bundle extras = new Bundle(1);
7082        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7083
7084        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7085                packageName, extras, null, null, new int[] {userId});
7086        try {
7087            IActivityManager am = ActivityManagerNative.getDefault();
7088            final boolean isSystem =
7089                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7090            if (isSystem && am.isUserRunning(userId, false)) {
7091                // The just-installed/enabled app is bundled on the system, so presumed
7092                // to be able to run automatically without needing an explicit launch.
7093                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7094                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7095                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7096                        .setPackage(packageName);
7097                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7098                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7099            }
7100        } catch (RemoteException e) {
7101            // shouldn't happen
7102            Slog.w(TAG, "Unable to bootstrap installed package", e);
7103        }
7104    }
7105
7106    @Override
7107    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7108            int userId) {
7109        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7110        PackageSetting pkgSetting;
7111        final int uid = Binder.getCallingUid();
7112        if (UserHandle.getUserId(uid) != userId) {
7113            mContext.enforceCallingOrSelfPermission(
7114                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7115                    "setApplicationBlockedSetting for user " + userId);
7116        }
7117
7118        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7119            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7120            return false;
7121        }
7122
7123        long callingId = Binder.clearCallingIdentity();
7124        try {
7125            boolean sendAdded = false;
7126            boolean sendRemoved = false;
7127            // writer
7128            synchronized (mPackages) {
7129                pkgSetting = mSettings.mPackages.get(packageName);
7130                if (pkgSetting == null) {
7131                    return false;
7132                }
7133                if (pkgSetting.getBlocked(userId) != blocked) {
7134                    pkgSetting.setBlocked(blocked, userId);
7135                    mSettings.writePackageRestrictionsLPr(userId);
7136                    if (blocked) {
7137                        sendRemoved = true;
7138                    } else {
7139                        sendAdded = true;
7140                    }
7141                }
7142            }
7143            if (sendAdded) {
7144                sendPackageAddedForUser(packageName, pkgSetting, userId);
7145                return true;
7146            }
7147            if (sendRemoved) {
7148                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7149                        "blocking pkg");
7150                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7151            }
7152        } finally {
7153            Binder.restoreCallingIdentity(callingId);
7154        }
7155        return false;
7156    }
7157
7158    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7159            int userId) {
7160        final PackageRemovedInfo info = new PackageRemovedInfo();
7161        info.removedPackage = packageName;
7162        info.removedUsers = new int[] {userId};
7163        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7164        info.sendBroadcast(false, false, false);
7165    }
7166
7167    /**
7168     * Returns true if application is not found or there was an error. Otherwise it returns
7169     * the blocked state of the package for the given user.
7170     */
7171    @Override
7172    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7173        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7174        PackageSetting pkgSetting;
7175        final int uid = Binder.getCallingUid();
7176        if (UserHandle.getUserId(uid) != userId) {
7177            mContext.enforceCallingPermission(
7178                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7179                    "getApplicationBlocked for user " + userId);
7180        }
7181        long callingId = Binder.clearCallingIdentity();
7182        try {
7183            // writer
7184            synchronized (mPackages) {
7185                pkgSetting = mSettings.mPackages.get(packageName);
7186                if (pkgSetting == null) {
7187                    return true;
7188                }
7189                return pkgSetting.getBlocked(userId);
7190            }
7191        } finally {
7192            Binder.restoreCallingIdentity(callingId);
7193        }
7194    }
7195
7196    /**
7197     * @hide
7198     */
7199    @Override
7200    public int installExistingPackageAsUser(String packageName, int userId) {
7201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7202                null);
7203        PackageSetting pkgSetting;
7204        final int uid = Binder.getCallingUid();
7205        if (UserHandle.getUserId(uid) != userId) {
7206            mContext.enforceCallingPermission(
7207                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7208                    "installExistingPackage for user " + userId);
7209        }
7210        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7211            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7212        }
7213
7214        long callingId = Binder.clearCallingIdentity();
7215        try {
7216            boolean sendAdded = false;
7217            Bundle extras = new Bundle(1);
7218
7219            // writer
7220            synchronized (mPackages) {
7221                pkgSetting = mSettings.mPackages.get(packageName);
7222                if (pkgSetting == null) {
7223                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7224                }
7225                if (!pkgSetting.getInstalled(userId)) {
7226                    pkgSetting.setInstalled(true, userId);
7227                    pkgSetting.setBlocked(false, userId);
7228                    mSettings.writePackageRestrictionsLPr(userId);
7229                    sendAdded = true;
7230                }
7231            }
7232
7233            if (sendAdded) {
7234                sendPackageAddedForUser(packageName, pkgSetting, userId);
7235            }
7236        } finally {
7237            Binder.restoreCallingIdentity(callingId);
7238        }
7239
7240        return PackageManager.INSTALL_SUCCEEDED;
7241    }
7242
7243    private boolean isUserRestricted(int userId, String restrictionKey) {
7244        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7245        if (restrictions.getBoolean(restrictionKey, false)) {
7246            Log.w(TAG, "User is restricted: " + restrictionKey);
7247            return true;
7248        }
7249        return false;
7250    }
7251
7252    @Override
7253    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7254        mContext.enforceCallingOrSelfPermission(
7255                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7256                "Only package verification agents can verify applications");
7257
7258        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7259        final PackageVerificationResponse response = new PackageVerificationResponse(
7260                verificationCode, Binder.getCallingUid());
7261        msg.arg1 = id;
7262        msg.obj = response;
7263        mHandler.sendMessage(msg);
7264    }
7265
7266    @Override
7267    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7268            long millisecondsToDelay) {
7269        mContext.enforceCallingOrSelfPermission(
7270                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7271                "Only package verification agents can extend verification timeouts");
7272
7273        final PackageVerificationState state = mPendingVerification.get(id);
7274        final PackageVerificationResponse response = new PackageVerificationResponse(
7275                verificationCodeAtTimeout, Binder.getCallingUid());
7276
7277        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7278            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7279        }
7280        if (millisecondsToDelay < 0) {
7281            millisecondsToDelay = 0;
7282        }
7283        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7284                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7285            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7286        }
7287
7288        if ((state != null) && !state.timeoutExtended()) {
7289            state.extendTimeout();
7290
7291            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7292            msg.arg1 = id;
7293            msg.obj = response;
7294            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7295        }
7296    }
7297
7298    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7299            int verificationCode, UserHandle user) {
7300        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7301        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7302        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7303        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7304        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7305
7306        mContext.sendBroadcastAsUser(intent, user,
7307                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7308    }
7309
7310    private ComponentName matchComponentForVerifier(String packageName,
7311            List<ResolveInfo> receivers) {
7312        ActivityInfo targetReceiver = null;
7313
7314        final int NR = receivers.size();
7315        for (int i = 0; i < NR; i++) {
7316            final ResolveInfo info = receivers.get(i);
7317            if (info.activityInfo == null) {
7318                continue;
7319            }
7320
7321            if (packageName.equals(info.activityInfo.packageName)) {
7322                targetReceiver = info.activityInfo;
7323                break;
7324            }
7325        }
7326
7327        if (targetReceiver == null) {
7328            return null;
7329        }
7330
7331        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7332    }
7333
7334    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7335            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7336        if (pkgInfo.verifiers.length == 0) {
7337            return null;
7338        }
7339
7340        final int N = pkgInfo.verifiers.length;
7341        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7342        for (int i = 0; i < N; i++) {
7343            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7344
7345            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7346                    receivers);
7347            if (comp == null) {
7348                continue;
7349            }
7350
7351            final int verifierUid = getUidForVerifier(verifierInfo);
7352            if (verifierUid == -1) {
7353                continue;
7354            }
7355
7356            if (DEBUG_VERIFY) {
7357                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7358                        + " with the correct signature");
7359            }
7360            sufficientVerifiers.add(comp);
7361            verificationState.addSufficientVerifier(verifierUid);
7362        }
7363
7364        return sufficientVerifiers;
7365    }
7366
7367    private int getUidForVerifier(VerifierInfo verifierInfo) {
7368        synchronized (mPackages) {
7369            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7370            if (pkg == null) {
7371                return -1;
7372            } else if (pkg.mSignatures.length != 1) {
7373                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7374                        + " has more than one signature; ignoring");
7375                return -1;
7376            }
7377
7378            /*
7379             * If the public key of the package's signature does not match
7380             * our expected public key, then this is a different package and
7381             * we should skip.
7382             */
7383
7384            final byte[] expectedPublicKey;
7385            try {
7386                final Signature verifierSig = pkg.mSignatures[0];
7387                final PublicKey publicKey = verifierSig.getPublicKey();
7388                expectedPublicKey = publicKey.getEncoded();
7389            } catch (CertificateException e) {
7390                return -1;
7391            }
7392
7393            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7394
7395            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7396                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7397                        + " does not have the expected public key; ignoring");
7398                return -1;
7399            }
7400
7401            return pkg.applicationInfo.uid;
7402        }
7403    }
7404
7405    public void finishPackageInstall(int token) {
7406        enforceSystemOrRoot("Only the system is allowed to finish installs");
7407
7408        if (DEBUG_INSTALL) {
7409            Slog.v(TAG, "BM finishing package install for " + token);
7410        }
7411
7412        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7413        mHandler.sendMessage(msg);
7414    }
7415
7416    /**
7417     * Get the verification agent timeout.
7418     *
7419     * @return verification timeout in milliseconds
7420     */
7421    private long getVerificationTimeout() {
7422        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7423                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7424                DEFAULT_VERIFICATION_TIMEOUT);
7425    }
7426
7427    /**
7428     * Get the default verification agent response code.
7429     *
7430     * @return default verification response code
7431     */
7432    private int getDefaultVerificationResponse() {
7433        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7434                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7435                DEFAULT_VERIFICATION_RESPONSE);
7436    }
7437
7438    /**
7439     * Check whether or not package verification has been enabled.
7440     *
7441     * @return true if verification should be performed
7442     */
7443    private boolean isVerificationEnabled(int flags) {
7444        if (!DEFAULT_VERIFY_ENABLE) {
7445            return false;
7446        }
7447
7448        // Check if installing from ADB
7449        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7450            // Do not run verification in a test harness environment
7451            if (ActivityManager.isRunningInTestHarness()) {
7452                return false;
7453            }
7454            // Check if the developer does not want package verification for ADB installs
7455            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7456                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7457                return false;
7458            }
7459        }
7460
7461        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7462                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7463    }
7464
7465    /**
7466     * Get the "allow unknown sources" setting.
7467     *
7468     * @return the current "allow unknown sources" setting
7469     */
7470    private int getUnknownSourcesSettings() {
7471        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7472                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7473                -1);
7474    }
7475
7476    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7477        final int uid = Binder.getCallingUid();
7478        // writer
7479        synchronized (mPackages) {
7480            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7481            if (targetPackageSetting == null) {
7482                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7483            }
7484
7485            PackageSetting installerPackageSetting;
7486            if (installerPackageName != null) {
7487                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7488                if (installerPackageSetting == null) {
7489                    throw new IllegalArgumentException("Unknown installer package: "
7490                            + installerPackageName);
7491                }
7492            } else {
7493                installerPackageSetting = null;
7494            }
7495
7496            Signature[] callerSignature;
7497            Object obj = mSettings.getUserIdLPr(uid);
7498            if (obj != null) {
7499                if (obj instanceof SharedUserSetting) {
7500                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7501                } else if (obj instanceof PackageSetting) {
7502                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7503                } else {
7504                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7505                }
7506            } else {
7507                throw new SecurityException("Unknown calling uid " + uid);
7508            }
7509
7510            // Verify: can't set installerPackageName to a package that is
7511            // not signed with the same cert as the caller.
7512            if (installerPackageSetting != null) {
7513                if (compareSignatures(callerSignature,
7514                        installerPackageSetting.signatures.mSignatures)
7515                        != PackageManager.SIGNATURE_MATCH) {
7516                    throw new SecurityException(
7517                            "Caller does not have same cert as new installer package "
7518                            + installerPackageName);
7519                }
7520            }
7521
7522            // Verify: if target already has an installer package, it must
7523            // be signed with the same cert as the caller.
7524            if (targetPackageSetting.installerPackageName != null) {
7525                PackageSetting setting = mSettings.mPackages.get(
7526                        targetPackageSetting.installerPackageName);
7527                // If the currently set package isn't valid, then it's always
7528                // okay to change it.
7529                if (setting != null) {
7530                    if (compareSignatures(callerSignature,
7531                            setting.signatures.mSignatures)
7532                            != PackageManager.SIGNATURE_MATCH) {
7533                        throw new SecurityException(
7534                                "Caller does not have same cert as old installer package "
7535                                + targetPackageSetting.installerPackageName);
7536                    }
7537                }
7538            }
7539
7540            // Okay!
7541            targetPackageSetting.installerPackageName = installerPackageName;
7542            scheduleWriteSettingsLocked();
7543        }
7544    }
7545
7546    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7547        // Queue up an async operation since the package installation may take a little while.
7548        mHandler.post(new Runnable() {
7549            public void run() {
7550                mHandler.removeCallbacks(this);
7551                 // Result object to be returned
7552                PackageInstalledInfo res = new PackageInstalledInfo();
7553                res.returnCode = currentStatus;
7554                res.uid = -1;
7555                res.pkg = null;
7556                res.removedInfo = new PackageRemovedInfo();
7557                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7558                    args.doPreInstall(res.returnCode);
7559                    synchronized (mInstallLock) {
7560                        installPackageLI(args, true, res);
7561                    }
7562                    args.doPostInstall(res.returnCode, res.uid);
7563                }
7564
7565                // A restore should be performed at this point if (a) the install
7566                // succeeded, (b) the operation is not an update, and (c) the new
7567                // package has a backupAgent defined.
7568                final boolean update = res.removedInfo.removedPackage != null;
7569                boolean doRestore = (!update
7570                        && res.pkg != null
7571                        && res.pkg.applicationInfo.backupAgentName != null);
7572
7573                // Set up the post-install work request bookkeeping.  This will be used
7574                // and cleaned up by the post-install event handling regardless of whether
7575                // there's a restore pass performed.  Token values are >= 1.
7576                int token;
7577                if (mNextInstallToken < 0) mNextInstallToken = 1;
7578                token = mNextInstallToken++;
7579
7580                PostInstallData data = new PostInstallData(args, res);
7581                mRunningInstalls.put(token, data);
7582                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7583
7584                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7585                    // Pass responsibility to the Backup Manager.  It will perform a
7586                    // restore if appropriate, then pass responsibility back to the
7587                    // Package Manager to run the post-install observer callbacks
7588                    // and broadcasts.
7589                    IBackupManager bm = IBackupManager.Stub.asInterface(
7590                            ServiceManager.getService(Context.BACKUP_SERVICE));
7591                    if (bm != null) {
7592                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7593                                + " to BM for possible restore");
7594                        try {
7595                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7596                        } catch (RemoteException e) {
7597                            // can't happen; the backup manager is local
7598                        } catch (Exception e) {
7599                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7600                            doRestore = false;
7601                        }
7602                    } else {
7603                        Slog.e(TAG, "Backup Manager not found!");
7604                        doRestore = false;
7605                    }
7606                }
7607
7608                if (!doRestore) {
7609                    // No restore possible, or the Backup Manager was mysteriously not
7610                    // available -- just fire the post-install work request directly.
7611                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7612                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7613                    mHandler.sendMessage(msg);
7614                }
7615            }
7616        });
7617    }
7618
7619    private abstract class HandlerParams {
7620        private static final int MAX_RETRIES = 4;
7621
7622        /**
7623         * Number of times startCopy() has been attempted and had a non-fatal
7624         * error.
7625         */
7626        private int mRetries = 0;
7627
7628        /** User handle for the user requesting the information or installation. */
7629        private final UserHandle mUser;
7630
7631        HandlerParams(UserHandle user) {
7632            mUser = user;
7633        }
7634
7635        UserHandle getUser() {
7636            return mUser;
7637        }
7638
7639        final boolean startCopy() {
7640            boolean res;
7641            try {
7642                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7643
7644                if (++mRetries > MAX_RETRIES) {
7645                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7646                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7647                    handleServiceError();
7648                    return false;
7649                } else {
7650                    handleStartCopy();
7651                    res = true;
7652                }
7653            } catch (RemoteException e) {
7654                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7655                mHandler.sendEmptyMessage(MCS_RECONNECT);
7656                res = false;
7657            }
7658            handleReturnCode();
7659            return res;
7660        }
7661
7662        final void serviceError() {
7663            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7664            handleServiceError();
7665            handleReturnCode();
7666        }
7667
7668        abstract void handleStartCopy() throws RemoteException;
7669        abstract void handleServiceError();
7670        abstract void handleReturnCode();
7671    }
7672
7673    class MeasureParams extends HandlerParams {
7674        private final PackageStats mStats;
7675        private boolean mSuccess;
7676
7677        private final IPackageStatsObserver mObserver;
7678
7679        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7680            super(new UserHandle(stats.userHandle));
7681            mObserver = observer;
7682            mStats = stats;
7683        }
7684
7685        @Override
7686        public String toString() {
7687            return "MeasureParams{"
7688                + Integer.toHexString(System.identityHashCode(this))
7689                + " " + mStats.packageName + "}";
7690        }
7691
7692        @Override
7693        void handleStartCopy() throws RemoteException {
7694            synchronized (mInstallLock) {
7695                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7696            }
7697
7698            if (mSuccess) {
7699                final boolean mounted;
7700                if (Environment.isExternalStorageEmulated()) {
7701                    mounted = true;
7702                } else {
7703                    final String status = Environment.getExternalStorageState();
7704                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
7705                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7706                }
7707
7708                if (mounted) {
7709                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7710
7711                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7712                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7713
7714                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
7715                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7716
7717                    // Always subtract cache size, since it's a subdirectory
7718                    mStats.externalDataSize -= mStats.externalCacheSize;
7719
7720                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7721                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7722
7723                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
7724                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7725                }
7726            }
7727        }
7728
7729        @Override
7730        void handleReturnCode() {
7731            if (mObserver != null) {
7732                try {
7733                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7734                } catch (RemoteException e) {
7735                    Slog.i(TAG, "Observer no longer exists.");
7736                }
7737            }
7738        }
7739
7740        @Override
7741        void handleServiceError() {
7742            Slog.e(TAG, "Could not measure application " + mStats.packageName
7743                            + " external storage");
7744        }
7745    }
7746
7747    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7748            throws RemoteException {
7749        long result = 0;
7750        for (File path : paths) {
7751            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7752        }
7753        return result;
7754    }
7755
7756    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7757        for (File path : paths) {
7758            try {
7759                mcs.clearDirectory(path.getAbsolutePath());
7760            } catch (RemoteException e) {
7761            }
7762        }
7763    }
7764
7765    class InstallParams extends HandlerParams {
7766        final IPackageInstallObserver observer;
7767        final IPackageInstallObserver2 observer2;
7768        int flags;
7769
7770        private final Uri mPackageURI;
7771        final String installerPackageName;
7772        final VerificationParams verificationParams;
7773        private InstallArgs mArgs;
7774        private int mRet;
7775        private File mTempPackage;
7776        final ContainerEncryptionParams encryptionParams;
7777
7778        InstallParams(Uri packageURI,
7779                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7780                int flags, String installerPackageName, VerificationParams verificationParams,
7781                ContainerEncryptionParams encryptionParams, UserHandle user) {
7782            super(user);
7783            this.mPackageURI = packageURI;
7784            this.flags = flags;
7785            this.observer = observer;
7786            this.observer2 = observer2;
7787            this.installerPackageName = installerPackageName;
7788            this.verificationParams = verificationParams;
7789            this.encryptionParams = encryptionParams;
7790        }
7791
7792        @Override
7793        public String toString() {
7794            return "InstallParams{"
7795                + Integer.toHexString(System.identityHashCode(this))
7796                + " " + mPackageURI + "}";
7797        }
7798
7799        public ManifestDigest getManifestDigest() {
7800            if (verificationParams == null) {
7801                return null;
7802            }
7803            return verificationParams.getManifestDigest();
7804        }
7805
7806        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7807            String packageName = pkgLite.packageName;
7808            int installLocation = pkgLite.installLocation;
7809            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7810            // reader
7811            synchronized (mPackages) {
7812                PackageParser.Package pkg = mPackages.get(packageName);
7813                if (pkg != null) {
7814                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7815                        // Check for downgrading.
7816                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7817                            if (pkgLite.versionCode < pkg.mVersionCode) {
7818                                Slog.w(TAG, "Can't install update of " + packageName
7819                                        + " update version " + pkgLite.versionCode
7820                                        + " is older than installed version "
7821                                        + pkg.mVersionCode);
7822                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7823                            }
7824                        }
7825                        // Check for updated system application.
7826                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7827                            if (onSd) {
7828                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7829                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7830                            }
7831                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7832                        } else {
7833                            if (onSd) {
7834                                // Install flag overrides everything.
7835                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7836                            }
7837                            // If current upgrade specifies particular preference
7838                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7839                                // Application explicitly specified internal.
7840                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7841                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7842                                // App explictly prefers external. Let policy decide
7843                            } else {
7844                                // Prefer previous location
7845                                if (isExternal(pkg)) {
7846                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7847                                }
7848                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7849                            }
7850                        }
7851                    } else {
7852                        // Invalid install. Return error code
7853                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7854                    }
7855                }
7856            }
7857            // All the special cases have been taken care of.
7858            // Return result based on recommended install location.
7859            if (onSd) {
7860                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7861            }
7862            return pkgLite.recommendedInstallLocation;
7863        }
7864
7865        private long getMemoryLowThreshold() {
7866            final DeviceStorageMonitorInternal
7867                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7868            if (dsm == null) {
7869                return 0L;
7870            }
7871            return dsm.getMemoryLowThreshold();
7872        }
7873
7874        /*
7875         * Invoke remote method to get package information and install
7876         * location values. Override install location based on default
7877         * policy if needed and then create install arguments based
7878         * on the install location.
7879         */
7880        public void handleStartCopy() throws RemoteException {
7881            int ret = PackageManager.INSTALL_SUCCEEDED;
7882            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7883            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7884            PackageInfoLite pkgLite = null;
7885
7886            if (onInt && onSd) {
7887                // Check if both bits are set.
7888                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7889                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7890            } else {
7891                final long lowThreshold = getMemoryLowThreshold();
7892                if (lowThreshold == 0L) {
7893                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7894                }
7895
7896                try {
7897                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7898                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7899
7900                    final File packageFile;
7901                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7902                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7903                        if (mTempPackage != null) {
7904                            ParcelFileDescriptor out;
7905                            try {
7906                                out = ParcelFileDescriptor.open(mTempPackage,
7907                                        ParcelFileDescriptor.MODE_READ_WRITE);
7908                            } catch (FileNotFoundException e) {
7909                                out = null;
7910                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7911                            }
7912
7913                            // Make a temporary file for decryption.
7914                            ret = mContainerService
7915                                    .copyResource(mPackageURI, encryptionParams, out);
7916                            IoUtils.closeQuietly(out);
7917
7918                            packageFile = mTempPackage;
7919
7920                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7921                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7922                                            | FileUtils.S_IROTH,
7923                                    -1, -1);
7924                        } else {
7925                            packageFile = null;
7926                        }
7927                    } else {
7928                        packageFile = new File(mPackageURI.getPath());
7929                    }
7930
7931                    if (packageFile != null) {
7932                        // Remote call to find out default install location
7933                        final String packageFilePath = packageFile.getAbsolutePath();
7934                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7935                                lowThreshold);
7936
7937                        /*
7938                         * If we have too little free space, try to free cache
7939                         * before giving up.
7940                         */
7941                        if (pkgLite.recommendedInstallLocation
7942                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7943                            final long size = mContainerService.calculateInstalledSize(
7944                                    packageFilePath, isForwardLocked());
7945                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7946                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7947                                        flags, lowThreshold);
7948                            }
7949                            /*
7950                             * The cache free must have deleted the file we
7951                             * downloaded to install.
7952                             *
7953                             * TODO: fix the "freeCache" call to not delete
7954                             *       the file we care about.
7955                             */
7956                            if (pkgLite.recommendedInstallLocation
7957                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7958                                pkgLite.recommendedInstallLocation
7959                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7960                            }
7961                        }
7962                    }
7963                } finally {
7964                    mContext.revokeUriPermission(mPackageURI,
7965                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7966                }
7967            }
7968
7969            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7970                int loc = pkgLite.recommendedInstallLocation;
7971                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7972                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7973                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7974                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7975                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7976                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7977                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7978                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7979                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7980                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7981                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7982                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7983                } else {
7984                    // Override with defaults if needed.
7985                    loc = installLocationPolicy(pkgLite, flags);
7986                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7987                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7988                    } else if (!onSd && !onInt) {
7989                        // Override install location with flags
7990                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7991                            // Set the flag to install on external media.
7992                            flags |= PackageManager.INSTALL_EXTERNAL;
7993                            flags &= ~PackageManager.INSTALL_INTERNAL;
7994                        } else {
7995                            // Make sure the flag for installing on external
7996                            // media is unset
7997                            flags |= PackageManager.INSTALL_INTERNAL;
7998                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7999                        }
8000                    }
8001                }
8002            }
8003
8004            final InstallArgs args = createInstallArgs(this);
8005            mArgs = args;
8006
8007            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8008                 /*
8009                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8010                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8011                 */
8012                int userIdentifier = getUser().getIdentifier();
8013                if (userIdentifier == UserHandle.USER_ALL
8014                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8015                    userIdentifier = UserHandle.USER_OWNER;
8016                }
8017
8018                /*
8019                 * Determine if we have any installed package verifiers. If we
8020                 * do, then we'll defer to them to verify the packages.
8021                 */
8022                final int requiredUid = mRequiredVerifierPackage == null ? -1
8023                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8024                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8025                    final Intent verification = new Intent(
8026                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8027                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8028                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8029
8030                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8031                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8032                            0 /* TODO: Which userId? */);
8033
8034                    if (DEBUG_VERIFY) {
8035                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8036                                + verification.toString() + " with " + pkgLite.verifiers.length
8037                                + " optional verifiers");
8038                    }
8039
8040                    final int verificationId = mPendingVerificationToken++;
8041
8042                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8043
8044                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8045                            installerPackageName);
8046
8047                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8048
8049                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8050                            pkgLite.packageName);
8051
8052                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8053                            pkgLite.versionCode);
8054
8055                    if (verificationParams != null) {
8056                        if (verificationParams.getVerificationURI() != null) {
8057                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8058                                 verificationParams.getVerificationURI());
8059                        }
8060                        if (verificationParams.getOriginatingURI() != null) {
8061                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8062                                  verificationParams.getOriginatingURI());
8063                        }
8064                        if (verificationParams.getReferrer() != null) {
8065                            verification.putExtra(Intent.EXTRA_REFERRER,
8066                                  verificationParams.getReferrer());
8067                        }
8068                        if (verificationParams.getOriginatingUid() >= 0) {
8069                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8070                                  verificationParams.getOriginatingUid());
8071                        }
8072                        if (verificationParams.getInstallerUid() >= 0) {
8073                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8074                                  verificationParams.getInstallerUid());
8075                        }
8076                    }
8077
8078                    final PackageVerificationState verificationState = new PackageVerificationState(
8079                            requiredUid, args);
8080
8081                    mPendingVerification.append(verificationId, verificationState);
8082
8083                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8084                            receivers, verificationState);
8085
8086                    /*
8087                     * If any sufficient verifiers were listed in the package
8088                     * manifest, attempt to ask them.
8089                     */
8090                    if (sufficientVerifiers != null) {
8091                        final int N = sufficientVerifiers.size();
8092                        if (N == 0) {
8093                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8094                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8095                        } else {
8096                            for (int i = 0; i < N; i++) {
8097                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8098
8099                                final Intent sufficientIntent = new Intent(verification);
8100                                sufficientIntent.setComponent(verifierComponent);
8101
8102                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8103                            }
8104                        }
8105                    }
8106
8107                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8108                            mRequiredVerifierPackage, receivers);
8109                    if (ret == PackageManager.INSTALL_SUCCEEDED
8110                            && mRequiredVerifierPackage != null) {
8111                        /*
8112                         * Send the intent to the required verification agent,
8113                         * but only start the verification timeout after the
8114                         * target BroadcastReceivers have run.
8115                         */
8116                        verification.setComponent(requiredVerifierComponent);
8117                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8118                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8119                                new BroadcastReceiver() {
8120                                    @Override
8121                                    public void onReceive(Context context, Intent intent) {
8122                                        final Message msg = mHandler
8123                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8124                                        msg.arg1 = verificationId;
8125                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8126                                    }
8127                                }, null, 0, null, null);
8128
8129                        /*
8130                         * We don't want the copy to proceed until verification
8131                         * succeeds, so null out this field.
8132                         */
8133                        mArgs = null;
8134                    }
8135                } else {
8136                    /*
8137                     * No package verification is enabled, so immediately start
8138                     * the remote call to initiate copy using temporary file.
8139                     */
8140                    ret = args.copyApk(mContainerService, true);
8141                }
8142            }
8143
8144            mRet = ret;
8145        }
8146
8147        @Override
8148        void handleReturnCode() {
8149            // If mArgs is null, then MCS couldn't be reached. When it
8150            // reconnects, it will try again to install. At that point, this
8151            // will succeed.
8152            if (mArgs != null) {
8153                processPendingInstall(mArgs, mRet);
8154
8155                if (mTempPackage != null) {
8156                    if (!mTempPackage.delete()) {
8157                        Slog.w(TAG, "Couldn't delete temporary file: " +
8158                                mTempPackage.getAbsolutePath());
8159                    }
8160                }
8161            }
8162        }
8163
8164        @Override
8165        void handleServiceError() {
8166            mArgs = createInstallArgs(this);
8167            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8168        }
8169
8170        public boolean isForwardLocked() {
8171            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8172        }
8173
8174        public Uri getPackageUri() {
8175            if (mTempPackage != null) {
8176                return Uri.fromFile(mTempPackage);
8177            } else {
8178                return mPackageURI;
8179            }
8180        }
8181    }
8182
8183    /*
8184     * Utility class used in movePackage api.
8185     * srcArgs and targetArgs are not set for invalid flags and make
8186     * sure to do null checks when invoking methods on them.
8187     * We probably want to return ErrorPrams for both failed installs
8188     * and moves.
8189     */
8190    class MoveParams extends HandlerParams {
8191        final IPackageMoveObserver observer;
8192        final int flags;
8193        final String packageName;
8194        final InstallArgs srcArgs;
8195        final InstallArgs targetArgs;
8196        int uid;
8197        int mRet;
8198
8199        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8200                String packageName, String dataDir, int uid, UserHandle user) {
8201            super(user);
8202            this.srcArgs = srcArgs;
8203            this.observer = observer;
8204            this.flags = flags;
8205            this.packageName = packageName;
8206            this.uid = uid;
8207            if (srcArgs != null) {
8208                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8209                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
8210            } else {
8211                targetArgs = null;
8212            }
8213        }
8214
8215        @Override
8216        public String toString() {
8217            return "MoveParams{"
8218                + Integer.toHexString(System.identityHashCode(this))
8219                + " " + packageName + "}";
8220        }
8221
8222        public void handleStartCopy() throws RemoteException {
8223            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8224            // Check for storage space on target medium
8225            if (!targetArgs.checkFreeStorage(mContainerService)) {
8226                Log.w(TAG, "Insufficient storage to install");
8227                return;
8228            }
8229
8230            mRet = srcArgs.doPreCopy();
8231            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8232                return;
8233            }
8234
8235            mRet = targetArgs.copyApk(mContainerService, false);
8236            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8237                srcArgs.doPostCopy(uid);
8238                return;
8239            }
8240
8241            mRet = srcArgs.doPostCopy(uid);
8242            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8243                return;
8244            }
8245
8246            mRet = targetArgs.doPreInstall(mRet);
8247            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8248                return;
8249            }
8250
8251            if (DEBUG_SD_INSTALL) {
8252                StringBuilder builder = new StringBuilder();
8253                if (srcArgs != null) {
8254                    builder.append("src: ");
8255                    builder.append(srcArgs.getCodePath());
8256                }
8257                if (targetArgs != null) {
8258                    builder.append(" target : ");
8259                    builder.append(targetArgs.getCodePath());
8260                }
8261                Log.i(TAG, builder.toString());
8262            }
8263        }
8264
8265        @Override
8266        void handleReturnCode() {
8267            targetArgs.doPostInstall(mRet, uid);
8268            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8269            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8270                currentStatus = PackageManager.MOVE_SUCCEEDED;
8271            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8272                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8273            }
8274            processPendingMove(this, currentStatus);
8275        }
8276
8277        @Override
8278        void handleServiceError() {
8279            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8280        }
8281    }
8282
8283    /**
8284     * Used during creation of InstallArgs
8285     *
8286     * @param flags package installation flags
8287     * @return true if should be installed on external storage
8288     */
8289    private static boolean installOnSd(int flags) {
8290        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8291            return false;
8292        }
8293        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8294            return true;
8295        }
8296        return false;
8297    }
8298
8299    /**
8300     * Used during creation of InstallArgs
8301     *
8302     * @param flags package installation flags
8303     * @return true if should be installed as forward locked
8304     */
8305    private static boolean installForwardLocked(int flags) {
8306        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8307    }
8308
8309    private InstallArgs createInstallArgs(InstallParams params) {
8310        if (installOnSd(params.flags) || params.isForwardLocked()) {
8311            return new AsecInstallArgs(params);
8312        } else {
8313            return new FileInstallArgs(params);
8314        }
8315    }
8316
8317    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8318            String nativeLibraryPath) {
8319        final boolean isInAsec;
8320        if (installOnSd(flags)) {
8321            /* Apps on SD card are always in ASEC containers. */
8322            isInAsec = true;
8323        } else if (installForwardLocked(flags)
8324                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8325            /*
8326             * Forward-locked apps are only in ASEC containers if they're the
8327             * new style
8328             */
8329            isInAsec = true;
8330        } else {
8331            isInAsec = false;
8332        }
8333
8334        if (isInAsec) {
8335            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8336                    installOnSd(flags), installForwardLocked(flags));
8337        } else {
8338            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
8339        }
8340    }
8341
8342    // Used by package mover
8343    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
8344        if (installOnSd(flags) || installForwardLocked(flags)) {
8345            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8346                    + AsecInstallArgs.RES_FILE_NAME);
8347            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
8348                    installForwardLocked(flags));
8349        } else {
8350            return new FileInstallArgs(packageURI, pkgName, dataDir);
8351        }
8352    }
8353
8354    static abstract class InstallArgs {
8355        final IPackageInstallObserver observer;
8356        final IPackageInstallObserver2 observer2;
8357        // Always refers to PackageManager flags only
8358        final int flags;
8359        final Uri packageURI;
8360        final String installerPackageName;
8361        final ManifestDigest manifestDigest;
8362        final UserHandle user;
8363
8364        InstallArgs(Uri packageURI,
8365                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8366                int flags, String installerPackageName, ManifestDigest manifestDigest,
8367                UserHandle user) {
8368            this.packageURI = packageURI;
8369            this.flags = flags;
8370            this.observer = observer;
8371            this.observer2 = observer2;
8372            this.installerPackageName = installerPackageName;
8373            this.manifestDigest = manifestDigest;
8374            this.user = user;
8375        }
8376
8377        abstract void createCopyFile();
8378        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8379        abstract int doPreInstall(int status);
8380        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8381
8382        abstract int doPostInstall(int status, int uid);
8383        abstract String getCodePath();
8384        abstract String getResourcePath();
8385        abstract String getNativeLibraryPath();
8386        // Need installer lock especially for dex file removal.
8387        abstract void cleanUpResourcesLI();
8388        abstract boolean doPostDeleteLI(boolean delete);
8389        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8390
8391        /**
8392         * Called before the source arguments are copied. This is used mostly
8393         * for MoveParams when it needs to read the source file to put it in the
8394         * destination.
8395         */
8396        int doPreCopy() {
8397            return PackageManager.INSTALL_SUCCEEDED;
8398        }
8399
8400        /**
8401         * Called after the source arguments are copied. This is used mostly for
8402         * MoveParams when it needs to read the source file to put it in the
8403         * destination.
8404         *
8405         * @return
8406         */
8407        int doPostCopy(int uid) {
8408            return PackageManager.INSTALL_SUCCEEDED;
8409        }
8410
8411        protected boolean isFwdLocked() {
8412            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8413        }
8414
8415        UserHandle getUser() {
8416            return user;
8417        }
8418    }
8419
8420    class FileInstallArgs extends InstallArgs {
8421        File installDir;
8422        String codeFileName;
8423        String resourceFileName;
8424        String libraryPath;
8425        boolean created = false;
8426
8427        FileInstallArgs(InstallParams params) {
8428            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8429                    params.installerPackageName, params.getManifestDigest(),
8430                    params.getUser());
8431        }
8432
8433        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
8434            super(null, null, null, 0, null, null, null);
8435            File codeFile = new File(fullCodePath);
8436            installDir = codeFile.getParentFile();
8437            codeFileName = fullCodePath;
8438            resourceFileName = fullResourcePath;
8439            libraryPath = nativeLibraryPath;
8440        }
8441
8442        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
8443            super(packageURI, null, null, 0, null, null, null);
8444            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8445            String apkName = getNextCodePath(null, pkgName, ".apk");
8446            codeFileName = new File(installDir, apkName + ".apk").getPath();
8447            resourceFileName = getResourcePathFromCodePath();
8448            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8449        }
8450
8451        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8452            final long lowThreshold;
8453
8454            final DeviceStorageMonitorInternal
8455                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8456            if (dsm == null) {
8457                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8458                lowThreshold = 0L;
8459            } else {
8460                if (dsm.isMemoryLow()) {
8461                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8462                    return false;
8463                }
8464
8465                lowThreshold = dsm.getMemoryLowThreshold();
8466            }
8467
8468            try {
8469                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8470                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8471                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8472            } finally {
8473                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8474            }
8475        }
8476
8477        String getCodePath() {
8478            return codeFileName;
8479        }
8480
8481        void createCopyFile() {
8482            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8483            codeFileName = createTempPackageFile(installDir).getPath();
8484            resourceFileName = getResourcePathFromCodePath();
8485            libraryPath = getLibraryPathFromCodePath();
8486            created = true;
8487        }
8488
8489        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8490            if (temp) {
8491                // Generate temp file name
8492                createCopyFile();
8493            }
8494            // Get a ParcelFileDescriptor to write to the output file
8495            File codeFile = new File(codeFileName);
8496            if (!created) {
8497                try {
8498                    codeFile.createNewFile();
8499                    // Set permissions
8500                    if (!setPermissions()) {
8501                        // Failed setting permissions.
8502                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8503                    }
8504                } catch (IOException e) {
8505                   Slog.w(TAG, "Failed to create file " + codeFile);
8506                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8507                }
8508            }
8509            ParcelFileDescriptor out = null;
8510            try {
8511                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8512            } catch (FileNotFoundException e) {
8513                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8514                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8515            }
8516            // Copy the resource now
8517            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8518            try {
8519                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8520                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8521                ret = imcs.copyResource(packageURI, null, out);
8522            } finally {
8523                IoUtils.closeQuietly(out);
8524                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8525            }
8526
8527            if (isFwdLocked()) {
8528                final File destResourceFile = new File(getResourcePath());
8529
8530                // Copy the public files
8531                try {
8532                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8533                } catch (IOException e) {
8534                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8535                            + " forward-locked app.");
8536                    destResourceFile.delete();
8537                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8538                }
8539            }
8540
8541            final File nativeLibraryFile = new File(getNativeLibraryPath());
8542            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8543            if (nativeLibraryFile.exists()) {
8544                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8545                nativeLibraryFile.delete();
8546            }
8547            try {
8548                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8549                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8550                    return copyRet;
8551                }
8552            } catch (IOException e) {
8553                Slog.e(TAG, "Copying native libraries failed", e);
8554                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8555            }
8556
8557            return ret;
8558        }
8559
8560        int doPreInstall(int status) {
8561            if (status != PackageManager.INSTALL_SUCCEEDED) {
8562                cleanUp();
8563            }
8564            return status;
8565        }
8566
8567        boolean doRename(int status, final String pkgName, String oldCodePath) {
8568            if (status != PackageManager.INSTALL_SUCCEEDED) {
8569                cleanUp();
8570                return false;
8571            } else {
8572                final File oldCodeFile = new File(getCodePath());
8573                final File oldResourceFile = new File(getResourcePath());
8574                final File oldLibraryFile = new File(getNativeLibraryPath());
8575
8576                // Rename APK file based on packageName
8577                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8578                final File newCodeFile = new File(installDir, apkName + ".apk");
8579                if (!oldCodeFile.renameTo(newCodeFile)) {
8580                    return false;
8581                }
8582                codeFileName = newCodeFile.getPath();
8583
8584                // Rename public resource file if it's forward-locked.
8585                final File newResFile = new File(getResourcePathFromCodePath());
8586                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8587                    return false;
8588                }
8589                resourceFileName = newResFile.getPath();
8590
8591                // Rename library path
8592                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8593                if (newLibraryFile.exists()) {
8594                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8595                    newLibraryFile.delete();
8596                }
8597                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8598                    Slog.e(TAG, "Cannot rename native library directory "
8599                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8600                    return false;
8601                }
8602                libraryPath = newLibraryFile.getPath();
8603
8604                // Attempt to set permissions
8605                if (!setPermissions()) {
8606                    return false;
8607                }
8608
8609                if (!SELinux.restorecon(newCodeFile)) {
8610                    return false;
8611                }
8612
8613                return true;
8614            }
8615        }
8616
8617        int doPostInstall(int status, int uid) {
8618            if (status != PackageManager.INSTALL_SUCCEEDED) {
8619                cleanUp();
8620            }
8621            return status;
8622        }
8623
8624        String getResourcePath() {
8625            return resourceFileName;
8626        }
8627
8628        private String getResourcePathFromCodePath() {
8629            final String codePath = getCodePath();
8630            if (isFwdLocked()) {
8631                final StringBuilder sb = new StringBuilder();
8632
8633                sb.append(mAppInstallDir.getPath());
8634                sb.append('/');
8635                sb.append(getApkName(codePath));
8636                sb.append(".zip");
8637
8638                /*
8639                 * If our APK is a temporary file, mark the resource as a
8640                 * temporary file as well so it can be cleaned up after
8641                 * catastrophic failure.
8642                 */
8643                if (codePath.endsWith(".tmp")) {
8644                    sb.append(".tmp");
8645                }
8646
8647                return sb.toString();
8648            } else {
8649                return codePath;
8650            }
8651        }
8652
8653        private String getLibraryPathFromCodePath() {
8654            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8655        }
8656
8657        @Override
8658        String getNativeLibraryPath() {
8659            if (libraryPath == null) {
8660                libraryPath = getLibraryPathFromCodePath();
8661            }
8662            return libraryPath;
8663        }
8664
8665        private boolean cleanUp() {
8666            boolean ret = true;
8667            String sourceDir = getCodePath();
8668            String publicSourceDir = getResourcePath();
8669            if (sourceDir != null) {
8670                File sourceFile = new File(sourceDir);
8671                if (!sourceFile.exists()) {
8672                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8673                    ret = false;
8674                }
8675                // Delete application's code and resources
8676                sourceFile.delete();
8677            }
8678            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8679                final File publicSourceFile = new File(publicSourceDir);
8680                if (!publicSourceFile.exists()) {
8681                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8682                }
8683                if (publicSourceFile.exists()) {
8684                    publicSourceFile.delete();
8685                }
8686            }
8687
8688            if (libraryPath != null) {
8689                File nativeLibraryFile = new File(libraryPath);
8690                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8691                if (!nativeLibraryFile.delete()) {
8692                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8693                }
8694            }
8695
8696            return ret;
8697        }
8698
8699        void cleanUpResourcesLI() {
8700            String sourceDir = getCodePath();
8701            if (cleanUp()) {
8702                int retCode = mInstaller.rmdex(sourceDir);
8703                if (retCode < 0) {
8704                    Slog.w(TAG, "Couldn't remove dex file for package: "
8705                            +  " at location "
8706                            + sourceDir + ", retcode=" + retCode);
8707                    // we don't consider this to be a failure of the core package deletion
8708                }
8709            }
8710        }
8711
8712        private boolean setPermissions() {
8713            // TODO Do this in a more elegant way later on. for now just a hack
8714            if (!isFwdLocked()) {
8715                final int filePermissions =
8716                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8717                    |FileUtils.S_IROTH;
8718                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8719                if (retCode != 0) {
8720                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8721                            getCodePath()
8722                            + ". The return code was: " + retCode);
8723                    // TODO Define new internal error
8724                    return false;
8725                }
8726                return true;
8727            }
8728            return true;
8729        }
8730
8731        boolean doPostDeleteLI(boolean delete) {
8732            // XXX err, shouldn't we respect the delete flag?
8733            cleanUpResourcesLI();
8734            return true;
8735        }
8736    }
8737
8738    private boolean isAsecExternal(String cid) {
8739        final String asecPath = PackageHelper.getSdFilesystem(cid);
8740        return !asecPath.startsWith(mAsecInternalPath);
8741    }
8742
8743    /**
8744     * Extract the MountService "container ID" from the full code path of an
8745     * .apk.
8746     */
8747    static String cidFromCodePath(String fullCodePath) {
8748        int eidx = fullCodePath.lastIndexOf("/");
8749        String subStr1 = fullCodePath.substring(0, eidx);
8750        int sidx = subStr1.lastIndexOf("/");
8751        return subStr1.substring(sidx+1, eidx);
8752    }
8753
8754    class AsecInstallArgs extends InstallArgs {
8755        static final String RES_FILE_NAME = "pkg.apk";
8756        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8757
8758        String cid;
8759        String packagePath;
8760        String resourcePath;
8761        String libraryPath;
8762
8763        AsecInstallArgs(InstallParams params) {
8764            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8765                    params.installerPackageName, params.getManifestDigest(),
8766                    params.getUser());
8767        }
8768
8769        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8770                boolean isExternal, boolean isForwardLocked) {
8771            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8772                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8773                    null, null, null);
8774            // Extract cid from fullCodePath
8775            int eidx = fullCodePath.lastIndexOf("/");
8776            String subStr1 = fullCodePath.substring(0, eidx);
8777            int sidx = subStr1.lastIndexOf("/");
8778            cid = subStr1.substring(sidx+1, eidx);
8779            setCachePath(subStr1);
8780        }
8781
8782        AsecInstallArgs(String cid, boolean isForwardLocked) {
8783            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8784                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8785                    null, null, null);
8786            this.cid = cid;
8787            setCachePath(PackageHelper.getSdDir(cid));
8788        }
8789
8790        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
8791            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8792                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8793                    null, null, null);
8794            this.cid = cid;
8795        }
8796
8797        void createCopyFile() {
8798            cid = getTempContainerId();
8799        }
8800
8801        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8802            try {
8803                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8804                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8805                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8806            } finally {
8807                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8808            }
8809        }
8810
8811        private final boolean isExternal() {
8812            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8813        }
8814
8815        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8816            if (temp) {
8817                createCopyFile();
8818            } else {
8819                /*
8820                 * Pre-emptively destroy the container since it's destroyed if
8821                 * copying fails due to it existing anyway.
8822                 */
8823                PackageHelper.destroySdDir(cid);
8824            }
8825
8826            final String newCachePath;
8827            try {
8828                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8829                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8830                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8831                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8832            } finally {
8833                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8834            }
8835
8836            if (newCachePath != null) {
8837                setCachePath(newCachePath);
8838                return PackageManager.INSTALL_SUCCEEDED;
8839            } else {
8840                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8841            }
8842        }
8843
8844        @Override
8845        String getCodePath() {
8846            return packagePath;
8847        }
8848
8849        @Override
8850        String getResourcePath() {
8851            return resourcePath;
8852        }
8853
8854        @Override
8855        String getNativeLibraryPath() {
8856            return libraryPath;
8857        }
8858
8859        int doPreInstall(int status) {
8860            if (status != PackageManager.INSTALL_SUCCEEDED) {
8861                // Destroy container
8862                PackageHelper.destroySdDir(cid);
8863            } else {
8864                boolean mounted = PackageHelper.isContainerMounted(cid);
8865                if (!mounted) {
8866                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8867                            Process.SYSTEM_UID);
8868                    if (newCachePath != null) {
8869                        setCachePath(newCachePath);
8870                    } else {
8871                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8872                    }
8873                }
8874            }
8875            return status;
8876        }
8877
8878        boolean doRename(int status, final String pkgName,
8879                String oldCodePath) {
8880            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8881            String newCachePath = null;
8882            if (PackageHelper.isContainerMounted(cid)) {
8883                // Unmount the container
8884                if (!PackageHelper.unMountSdDir(cid)) {
8885                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8886                    return false;
8887                }
8888            }
8889            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8890                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8891                        " which might be stale. Will try to clean up.");
8892                // Clean up the stale container and proceed to recreate.
8893                if (!PackageHelper.destroySdDir(newCacheId)) {
8894                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8895                    return false;
8896                }
8897                // Successfully cleaned up stale container. Try to rename again.
8898                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8899                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8900                            + " inspite of cleaning it up.");
8901                    return false;
8902                }
8903            }
8904            if (!PackageHelper.isContainerMounted(newCacheId)) {
8905                Slog.w(TAG, "Mounting container " + newCacheId);
8906                newCachePath = PackageHelper.mountSdDir(newCacheId,
8907                        getEncryptKey(), Process.SYSTEM_UID);
8908            } else {
8909                newCachePath = PackageHelper.getSdDir(newCacheId);
8910            }
8911            if (newCachePath == null) {
8912                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8913                return false;
8914            }
8915            Log.i(TAG, "Succesfully renamed " + cid +
8916                    " to " + newCacheId +
8917                    " at new path: " + newCachePath);
8918            cid = newCacheId;
8919            setCachePath(newCachePath);
8920            return true;
8921        }
8922
8923        private void setCachePath(String newCachePath) {
8924            File cachePath = new File(newCachePath);
8925            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8926            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8927
8928            if (isFwdLocked()) {
8929                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8930            } else {
8931                resourcePath = packagePath;
8932            }
8933        }
8934
8935        int doPostInstall(int status, int uid) {
8936            if (status != PackageManager.INSTALL_SUCCEEDED) {
8937                cleanUp();
8938            } else {
8939                final int groupOwner;
8940                final String protectedFile;
8941                if (isFwdLocked()) {
8942                    groupOwner = UserHandle.getSharedAppGid(uid);
8943                    protectedFile = RES_FILE_NAME;
8944                } else {
8945                    groupOwner = -1;
8946                    protectedFile = null;
8947                }
8948
8949                if (uid < Process.FIRST_APPLICATION_UID
8950                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8951                    Slog.e(TAG, "Failed to finalize " + cid);
8952                    PackageHelper.destroySdDir(cid);
8953                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8954                }
8955
8956                boolean mounted = PackageHelper.isContainerMounted(cid);
8957                if (!mounted) {
8958                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8959                }
8960            }
8961            return status;
8962        }
8963
8964        private void cleanUp() {
8965            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8966
8967            // Destroy secure container
8968            PackageHelper.destroySdDir(cid);
8969        }
8970
8971        void cleanUpResourcesLI() {
8972            String sourceFile = getCodePath();
8973            // Remove dex file
8974            int retCode = mInstaller.rmdex(sourceFile);
8975            if (retCode < 0) {
8976                Slog.w(TAG, "Couldn't remove dex file for package: "
8977                        + " at location "
8978                        + sourceFile.toString() + ", retcode=" + retCode);
8979                // we don't consider this to be a failure of the core package deletion
8980            }
8981            cleanUp();
8982        }
8983
8984        boolean matchContainer(String app) {
8985            if (cid.startsWith(app)) {
8986                return true;
8987            }
8988            return false;
8989        }
8990
8991        String getPackageName() {
8992            return getAsecPackageName(cid);
8993        }
8994
8995        boolean doPostDeleteLI(boolean delete) {
8996            boolean ret = false;
8997            boolean mounted = PackageHelper.isContainerMounted(cid);
8998            if (mounted) {
8999                // Unmount first
9000                ret = PackageHelper.unMountSdDir(cid);
9001            }
9002            if (ret && delete) {
9003                cleanUpResourcesLI();
9004            }
9005            return ret;
9006        }
9007
9008        @Override
9009        int doPreCopy() {
9010            if (isFwdLocked()) {
9011                if (!PackageHelper.fixSdPermissions(cid,
9012                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9013                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9014                }
9015            }
9016
9017            return PackageManager.INSTALL_SUCCEEDED;
9018        }
9019
9020        @Override
9021        int doPostCopy(int uid) {
9022            if (isFwdLocked()) {
9023                if (uid < Process.FIRST_APPLICATION_UID
9024                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9025                                RES_FILE_NAME)) {
9026                    Slog.e(TAG, "Failed to finalize " + cid);
9027                    PackageHelper.destroySdDir(cid);
9028                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9029                }
9030            }
9031
9032            return PackageManager.INSTALL_SUCCEEDED;
9033        }
9034    };
9035
9036    static String getAsecPackageName(String packageCid) {
9037        int idx = packageCid.lastIndexOf("-");
9038        if (idx == -1) {
9039            return packageCid;
9040        }
9041        return packageCid.substring(0, idx);
9042    }
9043
9044    // Utility method used to create code paths based on package name and available index.
9045    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9046        String idxStr = "";
9047        int idx = 1;
9048        // Fall back to default value of idx=1 if prefix is not
9049        // part of oldCodePath
9050        if (oldCodePath != null) {
9051            String subStr = oldCodePath;
9052            // Drop the suffix right away
9053            if (subStr.endsWith(suffix)) {
9054                subStr = subStr.substring(0, subStr.length() - suffix.length());
9055            }
9056            // If oldCodePath already contains prefix find out the
9057            // ending index to either increment or decrement.
9058            int sidx = subStr.lastIndexOf(prefix);
9059            if (sidx != -1) {
9060                subStr = subStr.substring(sidx + prefix.length());
9061                if (subStr != null) {
9062                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9063                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9064                    }
9065                    try {
9066                        idx = Integer.parseInt(subStr);
9067                        if (idx <= 1) {
9068                            idx++;
9069                        } else {
9070                            idx--;
9071                        }
9072                    } catch(NumberFormatException e) {
9073                    }
9074                }
9075            }
9076        }
9077        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9078        return prefix + idxStr;
9079    }
9080
9081    // Utility method used to ignore ADD/REMOVE events
9082    // by directory observer.
9083    private static boolean ignoreCodePath(String fullPathStr) {
9084        String apkName = getApkName(fullPathStr);
9085        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9086        if (idx != -1 && ((idx+1) < apkName.length())) {
9087            // Make sure the package ends with a numeral
9088            String version = apkName.substring(idx+1);
9089            try {
9090                Integer.parseInt(version);
9091                return true;
9092            } catch (NumberFormatException e) {}
9093        }
9094        return false;
9095    }
9096
9097    // Utility method that returns the relative package path with respect
9098    // to the installation directory. Like say for /data/data/com.test-1.apk
9099    // string com.test-1 is returned.
9100    static String getApkName(String codePath) {
9101        if (codePath == null) {
9102            return null;
9103        }
9104        int sidx = codePath.lastIndexOf("/");
9105        int eidx = codePath.lastIndexOf(".");
9106        if (eidx == -1) {
9107            eidx = codePath.length();
9108        } else if (eidx == 0) {
9109            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9110            return null;
9111        }
9112        return codePath.substring(sidx+1, eidx);
9113    }
9114
9115    class PackageInstalledInfo {
9116        String name;
9117        int uid;
9118        // The set of users that originally had this package installed.
9119        int[] origUsers;
9120        // The set of users that now have this package installed.
9121        int[] newUsers;
9122        PackageParser.Package pkg;
9123        int returnCode;
9124        PackageRemovedInfo removedInfo;
9125
9126        // In some error cases we want to convey more info back to the observer
9127        String origPackage;
9128        String origPermission;
9129    }
9130
9131    /*
9132     * Install a non-existing package.
9133     */
9134    private void installNewPackageLI(PackageParser.Package pkg,
9135            int parseFlags, int scanMode, UserHandle user,
9136            String installerPackageName, PackageInstalledInfo res) {
9137        // Remember this for later, in case we need to rollback this install
9138        String pkgName = pkg.packageName;
9139
9140        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9141        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9142        synchronized(mPackages) {
9143            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9144                // A package with the same name is already installed, though
9145                // it has been renamed to an older name.  The package we
9146                // are trying to install should be installed as an update to
9147                // the existing one, but that has not been requested, so bail.
9148                Slog.w(TAG, "Attempt to re-install " + pkgName
9149                        + " without first uninstalling package running as "
9150                        + mSettings.mRenamedPackages.get(pkgName));
9151                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9152                return;
9153            }
9154            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9155                // Don't allow installation over an existing package with the same name.
9156                Slog.w(TAG, "Attempt to re-install " + pkgName
9157                        + " without first uninstalling.");
9158                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9159                return;
9160            }
9161        }
9162        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9163        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9164                System.currentTimeMillis(), user);
9165        if (newPackage == null) {
9166            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9167            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9168                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9169            }
9170        } else {
9171            updateSettingsLI(newPackage,
9172                    installerPackageName,
9173                    null, null,
9174                    res);
9175            // delete the partially installed application. the data directory will have to be
9176            // restored if it was already existing
9177            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9178                // remove package from internal structures.  Note that we want deletePackageX to
9179                // delete the package data and cache directories that it created in
9180                // scanPackageLocked, unless those directories existed before we even tried to
9181                // install.
9182                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9183                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9184                                res.removedInfo, true);
9185            }
9186        }
9187    }
9188
9189    private void replacePackageLI(PackageParser.Package pkg,
9190            int parseFlags, int scanMode, UserHandle user,
9191            String installerPackageName, PackageInstalledInfo res) {
9192
9193        PackageParser.Package oldPackage;
9194        String pkgName = pkg.packageName;
9195        int[] allUsers;
9196        boolean[] perUserInstalled;
9197
9198        // First find the old package info and check signatures
9199        synchronized(mPackages) {
9200            oldPackage = mPackages.get(pkgName);
9201            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9202            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9203                    != PackageManager.SIGNATURE_MATCH) {
9204                Slog.w(TAG, "New package has a different signature: " + pkgName);
9205                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9206                return;
9207            }
9208
9209            // In case of rollback, remember per-user/profile install state
9210            PackageSetting ps = mSettings.mPackages.get(pkgName);
9211            allUsers = sUserManager.getUserIds();
9212            perUserInstalled = new boolean[allUsers.length];
9213            for (int i = 0; i < allUsers.length; i++) {
9214                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9215            }
9216        }
9217        boolean sysPkg = (isSystemApp(oldPackage));
9218        if (sysPkg) {
9219            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9220                    user, allUsers, perUserInstalled, installerPackageName, res);
9221        } else {
9222            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9223                    user, allUsers, perUserInstalled, installerPackageName, res);
9224        }
9225    }
9226
9227    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9228            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9229            int[] allUsers, boolean[] perUserInstalled,
9230            String installerPackageName, PackageInstalledInfo res) {
9231        PackageParser.Package newPackage = null;
9232        String pkgName = deletedPackage.packageName;
9233        boolean deletedPkg = true;
9234        boolean updatedSettings = false;
9235
9236        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9237                + deletedPackage);
9238        long origUpdateTime;
9239        if (pkg.mExtras != null) {
9240            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9241        } else {
9242            origUpdateTime = 0;
9243        }
9244
9245        // First delete the existing package while retaining the data directory
9246        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9247                res.removedInfo, true)) {
9248            // If the existing package wasn't successfully deleted
9249            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9250            deletedPkg = false;
9251        } else {
9252            // Successfully deleted the old package. Now proceed with re-installation
9253            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9254            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9255                    System.currentTimeMillis(), user);
9256            if (newPackage == null) {
9257                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9258                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9259                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9260                }
9261            } else {
9262                updateSettingsLI(newPackage,
9263                        installerPackageName,
9264                        allUsers, perUserInstalled,
9265                        res);
9266                updatedSettings = true;
9267            }
9268        }
9269
9270        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9271            // remove package from internal structures.  Note that we want deletePackageX to
9272            // delete the package data and cache directories that it created in
9273            // scanPackageLocked, unless those directories existed before we even tried to
9274            // install.
9275            if(updatedSettings) {
9276                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9277                deletePackageLI(
9278                        pkgName, null, true, allUsers, perUserInstalled,
9279                        PackageManager.DELETE_KEEP_DATA,
9280                                res.removedInfo, true);
9281            }
9282            // Since we failed to install the new package we need to restore the old
9283            // package that we deleted.
9284            if(deletedPkg) {
9285                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9286                File restoreFile = new File(deletedPackage.mPath);
9287                // Parse old package
9288                boolean oldOnSd = isExternal(deletedPackage);
9289                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9290                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9291                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9292                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9293                        | SCAN_UPDATE_TIME;
9294                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9295                        origUpdateTime, null) == null) {
9296                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9297                    return;
9298                }
9299                // Restore of old package succeeded. Update permissions.
9300                // writer
9301                synchronized (mPackages) {
9302                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9303                            UPDATE_PERMISSIONS_ALL);
9304                    // can downgrade to reader
9305                    mSettings.writeLPr();
9306                }
9307                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9308            }
9309        }
9310    }
9311
9312    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9313            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9314            int[] allUsers, boolean[] perUserInstalled,
9315            String installerPackageName, PackageInstalledInfo res) {
9316        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9317                + ", old=" + deletedPackage);
9318        PackageParser.Package newPackage = null;
9319        boolean updatedSettings = false;
9320        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9321                PackageParser.PARSE_IS_SYSTEM;
9322        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9323            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9324        }
9325        String packageName = deletedPackage.packageName;
9326        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9327        if (packageName == null) {
9328            Slog.w(TAG, "Attempt to delete null packageName.");
9329            return;
9330        }
9331        PackageParser.Package oldPkg;
9332        PackageSetting oldPkgSetting;
9333        // reader
9334        synchronized (mPackages) {
9335            oldPkg = mPackages.get(packageName);
9336            oldPkgSetting = mSettings.mPackages.get(packageName);
9337            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9338                    (oldPkgSetting == null)) {
9339                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9340                return;
9341            }
9342        }
9343
9344        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9345
9346        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9347        res.removedInfo.removedPackage = packageName;
9348        // Remove existing system package
9349        removePackageLI(oldPkgSetting, true);
9350        // writer
9351        synchronized (mPackages) {
9352            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9353                // We didn't need to disable the .apk as a current system package,
9354                // which means we are replacing another update that is already
9355                // installed.  We need to make sure to delete the older one's .apk.
9356                res.removedInfo.args = createInstallArgs(0,
9357                        deletedPackage.applicationInfo.sourceDir,
9358                        deletedPackage.applicationInfo.publicSourceDir,
9359                        deletedPackage.applicationInfo.nativeLibraryDir);
9360            } else {
9361                res.removedInfo.args = null;
9362            }
9363        }
9364
9365        // Successfully disabled the old package. Now proceed with re-installation
9366        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9367        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9368        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9369        if (newPackage == null) {
9370            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9371            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9372                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9373            }
9374        } else {
9375            if (newPackage.mExtras != null) {
9376                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9377                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9378                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9379
9380                // is the update attempting to change shared user? that isn't going to work...
9381                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9382                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9383                            + " to " + newPkgSetting.sharedUser);
9384                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9385                    updatedSettings = true;
9386                }
9387            }
9388
9389            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9390                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9391                updatedSettings = true;
9392            }
9393        }
9394
9395        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9396            // Re installation failed. Restore old information
9397            // Remove new pkg information
9398            if (newPackage != null) {
9399                removeInstalledPackageLI(newPackage, true);
9400            }
9401            // Add back the old system package
9402            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9403            // Restore the old system information in Settings
9404            synchronized(mPackages) {
9405                if (updatedSettings) {
9406                    mSettings.enableSystemPackageLPw(packageName);
9407                    mSettings.setInstallerPackageName(packageName,
9408                            oldPkgSetting.installerPackageName);
9409                }
9410                mSettings.writeLPr();
9411            }
9412        }
9413    }
9414
9415    // Utility method used to move dex files during install.
9416    private int moveDexFilesLI(PackageParser.Package newPackage) {
9417        int retCode;
9418        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9419            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
9420            if (retCode != 0) {
9421                if (mNoDexOpt) {
9422                    /*
9423                     * If we're in an engineering build, programs are lazily run
9424                     * through dexopt. If the .dex file doesn't exist yet, it
9425                     * will be created when the program is run next.
9426                     */
9427                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9428                } else {
9429                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9430                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9431                }
9432            }
9433        }
9434        return PackageManager.INSTALL_SUCCEEDED;
9435    }
9436
9437    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9438            int[] allUsers, boolean[] perUserInstalled,
9439            PackageInstalledInfo res) {
9440        String pkgName = newPackage.packageName;
9441        synchronized (mPackages) {
9442            //write settings. the installStatus will be incomplete at this stage.
9443            //note that the new package setting would have already been
9444            //added to mPackages. It hasn't been persisted yet.
9445            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9446            mSettings.writeLPr();
9447        }
9448
9449        if ((res.returnCode = moveDexFilesLI(newPackage))
9450                != PackageManager.INSTALL_SUCCEEDED) {
9451            // Discontinue if moving dex files failed.
9452            return;
9453        }
9454
9455        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9456
9457        synchronized (mPackages) {
9458            updatePermissionsLPw(newPackage.packageName, newPackage,
9459                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9460                            ? UPDATE_PERMISSIONS_ALL : 0));
9461            // For system-bundled packages, we assume that installing an upgraded version
9462            // of the package implies that the user actually wants to run that new code,
9463            // so we enable the package.
9464            if (isSystemApp(newPackage)) {
9465                // NB: implicit assumption that system package upgrades apply to all users
9466                if (DEBUG_INSTALL) {
9467                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9468                }
9469                PackageSetting ps = mSettings.mPackages.get(pkgName);
9470                if (ps != null) {
9471                    if (res.origUsers != null) {
9472                        for (int userHandle : res.origUsers) {
9473                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9474                                    userHandle, installerPackageName);
9475                        }
9476                    }
9477                    // Also convey the prior install/uninstall state
9478                    if (allUsers != null && perUserInstalled != null) {
9479                        for (int i = 0; i < allUsers.length; i++) {
9480                            if (DEBUG_INSTALL) {
9481                                Slog.d(TAG, "    user " + allUsers[i]
9482                                        + " => " + perUserInstalled[i]);
9483                            }
9484                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9485                        }
9486                        // these install state changes will be persisted in the
9487                        // upcoming call to mSettings.writeLPr().
9488                    }
9489                }
9490            }
9491            res.name = pkgName;
9492            res.uid = newPackage.applicationInfo.uid;
9493            res.pkg = newPackage;
9494            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9495            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9496            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9497            //to update install status
9498            mSettings.writeLPr();
9499        }
9500    }
9501
9502    private void installPackageLI(InstallArgs args,
9503            boolean newInstall, PackageInstalledInfo res) {
9504        int pFlags = args.flags;
9505        String installerPackageName = args.installerPackageName;
9506        File tmpPackageFile = new File(args.getCodePath());
9507        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9508        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9509        boolean replace = false;
9510        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9511                | (newInstall ? SCAN_NEW_INSTALL : 0);
9512        // Result object to be returned
9513        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9514
9515        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9516        // Retrieve PackageSettings and parse package
9517        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9518                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9519                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9520        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9521        pp.setSeparateProcesses(mSeparateProcesses);
9522        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9523                null, mMetrics, parseFlags);
9524        if (pkg == null) {
9525            res.returnCode = pp.getParseError();
9526            return;
9527        }
9528        String pkgName = res.name = pkg.packageName;
9529        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9530            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9531                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9532                return;
9533            }
9534        }
9535        if (!pp.collectCertificates(pkg, parseFlags)) {
9536            res.returnCode = pp.getParseError();
9537            return;
9538        }
9539
9540        /* If the installer passed in a manifest digest, compare it now. */
9541        if (args.manifestDigest != null) {
9542            if (DEBUG_INSTALL) {
9543                final String parsedManifest = pkg.manifestDigest == null ? "null"
9544                        : pkg.manifestDigest.toString();
9545                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9546                        + parsedManifest);
9547            }
9548
9549            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9550                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9551                return;
9552            }
9553        } else if (DEBUG_INSTALL) {
9554            final String parsedManifest = pkg.manifestDigest == null
9555                    ? "null" : pkg.manifestDigest.toString();
9556            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9557        }
9558
9559        // Get rid of all references to package scan path via parser.
9560        pp = null;
9561        String oldCodePath = null;
9562        boolean systemApp = false;
9563        synchronized (mPackages) {
9564            // Check whether the newly-scanned package wants to define an already-defined perm
9565            int N = pkg.permissions.size();
9566            for (int i = 0; i < N; i++) {
9567                PackageParser.Permission perm = pkg.permissions.get(i);
9568                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
9569                if (bp != null) {
9570                    // If the defining package is signed with our cert, it's okay.  This
9571                    // also includes the "updating the same package" case, of course.
9572                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
9573                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9574                        Slog.w(TAG, "Package " + pkg.packageName
9575                                + " attempting to redeclare permission " + perm.info.name
9576                                + " already owned by " + bp.sourcePackage);
9577                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
9578                        res.origPermission = perm.info.name;
9579                        res.origPackage = bp.sourcePackage;
9580                        return;
9581                    }
9582                }
9583            }
9584
9585            // Check if installing already existing package
9586            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9587                String oldName = mSettings.mRenamedPackages.get(pkgName);
9588                if (pkg.mOriginalPackages != null
9589                        && pkg.mOriginalPackages.contains(oldName)
9590                        && mPackages.containsKey(oldName)) {
9591                    // This package is derived from an original package,
9592                    // and this device has been updating from that original
9593                    // name.  We must continue using the original name, so
9594                    // rename the new package here.
9595                    pkg.setPackageName(oldName);
9596                    pkgName = pkg.packageName;
9597                    replace = true;
9598                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9599                            + oldName + " pkgName=" + pkgName);
9600                } else if (mPackages.containsKey(pkgName)) {
9601                    // This package, under its official name, already exists
9602                    // on the device; we should replace it.
9603                    replace = true;
9604                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9605                }
9606            }
9607            PackageSetting ps = mSettings.mPackages.get(pkgName);
9608            if (ps != null) {
9609                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9610                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9611                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9612                    systemApp = (ps.pkg.applicationInfo.flags &
9613                            ApplicationInfo.FLAG_SYSTEM) != 0;
9614                }
9615                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9616            }
9617        }
9618
9619        if (systemApp && onSd) {
9620            // Disable updates to system apps on sdcard
9621            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9622            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9623            return;
9624        }
9625
9626        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9627            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9628            return;
9629        }
9630        // Set application objects path explicitly after the rename
9631        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9632        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9633        if (replace) {
9634            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9635                    installerPackageName, res);
9636        } else {
9637            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9638                    installerPackageName, res);
9639        }
9640        synchronized (mPackages) {
9641            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9642            if (ps != null) {
9643                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9644            }
9645        }
9646    }
9647
9648    private static boolean isForwardLocked(PackageParser.Package pkg) {
9649        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9650    }
9651
9652
9653    private boolean isForwardLocked(PackageSetting ps) {
9654        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9655    }
9656
9657    private static boolean isExternal(PackageParser.Package pkg) {
9658        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9659    }
9660
9661    private static boolean isExternal(PackageSetting ps) {
9662        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9663    }
9664
9665    private static boolean isSystemApp(PackageParser.Package pkg) {
9666        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9667    }
9668
9669    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9670        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9671    }
9672
9673    private static boolean isSystemApp(ApplicationInfo info) {
9674        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9675    }
9676
9677    private static boolean isSystemApp(PackageSetting ps) {
9678        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9679    }
9680
9681    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9682        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9683    }
9684
9685    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9686        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9687    }
9688
9689    private int packageFlagsToInstallFlags(PackageSetting ps) {
9690        int installFlags = 0;
9691        if (isExternal(ps)) {
9692            installFlags |= PackageManager.INSTALL_EXTERNAL;
9693        }
9694        if (isForwardLocked(ps)) {
9695            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9696        }
9697        return installFlags;
9698    }
9699
9700    private void deleteTempPackageFiles() {
9701        final FilenameFilter filter = new FilenameFilter() {
9702            public boolean accept(File dir, String name) {
9703                return name.startsWith("vmdl") && name.endsWith(".tmp");
9704            }
9705        };
9706        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9707        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9708    }
9709
9710    private static final void deleteTempPackageFilesInDirectory(File directory,
9711            FilenameFilter filter) {
9712        final String[] tmpFilesList = directory.list(filter);
9713        if (tmpFilesList == null) {
9714            return;
9715        }
9716        for (int i = 0; i < tmpFilesList.length; i++) {
9717            final File tmpFile = new File(directory, tmpFilesList[i]);
9718            tmpFile.delete();
9719        }
9720    }
9721
9722    private File createTempPackageFile(File installDir) {
9723        File tmpPackageFile;
9724        try {
9725            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9726        } catch (IOException e) {
9727            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9728            return null;
9729        }
9730        try {
9731            FileUtils.setPermissions(
9732                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9733                    -1, -1);
9734            if (!SELinux.restorecon(tmpPackageFile)) {
9735                return null;
9736            }
9737        } catch (IOException e) {
9738            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9739            return null;
9740        }
9741        return tmpPackageFile;
9742    }
9743
9744    @Override
9745    public void deletePackageAsUser(final String packageName,
9746                                    final IPackageDeleteObserver observer,
9747                                    final int userId, final int flags) {
9748        mContext.enforceCallingOrSelfPermission(
9749                android.Manifest.permission.DELETE_PACKAGES, null);
9750        final int uid = Binder.getCallingUid();
9751        if (UserHandle.getUserId(uid) != userId) {
9752            mContext.enforceCallingPermission(
9753                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9754                    "deletePackage for user " + userId);
9755        }
9756        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9757            try {
9758                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9759            } catch (RemoteException re) {
9760            }
9761            return;
9762        }
9763
9764        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9765        // Queue up an async operation since the package deletion may take a little while.
9766        mHandler.post(new Runnable() {
9767            public void run() {
9768                mHandler.removeCallbacks(this);
9769                final int returnCode = deletePackageX(packageName, userId, flags);
9770                if (observer != null) {
9771                    try {
9772                        observer.packageDeleted(packageName, returnCode);
9773                    } catch (RemoteException e) {
9774                        Log.i(TAG, "Observer no longer exists.");
9775                    } //end catch
9776                } //end if
9777            } //end run
9778        });
9779    }
9780
9781    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9782        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9783                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9784        try {
9785            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9786                    || dpm.isDeviceOwner(packageName))) {
9787                return true;
9788            }
9789        } catch (RemoteException e) {
9790        }
9791        return false;
9792    }
9793
9794    /**
9795     *  This method is an internal method that could be get invoked either
9796     *  to delete an installed package or to clean up a failed installation.
9797     *  After deleting an installed package, a broadcast is sent to notify any
9798     *  listeners that the package has been installed. For cleaning up a failed
9799     *  installation, the broadcast is not necessary since the package's
9800     *  installation wouldn't have sent the initial broadcast either
9801     *  The key steps in deleting a package are
9802     *  deleting the package information in internal structures like mPackages,
9803     *  deleting the packages base directories through installd
9804     *  updating mSettings to reflect current status
9805     *  persisting settings for later use
9806     *  sending a broadcast if necessary
9807     */
9808    private int deletePackageX(String packageName, int userId, int flags) {
9809        final PackageRemovedInfo info = new PackageRemovedInfo();
9810        final boolean res;
9811
9812        if (isPackageDeviceAdmin(packageName, userId)) {
9813            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9814            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9815        }
9816
9817        boolean removedForAllUsers = false;
9818        boolean systemUpdate = false;
9819
9820        // for the uninstall-updates case and restricted profiles, remember the per-
9821        // userhandle installed state
9822        int[] allUsers;
9823        boolean[] perUserInstalled;
9824        synchronized (mPackages) {
9825            PackageSetting ps = mSettings.mPackages.get(packageName);
9826            allUsers = sUserManager.getUserIds();
9827            perUserInstalled = new boolean[allUsers.length];
9828            for (int i = 0; i < allUsers.length; i++) {
9829                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9830            }
9831        }
9832
9833        synchronized (mInstallLock) {
9834            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9835            res = deletePackageLI(packageName,
9836                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9837                            ? UserHandle.ALL : new UserHandle(userId),
9838                    true, allUsers, perUserInstalled,
9839                    flags | REMOVE_CHATTY, info, true);
9840            systemUpdate = info.isRemovedPackageSystemUpdate;
9841            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9842                removedForAllUsers = true;
9843            }
9844            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9845                    + " removedForAllUsers=" + removedForAllUsers);
9846        }
9847
9848        if (res) {
9849            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9850
9851            // If the removed package was a system update, the old system package
9852            // was re-enabled; we need to broadcast this information
9853            if (systemUpdate) {
9854                Bundle extras = new Bundle(1);
9855                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9856                        ? info.removedAppId : info.uid);
9857                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9858
9859                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9860                        extras, null, null, null);
9861                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9862                        extras, null, null, null);
9863                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9864                        null, packageName, null, null);
9865            }
9866        }
9867        // Force a gc here.
9868        Runtime.getRuntime().gc();
9869        // Delete the resources here after sending the broadcast to let
9870        // other processes clean up before deleting resources.
9871        if (info.args != null) {
9872            synchronized (mInstallLock) {
9873                info.args.doPostDeleteLI(true);
9874            }
9875        }
9876
9877        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9878    }
9879
9880    static class PackageRemovedInfo {
9881        String removedPackage;
9882        int uid = -1;
9883        int removedAppId = -1;
9884        int[] removedUsers = null;
9885        boolean isRemovedPackageSystemUpdate = false;
9886        // Clean up resources deleted packages.
9887        InstallArgs args = null;
9888
9889        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9890            Bundle extras = new Bundle(1);
9891            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9892            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9893            if (replacing) {
9894                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9895            }
9896            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9897            if (removedPackage != null) {
9898                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9899                        extras, null, null, removedUsers);
9900                if (fullRemove && !replacing) {
9901                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9902                            extras, null, null, removedUsers);
9903                }
9904            }
9905            if (removedAppId >= 0) {
9906                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9907                        removedUsers);
9908            }
9909        }
9910    }
9911
9912    /*
9913     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9914     * flag is not set, the data directory is removed as well.
9915     * make sure this flag is set for partially installed apps. If not its meaningless to
9916     * delete a partially installed application.
9917     */
9918    private void removePackageDataLI(PackageSetting ps,
9919            int[] allUserHandles, boolean[] perUserInstalled,
9920            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9921        String packageName = ps.name;
9922        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9923        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9924        // Retrieve object to delete permissions for shared user later on
9925        final PackageSetting deletedPs;
9926        // reader
9927        synchronized (mPackages) {
9928            deletedPs = mSettings.mPackages.get(packageName);
9929            if (outInfo != null) {
9930                outInfo.removedPackage = packageName;
9931                outInfo.removedUsers = deletedPs != null
9932                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9933                        : null;
9934            }
9935        }
9936        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9937            removeDataDirsLI(packageName);
9938            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9939        }
9940        // writer
9941        synchronized (mPackages) {
9942            if (deletedPs != null) {
9943                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9944                    if (outInfo != null) {
9945                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9946                    }
9947                    if (deletedPs != null) {
9948                        updatePermissionsLPw(deletedPs.name, null, 0);
9949                        if (deletedPs.sharedUser != null) {
9950                            // remove permissions associated with package
9951                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9952                        }
9953                    }
9954                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9955                }
9956                // make sure to preserve per-user disabled state if this removal was just
9957                // a downgrade of a system app to the factory package
9958                if (allUserHandles != null && perUserInstalled != null) {
9959                    if (DEBUG_REMOVE) {
9960                        Slog.d(TAG, "Propagating install state across downgrade");
9961                    }
9962                    for (int i = 0; i < allUserHandles.length; i++) {
9963                        if (DEBUG_REMOVE) {
9964                            Slog.d(TAG, "    user " + allUserHandles[i]
9965                                    + " => " + perUserInstalled[i]);
9966                        }
9967                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9968                    }
9969                }
9970            }
9971            // can downgrade to reader
9972            if (writeSettings) {
9973                // Save settings now
9974                mSettings.writeLPr();
9975            }
9976        }
9977        if (outInfo != null) {
9978            // A user ID was deleted here. Go through all users and remove it
9979            // from KeyStore.
9980            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9981        }
9982    }
9983
9984    static boolean locationIsPrivileged(File path) {
9985        try {
9986            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9987                    .getCanonicalPath();
9988            return path.getCanonicalPath().startsWith(privilegedAppDir);
9989        } catch (IOException e) {
9990            Slog.e(TAG, "Unable to access code path " + path);
9991        }
9992        return false;
9993    }
9994
9995    /*
9996     * Tries to delete system package.
9997     */
9998    private boolean deleteSystemPackageLI(PackageSetting newPs,
9999            int[] allUserHandles, boolean[] perUserInstalled,
10000            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10001        final boolean applyUserRestrictions
10002                = (allUserHandles != null) && (perUserInstalled != null);
10003        PackageSetting disabledPs = null;
10004        // Confirm if the system package has been updated
10005        // An updated system app can be deleted. This will also have to restore
10006        // the system pkg from system partition
10007        // reader
10008        synchronized (mPackages) {
10009            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10010        }
10011        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10012                + " disabledPs=" + disabledPs);
10013        if (disabledPs == null) {
10014            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10015            return false;
10016        } else if (DEBUG_REMOVE) {
10017            Slog.d(TAG, "Deleting system pkg from data partition");
10018        }
10019        if (DEBUG_REMOVE) {
10020            if (applyUserRestrictions) {
10021                Slog.d(TAG, "Remembering install states:");
10022                for (int i = 0; i < allUserHandles.length; i++) {
10023                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10024                }
10025            }
10026        }
10027        // Delete the updated package
10028        outInfo.isRemovedPackageSystemUpdate = true;
10029        if (disabledPs.versionCode < newPs.versionCode) {
10030            // Delete data for downgrades
10031            flags &= ~PackageManager.DELETE_KEEP_DATA;
10032        } else {
10033            // Preserve data by setting flag
10034            flags |= PackageManager.DELETE_KEEP_DATA;
10035        }
10036        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10037                allUserHandles, perUserInstalled, outInfo, writeSettings);
10038        if (!ret) {
10039            return false;
10040        }
10041        // writer
10042        synchronized (mPackages) {
10043            // Reinstate the old system package
10044            mSettings.enableSystemPackageLPw(newPs.name);
10045            // Remove any native libraries from the upgraded package.
10046            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10047        }
10048        // Install the system package
10049        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10050        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10051        if (locationIsPrivileged(disabledPs.codePath)) {
10052            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10053        }
10054        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10055                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10056
10057        if (newPkg == null) {
10058            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10059                    + " with error:" + mLastScanError);
10060            return false;
10061        }
10062        // writer
10063        synchronized (mPackages) {
10064            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10065            setInternalAppNativeLibraryPath(newPkg, ps);
10066            updatePermissionsLPw(newPkg.packageName, newPkg,
10067                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10068            if (applyUserRestrictions) {
10069                if (DEBUG_REMOVE) {
10070                    Slog.d(TAG, "Propagating install state across reinstall");
10071                }
10072                for (int i = 0; i < allUserHandles.length; i++) {
10073                    if (DEBUG_REMOVE) {
10074                        Slog.d(TAG, "    user " + allUserHandles[i]
10075                                + " => " + perUserInstalled[i]);
10076                    }
10077                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10078                }
10079                // Regardless of writeSettings we need to ensure that this restriction
10080                // state propagation is persisted
10081                mSettings.writeAllUsersPackageRestrictionsLPr();
10082            }
10083            // can downgrade to reader here
10084            if (writeSettings) {
10085                mSettings.writeLPr();
10086            }
10087        }
10088        return true;
10089    }
10090
10091    private boolean deleteInstalledPackageLI(PackageSetting ps,
10092            boolean deleteCodeAndResources, int flags,
10093            int[] allUserHandles, boolean[] perUserInstalled,
10094            PackageRemovedInfo outInfo, boolean writeSettings) {
10095        if (outInfo != null) {
10096            outInfo.uid = ps.appId;
10097        }
10098
10099        // Delete package data from internal structures and also remove data if flag is set
10100        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10101
10102        // Delete application code and resources
10103        if (deleteCodeAndResources && (outInfo != null)) {
10104            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10105                    ps.resourcePathString, ps.nativeLibraryPathString);
10106        }
10107        return true;
10108    }
10109
10110    /*
10111     * This method handles package deletion in general
10112     */
10113    private boolean deletePackageLI(String packageName, UserHandle user,
10114            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10115            int flags, PackageRemovedInfo outInfo,
10116            boolean writeSettings) {
10117        if (packageName == null) {
10118            Slog.w(TAG, "Attempt to delete null packageName.");
10119            return false;
10120        }
10121        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10122        PackageSetting ps;
10123        boolean dataOnly = false;
10124        int removeUser = -1;
10125        int appId = -1;
10126        synchronized (mPackages) {
10127            ps = mSettings.mPackages.get(packageName);
10128            if (ps == null) {
10129                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10130                return false;
10131            }
10132            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10133                    && user.getIdentifier() != UserHandle.USER_ALL) {
10134                // The caller is asking that the package only be deleted for a single
10135                // user.  To do this, we just mark its uninstalled state and delete
10136                // its data.  If this is a system app, we only allow this to happen if
10137                // they have set the special DELETE_SYSTEM_APP which requests different
10138                // semantics than normal for uninstalling system apps.
10139                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10140                ps.setUserState(user.getIdentifier(),
10141                        COMPONENT_ENABLED_STATE_DEFAULT,
10142                        false, //installed
10143                        true,  //stopped
10144                        true,  //notLaunched
10145                        false, //blocked
10146                        null, null, null);
10147                if (!isSystemApp(ps)) {
10148                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10149                        // Other user still have this package installed, so all
10150                        // we need to do is clear this user's data and save that
10151                        // it is uninstalled.
10152                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10153                        removeUser = user.getIdentifier();
10154                        appId = ps.appId;
10155                        mSettings.writePackageRestrictionsLPr(removeUser);
10156                    } else {
10157                        // We need to set it back to 'installed' so the uninstall
10158                        // broadcasts will be sent correctly.
10159                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10160                        ps.setInstalled(true, user.getIdentifier());
10161                    }
10162                } else {
10163                    // This is a system app, so we assume that the
10164                    // other users still have this package installed, so all
10165                    // we need to do is clear this user's data and save that
10166                    // it is uninstalled.
10167                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10168                    removeUser = user.getIdentifier();
10169                    appId = ps.appId;
10170                    mSettings.writePackageRestrictionsLPr(removeUser);
10171                }
10172            }
10173        }
10174
10175        if (removeUser >= 0) {
10176            // From above, we determined that we are deleting this only
10177            // for a single user.  Continue the work here.
10178            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10179            if (outInfo != null) {
10180                outInfo.removedPackage = packageName;
10181                outInfo.removedAppId = appId;
10182                outInfo.removedUsers = new int[] {removeUser};
10183            }
10184            mInstaller.clearUserData(packageName, removeUser);
10185            removeKeystoreDataIfNeeded(removeUser, appId);
10186            schedulePackageCleaning(packageName, removeUser, false);
10187            return true;
10188        }
10189
10190        if (dataOnly) {
10191            // Delete application data first
10192            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10193            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10194            return true;
10195        }
10196
10197        boolean ret = false;
10198        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10199        if (isSystemApp(ps)) {
10200            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10201            // When an updated system application is deleted we delete the existing resources as well and
10202            // fall back to existing code in system partition
10203            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10204                    flags, outInfo, writeSettings);
10205        } else {
10206            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10207            // Kill application pre-emptively especially for apps on sd.
10208            killApplication(packageName, ps.appId, "uninstall pkg");
10209            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10210                    allUserHandles, perUserInstalled,
10211                    outInfo, writeSettings);
10212        }
10213
10214        return ret;
10215    }
10216
10217    private final class ClearStorageConnection implements ServiceConnection {
10218        IMediaContainerService mContainerService;
10219
10220        @Override
10221        public void onServiceConnected(ComponentName name, IBinder service) {
10222            synchronized (this) {
10223                mContainerService = IMediaContainerService.Stub.asInterface(service);
10224                notifyAll();
10225            }
10226        }
10227
10228        @Override
10229        public void onServiceDisconnected(ComponentName name) {
10230        }
10231    }
10232
10233    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10234        final boolean mounted;
10235        if (Environment.isExternalStorageEmulated()) {
10236            mounted = true;
10237        } else {
10238            final String status = Environment.getExternalStorageState();
10239
10240            mounted = status.equals(Environment.MEDIA_MOUNTED)
10241                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10242        }
10243
10244        if (!mounted) {
10245            return;
10246        }
10247
10248        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10249        int[] users;
10250        if (userId == UserHandle.USER_ALL) {
10251            users = sUserManager.getUserIds();
10252        } else {
10253            users = new int[] { userId };
10254        }
10255        final ClearStorageConnection conn = new ClearStorageConnection();
10256        if (mContext.bindServiceAsUser(
10257                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10258            try {
10259                for (int curUser : users) {
10260                    long timeout = SystemClock.uptimeMillis() + 5000;
10261                    synchronized (conn) {
10262                        long now = SystemClock.uptimeMillis();
10263                        while (conn.mContainerService == null && now < timeout) {
10264                            try {
10265                                conn.wait(timeout - now);
10266                            } catch (InterruptedException e) {
10267                            }
10268                        }
10269                    }
10270                    if (conn.mContainerService == null) {
10271                        return;
10272                    }
10273
10274                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10275                    clearDirectory(conn.mContainerService,
10276                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10277                    if (allData) {
10278                        clearDirectory(conn.mContainerService,
10279                                userEnv.buildExternalStorageAppDataDirs(packageName));
10280                        clearDirectory(conn.mContainerService,
10281                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10282                    }
10283                }
10284            } finally {
10285                mContext.unbindService(conn);
10286            }
10287        }
10288    }
10289
10290    @Override
10291    public void clearApplicationUserData(final String packageName,
10292            final IPackageDataObserver observer, final int userId) {
10293        mContext.enforceCallingOrSelfPermission(
10294                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10295        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10296        // Queue up an async operation since the package deletion may take a little while.
10297        mHandler.post(new Runnable() {
10298            public void run() {
10299                mHandler.removeCallbacks(this);
10300                final boolean succeeded;
10301                synchronized (mInstallLock) {
10302                    succeeded = clearApplicationUserDataLI(packageName, userId);
10303                }
10304                clearExternalStorageDataSync(packageName, userId, true);
10305                if (succeeded) {
10306                    // invoke DeviceStorageMonitor's update method to clear any notifications
10307                    DeviceStorageMonitorInternal
10308                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10309                    if (dsm != null) {
10310                        dsm.checkMemory();
10311                    }
10312                }
10313                if(observer != null) {
10314                    try {
10315                        observer.onRemoveCompleted(packageName, succeeded);
10316                    } catch (RemoteException e) {
10317                        Log.i(TAG, "Observer no longer exists.");
10318                    }
10319                } //end if observer
10320            } //end run
10321        });
10322    }
10323
10324    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10325        if (packageName == null) {
10326            Slog.w(TAG, "Attempt to delete null packageName.");
10327            return false;
10328        }
10329        PackageParser.Package p;
10330        boolean dataOnly = false;
10331        final int appId;
10332        synchronized (mPackages) {
10333            p = mPackages.get(packageName);
10334            if (p == null) {
10335                dataOnly = true;
10336                PackageSetting ps = mSettings.mPackages.get(packageName);
10337                if ((ps == null) || (ps.pkg == null)) {
10338                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10339                    return false;
10340                }
10341                p = ps.pkg;
10342            }
10343            if (!dataOnly) {
10344                // need to check this only for fully installed applications
10345                if (p == null) {
10346                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10347                    return false;
10348                }
10349                final ApplicationInfo applicationInfo = p.applicationInfo;
10350                if (applicationInfo == null) {
10351                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10352                    return false;
10353                }
10354            }
10355            if (p != null && p.applicationInfo != null) {
10356                appId = p.applicationInfo.uid;
10357            } else {
10358                appId = -1;
10359            }
10360        }
10361        int retCode = mInstaller.clearUserData(packageName, userId);
10362        if (retCode < 0) {
10363            Slog.w(TAG, "Couldn't remove cache files for package: "
10364                    + packageName);
10365            return false;
10366        }
10367        removeKeystoreDataIfNeeded(userId, appId);
10368        return true;
10369    }
10370
10371    /**
10372     * Remove entries from the keystore daemon. Will only remove it if the
10373     * {@code appId} is valid.
10374     */
10375    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10376        if (appId < 0) {
10377            return;
10378        }
10379
10380        final KeyStore keyStore = KeyStore.getInstance();
10381        if (keyStore != null) {
10382            if (userId == UserHandle.USER_ALL) {
10383                for (final int individual : sUserManager.getUserIds()) {
10384                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10385                }
10386            } else {
10387                keyStore.clearUid(UserHandle.getUid(userId, appId));
10388            }
10389        } else {
10390            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10391        }
10392    }
10393
10394    public void deleteApplicationCacheFiles(final String packageName,
10395            final IPackageDataObserver observer) {
10396        mContext.enforceCallingOrSelfPermission(
10397                android.Manifest.permission.DELETE_CACHE_FILES, null);
10398        // Queue up an async operation since the package deletion may take a little while.
10399        final int userId = UserHandle.getCallingUserId();
10400        mHandler.post(new Runnable() {
10401            public void run() {
10402                mHandler.removeCallbacks(this);
10403                final boolean succeded;
10404                synchronized (mInstallLock) {
10405                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10406                }
10407                clearExternalStorageDataSync(packageName, userId, false);
10408                if(observer != null) {
10409                    try {
10410                        observer.onRemoveCompleted(packageName, succeded);
10411                    } catch (RemoteException e) {
10412                        Log.i(TAG, "Observer no longer exists.");
10413                    }
10414                } //end if observer
10415            } //end run
10416        });
10417    }
10418
10419    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10420        if (packageName == null) {
10421            Slog.w(TAG, "Attempt to delete null packageName.");
10422            return false;
10423        }
10424        PackageParser.Package p;
10425        synchronized (mPackages) {
10426            p = mPackages.get(packageName);
10427        }
10428        if (p == null) {
10429            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10430            return false;
10431        }
10432        final ApplicationInfo applicationInfo = p.applicationInfo;
10433        if (applicationInfo == null) {
10434            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10435            return false;
10436        }
10437        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10438        if (retCode < 0) {
10439            Slog.w(TAG, "Couldn't remove cache files for package: "
10440                       + packageName + " u" + userId);
10441            return false;
10442        }
10443        return true;
10444    }
10445
10446    public void getPackageSizeInfo(final String packageName, int userHandle,
10447            final IPackageStatsObserver observer) {
10448        mContext.enforceCallingOrSelfPermission(
10449                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10450        if (packageName == null) {
10451            throw new IllegalArgumentException("Attempt to get size of null packageName");
10452        }
10453
10454        PackageStats stats = new PackageStats(packageName, userHandle);
10455
10456        /*
10457         * Queue up an async operation since the package measurement may take a
10458         * little while.
10459         */
10460        Message msg = mHandler.obtainMessage(INIT_COPY);
10461        msg.obj = new MeasureParams(stats, observer);
10462        mHandler.sendMessage(msg);
10463    }
10464
10465    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10466            PackageStats pStats) {
10467        if (packageName == null) {
10468            Slog.w(TAG, "Attempt to get size of null packageName.");
10469            return false;
10470        }
10471        PackageParser.Package p;
10472        boolean dataOnly = false;
10473        String libDirPath = null;
10474        String asecPath = null;
10475        synchronized (mPackages) {
10476            p = mPackages.get(packageName);
10477            PackageSetting ps = mSettings.mPackages.get(packageName);
10478            if(p == null) {
10479                dataOnly = true;
10480                if((ps == null) || (ps.pkg == null)) {
10481                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10482                    return false;
10483                }
10484                p = ps.pkg;
10485            }
10486            if (ps != null) {
10487                libDirPath = ps.nativeLibraryPathString;
10488            }
10489            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10490                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10491                if (secureContainerId != null) {
10492                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10493                }
10494            }
10495        }
10496        String publicSrcDir = null;
10497        if(!dataOnly) {
10498            final ApplicationInfo applicationInfo = p.applicationInfo;
10499            if (applicationInfo == null) {
10500                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10501                return false;
10502            }
10503            if (isForwardLocked(p)) {
10504                publicSrcDir = applicationInfo.publicSourceDir;
10505            }
10506        }
10507        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10508                publicSrcDir, asecPath, pStats);
10509        if (res < 0) {
10510            return false;
10511        }
10512
10513        // Fix-up for forward-locked applications in ASEC containers.
10514        if (!isExternal(p)) {
10515            pStats.codeSize += pStats.externalCodeSize;
10516            pStats.externalCodeSize = 0L;
10517        }
10518
10519        return true;
10520    }
10521
10522
10523    public void addPackageToPreferred(String packageName) {
10524        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10525    }
10526
10527    public void removePackageFromPreferred(String packageName) {
10528        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10529    }
10530
10531    public List<PackageInfo> getPreferredPackages(int flags) {
10532        return new ArrayList<PackageInfo>();
10533    }
10534
10535    private int getUidTargetSdkVersionLockedLPr(int uid) {
10536        Object obj = mSettings.getUserIdLPr(uid);
10537        if (obj instanceof SharedUserSetting) {
10538            final SharedUserSetting sus = (SharedUserSetting) obj;
10539            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10540            final Iterator<PackageSetting> it = sus.packages.iterator();
10541            while (it.hasNext()) {
10542                final PackageSetting ps = it.next();
10543                if (ps.pkg != null) {
10544                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10545                    if (v < vers) vers = v;
10546                }
10547            }
10548            return vers;
10549        } else if (obj instanceof PackageSetting) {
10550            final PackageSetting ps = (PackageSetting) obj;
10551            if (ps.pkg != null) {
10552                return ps.pkg.applicationInfo.targetSdkVersion;
10553            }
10554        }
10555        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10556    }
10557
10558    public void addPreferredActivity(IntentFilter filter, int match,
10559            ComponentName[] set, ComponentName activity, int userId) {
10560        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10561    }
10562
10563    private void addPreferredActivityInternal(IntentFilter filter, int match,
10564            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10565        // writer
10566        int callingUid = Binder.getCallingUid();
10567        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10568        if (filter.countActions() == 0) {
10569            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10570            return;
10571        }
10572        synchronized (mPackages) {
10573            if (mContext.checkCallingOrSelfPermission(
10574                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10575                    != PackageManager.PERMISSION_GRANTED) {
10576                if (getUidTargetSdkVersionLockedLPr(callingUid)
10577                        < Build.VERSION_CODES.FROYO) {
10578                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10579                            + callingUid);
10580                    return;
10581                }
10582                mContext.enforceCallingOrSelfPermission(
10583                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10584            }
10585
10586            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10587            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10588            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10589                    new PreferredActivity(filter, match, set, activity, always));
10590            mSettings.writePackageRestrictionsLPr(userId);
10591        }
10592    }
10593
10594    public void replacePreferredActivity(IntentFilter filter, int match,
10595            ComponentName[] set, ComponentName activity) {
10596        if (filter.countActions() != 1) {
10597            throw new IllegalArgumentException(
10598                    "replacePreferredActivity expects filter to have only 1 action.");
10599        }
10600        if (filter.countDataAuthorities() != 0
10601                || filter.countDataPaths() != 0
10602                || filter.countDataSchemes() > 1
10603                || filter.countDataTypes() != 0) {
10604            throw new IllegalArgumentException(
10605                    "replacePreferredActivity expects filter to have no data authorities, " +
10606                    "paths, or types; and at most one scheme.");
10607        }
10608        synchronized (mPackages) {
10609            if (mContext.checkCallingOrSelfPermission(
10610                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10611                    != PackageManager.PERMISSION_GRANTED) {
10612                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10613                        < Build.VERSION_CODES.FROYO) {
10614                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10615                            + Binder.getCallingUid());
10616                    return;
10617                }
10618                mContext.enforceCallingOrSelfPermission(
10619                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10620            }
10621
10622            final int callingUserId = UserHandle.getCallingUserId();
10623            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10624            if (pir != null) {
10625                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10626                if (filter.countDataSchemes() == 1) {
10627                    Uri.Builder builder = new Uri.Builder();
10628                    builder.scheme(filter.getDataScheme(0));
10629                    intent.setData(builder.build());
10630                }
10631                List<PreferredActivity> matches = pir.queryIntent(
10632                        intent, null, true, callingUserId);
10633                if (DEBUG_PREFERRED) {
10634                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10635                }
10636                for (int i = 0; i < matches.size(); i++) {
10637                    PreferredActivity pa = matches.get(i);
10638                    if (DEBUG_PREFERRED) {
10639                        Slog.i(TAG, "Removing preferred activity "
10640                                + pa.mPref.mComponent + ":");
10641                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10642                    }
10643                    pir.removeFilter(pa);
10644                }
10645            }
10646            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10647        }
10648    }
10649
10650    public void clearPackagePreferredActivities(String packageName) {
10651        final int uid = Binder.getCallingUid();
10652        // writer
10653        synchronized (mPackages) {
10654            PackageParser.Package pkg = mPackages.get(packageName);
10655            if (pkg == null || pkg.applicationInfo.uid != uid) {
10656                if (mContext.checkCallingOrSelfPermission(
10657                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10658                        != PackageManager.PERMISSION_GRANTED) {
10659                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10660                            < Build.VERSION_CODES.FROYO) {
10661                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10662                                + Binder.getCallingUid());
10663                        return;
10664                    }
10665                    mContext.enforceCallingOrSelfPermission(
10666                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10667                }
10668            }
10669
10670            int user = UserHandle.getCallingUserId();
10671            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10672                mSettings.writePackageRestrictionsLPr(user);
10673                scheduleWriteSettingsLocked();
10674            }
10675        }
10676    }
10677
10678    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10679    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10680        ArrayList<PreferredActivity> removed = null;
10681        boolean changed = false;
10682        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10683            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10684            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10685            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10686                continue;
10687            }
10688            Iterator<PreferredActivity> it = pir.filterIterator();
10689            while (it.hasNext()) {
10690                PreferredActivity pa = it.next();
10691                // Mark entry for removal only if it matches the package name
10692                // and the entry is of type "always".
10693                if (packageName == null ||
10694                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10695                                && pa.mPref.mAlways)) {
10696                    if (removed == null) {
10697                        removed = new ArrayList<PreferredActivity>();
10698                    }
10699                    removed.add(pa);
10700                }
10701            }
10702            if (removed != null) {
10703                for (int j=0; j<removed.size(); j++) {
10704                    PreferredActivity pa = removed.get(j);
10705                    pir.removeFilter(pa);
10706                }
10707                changed = true;
10708            }
10709        }
10710        return changed;
10711    }
10712
10713    public void resetPreferredActivities(int userId) {
10714        mContext.enforceCallingOrSelfPermission(
10715                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10716        // writer
10717        synchronized (mPackages) {
10718            int user = UserHandle.getCallingUserId();
10719            clearPackagePreferredActivitiesLPw(null, user);
10720            mSettings.readDefaultPreferredAppsLPw(this, user);
10721            mSettings.writePackageRestrictionsLPr(user);
10722            scheduleWriteSettingsLocked();
10723        }
10724    }
10725
10726    public int getPreferredActivities(List<IntentFilter> outFilters,
10727            List<ComponentName> outActivities, String packageName) {
10728
10729        int num = 0;
10730        final int userId = UserHandle.getCallingUserId();
10731        // reader
10732        synchronized (mPackages) {
10733            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10734            if (pir != null) {
10735                final Iterator<PreferredActivity> it = pir.filterIterator();
10736                while (it.hasNext()) {
10737                    final PreferredActivity pa = it.next();
10738                    if (packageName == null
10739                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10740                                    && pa.mPref.mAlways)) {
10741                        if (outFilters != null) {
10742                            outFilters.add(new IntentFilter(pa));
10743                        }
10744                        if (outActivities != null) {
10745                            outActivities.add(pa.mPref.mComponent);
10746                        }
10747                    }
10748                }
10749            }
10750        }
10751
10752        return num;
10753    }
10754
10755    @Override
10756    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
10757            int userId) {
10758        int callingUid = Binder.getCallingUid();
10759        if (callingUid != Process.SYSTEM_UID) {
10760            throw new SecurityException(
10761                    "addPersistentPreferredActivity can only be run by the system");
10762        }
10763        if (filter.countActions() == 0) {
10764            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10765            return;
10766        }
10767        synchronized (mPackages) {
10768            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
10769                    " :");
10770            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10771            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
10772                    new PersistentPreferredActivity(filter, activity));
10773            mSettings.writePackageRestrictionsLPr(userId);
10774        }
10775    }
10776
10777    @Override
10778    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
10779        int callingUid = Binder.getCallingUid();
10780        if (callingUid != Process.SYSTEM_UID) {
10781            throw new SecurityException(
10782                    "clearPackagePersistentPreferredActivities can only be run by the system");
10783        }
10784        ArrayList<PersistentPreferredActivity> removed = null;
10785        boolean changed = false;
10786        synchronized (mPackages) {
10787            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
10788                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
10789                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
10790                        .valueAt(i);
10791                if (userId != thisUserId) {
10792                    continue;
10793                }
10794                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
10795                while (it.hasNext()) {
10796                    PersistentPreferredActivity ppa = it.next();
10797                    // Mark entry for removal only if it matches the package name.
10798                    if (ppa.mComponent.getPackageName().equals(packageName)) {
10799                        if (removed == null) {
10800                            removed = new ArrayList<PersistentPreferredActivity>();
10801                        }
10802                        removed.add(ppa);
10803                    }
10804                }
10805                if (removed != null) {
10806                    for (int j=0; j<removed.size(); j++) {
10807                        PersistentPreferredActivity ppa = removed.get(j);
10808                        ppir.removeFilter(ppa);
10809                    }
10810                    changed = true;
10811                }
10812            }
10813
10814            if (changed) {
10815                mSettings.writePackageRestrictionsLPr(userId);
10816            }
10817        }
10818    }
10819
10820    @Override
10821    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10822        Intent intent = new Intent(Intent.ACTION_MAIN);
10823        intent.addCategory(Intent.CATEGORY_HOME);
10824
10825        final int callingUserId = UserHandle.getCallingUserId();
10826        List<ResolveInfo> list = queryIntentActivities(intent, null,
10827                PackageManager.GET_META_DATA, callingUserId);
10828        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10829                true, false, false, callingUserId);
10830
10831        allHomeCandidates.clear();
10832        if (list != null) {
10833            for (ResolveInfo ri : list) {
10834                allHomeCandidates.add(ri);
10835            }
10836        }
10837        return (preferred == null || preferred.activityInfo == null)
10838                ? null
10839                : new ComponentName(preferred.activityInfo.packageName,
10840                        preferred.activityInfo.name);
10841    }
10842
10843    @Override
10844    public void setApplicationEnabledSetting(String appPackageName,
10845            int newState, int flags, int userId, String callingPackage) {
10846        if (!sUserManager.exists(userId)) return;
10847        if (callingPackage == null) {
10848            callingPackage = Integer.toString(Binder.getCallingUid());
10849        }
10850        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10851    }
10852
10853    @Override
10854    public void setComponentEnabledSetting(ComponentName componentName,
10855            int newState, int flags, int userId) {
10856        if (!sUserManager.exists(userId)) return;
10857        setEnabledSetting(componentName.getPackageName(),
10858                componentName.getClassName(), newState, flags, userId, null);
10859    }
10860
10861    private void setEnabledSetting(final String packageName, String className, int newState,
10862            final int flags, int userId, String callingPackage) {
10863        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10864              || newState == COMPONENT_ENABLED_STATE_ENABLED
10865              || newState == COMPONENT_ENABLED_STATE_DISABLED
10866              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10867              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10868            throw new IllegalArgumentException("Invalid new component state: "
10869                    + newState);
10870        }
10871        PackageSetting pkgSetting;
10872        final int uid = Binder.getCallingUid();
10873        final int permission = mContext.checkCallingOrSelfPermission(
10874                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10875        enforceCrossUserPermission(uid, userId, false, "set enabled");
10876        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10877        boolean sendNow = false;
10878        boolean isApp = (className == null);
10879        String componentName = isApp ? packageName : className;
10880        int packageUid = -1;
10881        ArrayList<String> components;
10882
10883        // writer
10884        synchronized (mPackages) {
10885            pkgSetting = mSettings.mPackages.get(packageName);
10886            if (pkgSetting == null) {
10887                if (className == null) {
10888                    throw new IllegalArgumentException(
10889                            "Unknown package: " + packageName);
10890                }
10891                throw new IllegalArgumentException(
10892                        "Unknown component: " + packageName
10893                        + "/" + className);
10894            }
10895            // Allow root and verify that userId is not being specified by a different user
10896            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10897                throw new SecurityException(
10898                        "Permission Denial: attempt to change component state from pid="
10899                        + Binder.getCallingPid()
10900                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10901            }
10902            if (className == null) {
10903                // We're dealing with an application/package level state change
10904                if (pkgSetting.getEnabled(userId) == newState) {
10905                    // Nothing to do
10906                    return;
10907                }
10908                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10909                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10910                    // Don't care about who enables an app.
10911                    callingPackage = null;
10912                }
10913                pkgSetting.setEnabled(newState, userId, callingPackage);
10914                // pkgSetting.pkg.mSetEnabled = newState;
10915            } else {
10916                // We're dealing with a component level state change
10917                // First, verify that this is a valid class name.
10918                PackageParser.Package pkg = pkgSetting.pkg;
10919                if (pkg == null || !pkg.hasComponentClassName(className)) {
10920                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10921                        throw new IllegalArgumentException("Component class " + className
10922                                + " does not exist in " + packageName);
10923                    } else {
10924                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10925                                + className + " does not exist in " + packageName);
10926                    }
10927                }
10928                switch (newState) {
10929                case COMPONENT_ENABLED_STATE_ENABLED:
10930                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10931                        return;
10932                    }
10933                    break;
10934                case COMPONENT_ENABLED_STATE_DISABLED:
10935                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10936                        return;
10937                    }
10938                    break;
10939                case COMPONENT_ENABLED_STATE_DEFAULT:
10940                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10941                        return;
10942                    }
10943                    break;
10944                default:
10945                    Slog.e(TAG, "Invalid new component state: " + newState);
10946                    return;
10947                }
10948            }
10949            mSettings.writePackageRestrictionsLPr(userId);
10950            components = mPendingBroadcasts.get(userId, packageName);
10951            final boolean newPackage = components == null;
10952            if (newPackage) {
10953                components = new ArrayList<String>();
10954            }
10955            if (!components.contains(componentName)) {
10956                components.add(componentName);
10957            }
10958            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10959                sendNow = true;
10960                // Purge entry from pending broadcast list if another one exists already
10961                // since we are sending one right away.
10962                mPendingBroadcasts.remove(userId, packageName);
10963            } else {
10964                if (newPackage) {
10965                    mPendingBroadcasts.put(userId, packageName, components);
10966                }
10967                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10968                    // Schedule a message
10969                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10970                }
10971            }
10972        }
10973
10974        long callingId = Binder.clearCallingIdentity();
10975        try {
10976            if (sendNow) {
10977                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10978                sendPackageChangedBroadcast(packageName,
10979                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10980            }
10981        } finally {
10982            Binder.restoreCallingIdentity(callingId);
10983        }
10984    }
10985
10986    private void sendPackageChangedBroadcast(String packageName,
10987            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10988        if (DEBUG_INSTALL)
10989            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10990                    + componentNames);
10991        Bundle extras = new Bundle(4);
10992        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10993        String nameList[] = new String[componentNames.size()];
10994        componentNames.toArray(nameList);
10995        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10996        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10997        extras.putInt(Intent.EXTRA_UID, packageUid);
10998        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10999                new int[] {UserHandle.getUserId(packageUid)});
11000    }
11001
11002    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11003        if (!sUserManager.exists(userId)) return;
11004        final int uid = Binder.getCallingUid();
11005        final int permission = mContext.checkCallingOrSelfPermission(
11006                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11007        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11008        enforceCrossUserPermission(uid, userId, true, "stop package");
11009        // writer
11010        synchronized (mPackages) {
11011            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11012                    uid, userId)) {
11013                scheduleWritePackageRestrictionsLocked(userId);
11014            }
11015        }
11016    }
11017
11018    public String getInstallerPackageName(String packageName) {
11019        // reader
11020        synchronized (mPackages) {
11021            return mSettings.getInstallerPackageNameLPr(packageName);
11022        }
11023    }
11024
11025    @Override
11026    public int getApplicationEnabledSetting(String packageName, int userId) {
11027        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11028        int uid = Binder.getCallingUid();
11029        enforceCrossUserPermission(uid, userId, false, "get enabled");
11030        // reader
11031        synchronized (mPackages) {
11032            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11033        }
11034    }
11035
11036    @Override
11037    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11038        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11039        int uid = Binder.getCallingUid();
11040        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11041        // reader
11042        synchronized (mPackages) {
11043            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11044        }
11045    }
11046
11047    public void enterSafeMode() {
11048        enforceSystemOrRoot("Only the system can request entering safe mode");
11049
11050        if (!mSystemReady) {
11051            mSafeMode = true;
11052        }
11053    }
11054
11055    public void systemReady() {
11056        mSystemReady = true;
11057
11058        // Read the compatibilty setting when the system is ready.
11059        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11060                mContext.getContentResolver(),
11061                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11062        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11063        if (DEBUG_SETTINGS) {
11064            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11065        }
11066
11067        synchronized (mPackages) {
11068            // Verify that all of the preferred activity components actually
11069            // exist.  It is possible for applications to be updated and at
11070            // that point remove a previously declared activity component that
11071            // had been set as a preferred activity.  We try to clean this up
11072            // the next time we encounter that preferred activity, but it is
11073            // possible for the user flow to never be able to return to that
11074            // situation so here we do a sanity check to make sure we haven't
11075            // left any junk around.
11076            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11077            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11078                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11079                removed.clear();
11080                for (PreferredActivity pa : pir.filterSet()) {
11081                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11082                        removed.add(pa);
11083                    }
11084                }
11085                if (removed.size() > 0) {
11086                    for (int j=0; j<removed.size(); j++) {
11087                        PreferredActivity pa = removed.get(i);
11088                        Slog.w(TAG, "Removing dangling preferred activity: "
11089                                + pa.mPref.mComponent);
11090                        pir.removeFilter(pa);
11091                    }
11092                    mSettings.writePackageRestrictionsLPr(
11093                            mSettings.mPreferredActivities.keyAt(i));
11094                }
11095            }
11096        }
11097        sUserManager.systemReady();
11098    }
11099
11100    public boolean isSafeMode() {
11101        return mSafeMode;
11102    }
11103
11104    public boolean hasSystemUidErrors() {
11105        return mHasSystemUidErrors;
11106    }
11107
11108    static String arrayToString(int[] array) {
11109        StringBuffer buf = new StringBuffer(128);
11110        buf.append('[');
11111        if (array != null) {
11112            for (int i=0; i<array.length; i++) {
11113                if (i > 0) buf.append(", ");
11114                buf.append(array[i]);
11115            }
11116        }
11117        buf.append(']');
11118        return buf.toString();
11119    }
11120
11121    static class DumpState {
11122        public static final int DUMP_LIBS = 1 << 0;
11123
11124        public static final int DUMP_FEATURES = 1 << 1;
11125
11126        public static final int DUMP_RESOLVERS = 1 << 2;
11127
11128        public static final int DUMP_PERMISSIONS = 1 << 3;
11129
11130        public static final int DUMP_PACKAGES = 1 << 4;
11131
11132        public static final int DUMP_SHARED_USERS = 1 << 5;
11133
11134        public static final int DUMP_MESSAGES = 1 << 6;
11135
11136        public static final int DUMP_PROVIDERS = 1 << 7;
11137
11138        public static final int DUMP_VERIFIERS = 1 << 8;
11139
11140        public static final int DUMP_PREFERRED = 1 << 9;
11141
11142        public static final int DUMP_PREFERRED_XML = 1 << 10;
11143
11144        public static final int DUMP_KEYSETS = 1 << 11;
11145
11146        public static final int DUMP_VERSION = 1 << 12;
11147
11148        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11149
11150        private int mTypes;
11151
11152        private int mOptions;
11153
11154        private boolean mTitlePrinted;
11155
11156        private SharedUserSetting mSharedUser;
11157
11158        public boolean isDumping(int type) {
11159            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11160                return true;
11161            }
11162
11163            return (mTypes & type) != 0;
11164        }
11165
11166        public void setDump(int type) {
11167            mTypes |= type;
11168        }
11169
11170        public boolean isOptionEnabled(int option) {
11171            return (mOptions & option) != 0;
11172        }
11173
11174        public void setOptionEnabled(int option) {
11175            mOptions |= option;
11176        }
11177
11178        public boolean onTitlePrinted() {
11179            final boolean printed = mTitlePrinted;
11180            mTitlePrinted = true;
11181            return printed;
11182        }
11183
11184        public boolean getTitlePrinted() {
11185            return mTitlePrinted;
11186        }
11187
11188        public void setTitlePrinted(boolean enabled) {
11189            mTitlePrinted = enabled;
11190        }
11191
11192        public SharedUserSetting getSharedUser() {
11193            return mSharedUser;
11194        }
11195
11196        public void setSharedUser(SharedUserSetting user) {
11197            mSharedUser = user;
11198        }
11199    }
11200
11201    @Override
11202    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11203        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11204                != PackageManager.PERMISSION_GRANTED) {
11205            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11206                    + Binder.getCallingPid()
11207                    + ", uid=" + Binder.getCallingUid()
11208                    + " without permission "
11209                    + android.Manifest.permission.DUMP);
11210            return;
11211        }
11212
11213        DumpState dumpState = new DumpState();
11214        boolean fullPreferred = false;
11215        boolean checkin = false;
11216
11217        String packageName = null;
11218
11219        int opti = 0;
11220        while (opti < args.length) {
11221            String opt = args[opti];
11222            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11223                break;
11224            }
11225            opti++;
11226            if ("-a".equals(opt)) {
11227                // Right now we only know how to print all.
11228            } else if ("-h".equals(opt)) {
11229                pw.println("Package manager dump options:");
11230                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11231                pw.println("    --checkin: dump for a checkin");
11232                pw.println("    -f: print details of intent filters");
11233                pw.println("    -h: print this help");
11234                pw.println("  cmd may be one of:");
11235                pw.println("    l[ibraries]: list known shared libraries");
11236                pw.println("    f[ibraries]: list device features");
11237                pw.println("    r[esolvers]: dump intent resolvers");
11238                pw.println("    perm[issions]: dump permissions");
11239                pw.println("    pref[erred]: print preferred package settings");
11240                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11241                pw.println("    prov[iders]: dump content providers");
11242                pw.println("    p[ackages]: dump installed packages");
11243                pw.println("    s[hared-users]: dump shared user IDs");
11244                pw.println("    m[essages]: print collected runtime messages");
11245                pw.println("    v[erifiers]: print package verifier info");
11246                pw.println("    version: print database version info");
11247                pw.println("    <package.name>: info about given package");
11248                pw.println("    k[eysets]: print known keysets");
11249                return;
11250            } else if ("--checkin".equals(opt)) {
11251                checkin = true;
11252            } else if ("-f".equals(opt)) {
11253                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11254            } else {
11255                pw.println("Unknown argument: " + opt + "; use -h for help");
11256            }
11257        }
11258
11259        // Is the caller requesting to dump a particular piece of data?
11260        if (opti < args.length) {
11261            String cmd = args[opti];
11262            opti++;
11263            // Is this a package name?
11264            if ("android".equals(cmd) || cmd.contains(".")) {
11265                packageName = cmd;
11266                // When dumping a single package, we always dump all of its
11267                // filter information since the amount of data will be reasonable.
11268                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11269            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11270                dumpState.setDump(DumpState.DUMP_LIBS);
11271            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11272                dumpState.setDump(DumpState.DUMP_FEATURES);
11273            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11274                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11275            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11276                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11277            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11278                dumpState.setDump(DumpState.DUMP_PREFERRED);
11279            } else if ("preferred-xml".equals(cmd)) {
11280                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11281                if (opti < args.length && "--full".equals(args[opti])) {
11282                    fullPreferred = true;
11283                    opti++;
11284                }
11285            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11286                dumpState.setDump(DumpState.DUMP_PACKAGES);
11287            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11288                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11289            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11290                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11291            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11292                dumpState.setDump(DumpState.DUMP_MESSAGES);
11293            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11294                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11295            } else if ("version".equals(cmd)) {
11296                dumpState.setDump(DumpState.DUMP_VERSION);
11297            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11298                dumpState.setDump(DumpState.DUMP_KEYSETS);
11299            }
11300        }
11301
11302        if (checkin) {
11303            pw.println("vers,1");
11304        }
11305
11306        // reader
11307        synchronized (mPackages) {
11308            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11309                if (!checkin) {
11310                    if (dumpState.onTitlePrinted())
11311                        pw.println();
11312                    pw.println("Database versions:");
11313                    pw.print("  SDK Version:");
11314                    pw.print(" internal=");
11315                    pw.print(mSettings.mInternalSdkPlatform);
11316                    pw.print(" external=");
11317                    pw.println(mSettings.mExternalSdkPlatform);
11318                    pw.print("  DB Version:");
11319                    pw.print(" internal=");
11320                    pw.print(mSettings.mInternalDatabaseVersion);
11321                    pw.print(" external=");
11322                    pw.println(mSettings.mExternalDatabaseVersion);
11323                }
11324            }
11325
11326            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11327                if (!checkin) {
11328                    if (dumpState.onTitlePrinted())
11329                        pw.println();
11330                    pw.println("Verifiers:");
11331                    pw.print("  Required: ");
11332                    pw.print(mRequiredVerifierPackage);
11333                    pw.print(" (uid=");
11334                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11335                    pw.println(")");
11336                } else if (mRequiredVerifierPackage != null) {
11337                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11338                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11339                }
11340            }
11341
11342            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11343                boolean printedHeader = false;
11344                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11345                while (it.hasNext()) {
11346                    String name = it.next();
11347                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11348                    if (!checkin) {
11349                        if (!printedHeader) {
11350                            if (dumpState.onTitlePrinted())
11351                                pw.println();
11352                            pw.println("Libraries:");
11353                            printedHeader = true;
11354                        }
11355                        pw.print("  ");
11356                    } else {
11357                        pw.print("lib,");
11358                    }
11359                    pw.print(name);
11360                    if (!checkin) {
11361                        pw.print(" -> ");
11362                    }
11363                    if (ent.path != null) {
11364                        if (!checkin) {
11365                            pw.print("(jar) ");
11366                            pw.print(ent.path);
11367                        } else {
11368                            pw.print(",jar,");
11369                            pw.print(ent.path);
11370                        }
11371                    } else {
11372                        if (!checkin) {
11373                            pw.print("(apk) ");
11374                            pw.print(ent.apk);
11375                        } else {
11376                            pw.print(",apk,");
11377                            pw.print(ent.apk);
11378                        }
11379                    }
11380                    pw.println();
11381                }
11382            }
11383
11384            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11385                if (dumpState.onTitlePrinted())
11386                    pw.println();
11387                if (!checkin) {
11388                    pw.println("Features:");
11389                }
11390                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11391                while (it.hasNext()) {
11392                    String name = it.next();
11393                    if (!checkin) {
11394                        pw.print("  ");
11395                    } else {
11396                        pw.print("feat,");
11397                    }
11398                    pw.println(name);
11399                }
11400            }
11401
11402            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11403                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11404                        : "Activity Resolver Table:", "  ", packageName,
11405                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11406                    dumpState.setTitlePrinted(true);
11407                }
11408                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11409                        : "Receiver Resolver Table:", "  ", packageName,
11410                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11411                    dumpState.setTitlePrinted(true);
11412                }
11413                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11414                        : "Service Resolver Table:", "  ", packageName,
11415                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11416                    dumpState.setTitlePrinted(true);
11417                }
11418                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11419                        : "Provider Resolver Table:", "  ", packageName,
11420                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11421                    dumpState.setTitlePrinted(true);
11422                }
11423            }
11424
11425            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11426                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11427                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11428                    int user = mSettings.mPreferredActivities.keyAt(i);
11429                    if (pir.dump(pw,
11430                            dumpState.getTitlePrinted()
11431                                ? "\nPreferred Activities User " + user + ":"
11432                                : "Preferred Activities User " + user + ":", "  ",
11433                            packageName, true)) {
11434                        dumpState.setTitlePrinted(true);
11435                    }
11436                }
11437            }
11438
11439            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11440                pw.flush();
11441                FileOutputStream fout = new FileOutputStream(fd);
11442                BufferedOutputStream str = new BufferedOutputStream(fout);
11443                XmlSerializer serializer = new FastXmlSerializer();
11444                try {
11445                    serializer.setOutput(str, "utf-8");
11446                    serializer.startDocument(null, true);
11447                    serializer.setFeature(
11448                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11449                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11450                    serializer.endDocument();
11451                    serializer.flush();
11452                } catch (IllegalArgumentException e) {
11453                    pw.println("Failed writing: " + e);
11454                } catch (IllegalStateException e) {
11455                    pw.println("Failed writing: " + e);
11456                } catch (IOException e) {
11457                    pw.println("Failed writing: " + e);
11458                }
11459            }
11460
11461            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11462                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11463            }
11464
11465            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11466                boolean printedSomething = false;
11467                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11468                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11469                        continue;
11470                    }
11471                    if (!printedSomething) {
11472                        if (dumpState.onTitlePrinted())
11473                            pw.println();
11474                        pw.println("Registered ContentProviders:");
11475                        printedSomething = true;
11476                    }
11477                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11478                    pw.print("    "); pw.println(p.toString());
11479                }
11480                printedSomething = false;
11481                for (Map.Entry<String, PackageParser.Provider> entry :
11482                        mProvidersByAuthority.entrySet()) {
11483                    PackageParser.Provider p = entry.getValue();
11484                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11485                        continue;
11486                    }
11487                    if (!printedSomething) {
11488                        if (dumpState.onTitlePrinted())
11489                            pw.println();
11490                        pw.println("ContentProvider Authorities:");
11491                        printedSomething = true;
11492                    }
11493                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11494                    pw.print("    "); pw.println(p.toString());
11495                    if (p.info != null && p.info.applicationInfo != null) {
11496                        final String appInfo = p.info.applicationInfo.toString();
11497                        pw.print("      applicationInfo="); pw.println(appInfo);
11498                    }
11499                }
11500            }
11501
11502            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11503                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11504            }
11505
11506            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11507                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11508            }
11509
11510            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11511                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11512            }
11513
11514            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11515                if (dumpState.onTitlePrinted())
11516                    pw.println();
11517                mSettings.dumpReadMessagesLPr(pw, dumpState);
11518
11519                pw.println();
11520                pw.println("Package warning messages:");
11521                final File fname = getSettingsProblemFile();
11522                FileInputStream in = null;
11523                try {
11524                    in = new FileInputStream(fname);
11525                    final int avail = in.available();
11526                    final byte[] data = new byte[avail];
11527                    in.read(data);
11528                    pw.print(new String(data));
11529                } catch (FileNotFoundException e) {
11530                } catch (IOException e) {
11531                } finally {
11532                    if (in != null) {
11533                        try {
11534                            in.close();
11535                        } catch (IOException e) {
11536                        }
11537                    }
11538                }
11539            }
11540        }
11541    }
11542
11543    // ------- apps on sdcard specific code -------
11544    static final boolean DEBUG_SD_INSTALL = false;
11545
11546    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11547
11548    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11549
11550    private boolean mMediaMounted = false;
11551
11552    private String getEncryptKey() {
11553        try {
11554            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11555                    SD_ENCRYPTION_KEYSTORE_NAME);
11556            if (sdEncKey == null) {
11557                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11558                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11559                if (sdEncKey == null) {
11560                    Slog.e(TAG, "Failed to create encryption keys");
11561                    return null;
11562                }
11563            }
11564            return sdEncKey;
11565        } catch (NoSuchAlgorithmException nsae) {
11566            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11567            return null;
11568        } catch (IOException ioe) {
11569            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11570            return null;
11571        }
11572
11573    }
11574
11575    /* package */static String getTempContainerId() {
11576        int tmpIdx = 1;
11577        String list[] = PackageHelper.getSecureContainerList();
11578        if (list != null) {
11579            for (final String name : list) {
11580                // Ignore null and non-temporary container entries
11581                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11582                    continue;
11583                }
11584
11585                String subStr = name.substring(mTempContainerPrefix.length());
11586                try {
11587                    int cid = Integer.parseInt(subStr);
11588                    if (cid >= tmpIdx) {
11589                        tmpIdx = cid + 1;
11590                    }
11591                } catch (NumberFormatException e) {
11592                }
11593            }
11594        }
11595        return mTempContainerPrefix + tmpIdx;
11596    }
11597
11598    /*
11599     * Update media status on PackageManager.
11600     */
11601    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11602        int callingUid = Binder.getCallingUid();
11603        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11604            throw new SecurityException("Media status can only be updated by the system");
11605        }
11606        // reader; this apparently protects mMediaMounted, but should probably
11607        // be a different lock in that case.
11608        synchronized (mPackages) {
11609            Log.i(TAG, "Updating external media status from "
11610                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11611                    + (mediaStatus ? "mounted" : "unmounted"));
11612            if (DEBUG_SD_INSTALL)
11613                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11614                        + ", mMediaMounted=" + mMediaMounted);
11615            if (mediaStatus == mMediaMounted) {
11616                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11617                        : 0, -1);
11618                mHandler.sendMessage(msg);
11619                return;
11620            }
11621            mMediaMounted = mediaStatus;
11622        }
11623        // Queue up an async operation since the package installation may take a
11624        // little while.
11625        mHandler.post(new Runnable() {
11626            public void run() {
11627                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11628            }
11629        });
11630    }
11631
11632    /**
11633     * Called by MountService when the initial ASECs to scan are available.
11634     * Should block until all the ASEC containers are finished being scanned.
11635     */
11636    public void scanAvailableAsecs() {
11637        updateExternalMediaStatusInner(true, false, false);
11638        if (mShouldRestoreconData) {
11639            SELinuxMMAC.setRestoreconDone();
11640            mShouldRestoreconData = false;
11641        }
11642    }
11643
11644    /*
11645     * Collect information of applications on external media, map them against
11646     * existing containers and update information based on current mount status.
11647     * Please note that we always have to report status if reportStatus has been
11648     * set to true especially when unloading packages.
11649     */
11650    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11651            boolean externalStorage) {
11652        // Collection of uids
11653        int uidArr[] = null;
11654        // Collection of stale containers
11655        HashSet<String> removeCids = new HashSet<String>();
11656        // Collection of packages on external media with valid containers.
11657        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11658        // Get list of secure containers.
11659        final String list[] = PackageHelper.getSecureContainerList();
11660        if (list == null || list.length == 0) {
11661            Log.i(TAG, "No secure containers on sdcard");
11662        } else {
11663            // Process list of secure containers and categorize them
11664            // as active or stale based on their package internal state.
11665            int uidList[] = new int[list.length];
11666            int num = 0;
11667            // reader
11668            synchronized (mPackages) {
11669                for (String cid : list) {
11670                    if (DEBUG_SD_INSTALL)
11671                        Log.i(TAG, "Processing container " + cid);
11672                    String pkgName = getAsecPackageName(cid);
11673                    if (pkgName == null) {
11674                        if (DEBUG_SD_INSTALL)
11675                            Log.i(TAG, "Container : " + cid + " stale");
11676                        removeCids.add(cid);
11677                        continue;
11678                    }
11679                    if (DEBUG_SD_INSTALL)
11680                        Log.i(TAG, "Looking for pkg : " + pkgName);
11681
11682                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11683                    if (ps == null) {
11684                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11685                        removeCids.add(cid);
11686                        continue;
11687                    }
11688
11689                    /*
11690                     * Skip packages that are not external if we're unmounting
11691                     * external storage.
11692                     */
11693                    if (externalStorage && !isMounted && !isExternal(ps)) {
11694                        continue;
11695                    }
11696
11697                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
11698                    // The package status is changed only if the code path
11699                    // matches between settings and the container id.
11700                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11701                        if (DEBUG_SD_INSTALL) {
11702                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11703                                    + " at code path: " + ps.codePathString);
11704                        }
11705
11706                        // We do have a valid package installed on sdcard
11707                        processCids.put(args, ps.codePathString);
11708                        final int uid = ps.appId;
11709                        if (uid != -1) {
11710                            uidList[num++] = uid;
11711                        }
11712                    } else {
11713                        Log.i(TAG, "Deleting stale container for " + cid);
11714                        removeCids.add(cid);
11715                    }
11716                }
11717            }
11718
11719            if (num > 0) {
11720                // Sort uid list
11721                Arrays.sort(uidList, 0, num);
11722                // Throw away duplicates
11723                uidArr = new int[num];
11724                uidArr[0] = uidList[0];
11725                int di = 0;
11726                for (int i = 1; i < num; i++) {
11727                    if (uidList[i - 1] != uidList[i]) {
11728                        uidArr[di++] = uidList[i];
11729                    }
11730                }
11731            }
11732        }
11733        // Process packages with valid entries.
11734        if (isMounted) {
11735            if (DEBUG_SD_INSTALL)
11736                Log.i(TAG, "Loading packages");
11737            loadMediaPackages(processCids, uidArr, removeCids);
11738            startCleaningPackages();
11739        } else {
11740            if (DEBUG_SD_INSTALL)
11741                Log.i(TAG, "Unloading packages");
11742            unloadMediaPackages(processCids, uidArr, reportStatus);
11743        }
11744    }
11745
11746   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11747           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11748        int size = pkgList.size();
11749        if (size > 0) {
11750            // Send broadcasts here
11751            Bundle extras = new Bundle();
11752            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11753                    .toArray(new String[size]));
11754            if (uidArr != null) {
11755                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11756            }
11757            if (replacing) {
11758                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11759            }
11760            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11761                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11762            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11763        }
11764    }
11765
11766   /*
11767     * Look at potentially valid container ids from processCids If package
11768     * information doesn't match the one on record or package scanning fails,
11769     * the cid is added to list of removeCids. We currently don't delete stale
11770     * containers.
11771     */
11772   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11773            HashSet<String> removeCids) {
11774        ArrayList<String> pkgList = new ArrayList<String>();
11775        Set<AsecInstallArgs> keys = processCids.keySet();
11776        boolean doGc = false;
11777        for (AsecInstallArgs args : keys) {
11778            String codePath = processCids.get(args);
11779            if (DEBUG_SD_INSTALL)
11780                Log.i(TAG, "Loading container : " + args.cid);
11781            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11782            try {
11783                // Make sure there are no container errors first.
11784                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11785                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11786                            + " when installing from sdcard");
11787                    continue;
11788                }
11789                // Check code path here.
11790                if (codePath == null || !codePath.equals(args.getCodePath())) {
11791                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11792                            + " does not match one in settings " + codePath);
11793                    continue;
11794                }
11795                // Parse package
11796                int parseFlags = mDefParseFlags;
11797                if (args.isExternal()) {
11798                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11799                }
11800                if (args.isFwdLocked()) {
11801                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11802                }
11803
11804                doGc = true;
11805                synchronized (mInstallLock) {
11806                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11807                            0, 0, null);
11808                    // Scan the package
11809                    if (pkg != null) {
11810                        /*
11811                         * TODO why is the lock being held? doPostInstall is
11812                         * called in other places without the lock. This needs
11813                         * to be straightened out.
11814                         */
11815                        // writer
11816                        synchronized (mPackages) {
11817                            retCode = PackageManager.INSTALL_SUCCEEDED;
11818                            pkgList.add(pkg.packageName);
11819                            // Post process args
11820                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11821                                    pkg.applicationInfo.uid);
11822                        }
11823                    } else {
11824                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11825                    }
11826                }
11827
11828            } finally {
11829                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11830                    // Don't destroy container here. Wait till gc clears things
11831                    // up.
11832                    removeCids.add(args.cid);
11833                }
11834            }
11835        }
11836        // writer
11837        synchronized (mPackages) {
11838            // If the platform SDK has changed since the last time we booted,
11839            // we need to re-grant app permission to catch any new ones that
11840            // appear. This is really a hack, and means that apps can in some
11841            // cases get permissions that the user didn't initially explicitly
11842            // allow... it would be nice to have some better way to handle
11843            // this situation.
11844            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11845            if (regrantPermissions)
11846                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11847                        + mSdkVersion + "; regranting permissions for external storage");
11848            mSettings.mExternalSdkPlatform = mSdkVersion;
11849
11850            // Make sure group IDs have been assigned, and any permission
11851            // changes in other apps are accounted for
11852            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11853                    | (regrantPermissions
11854                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11855                            : 0));
11856
11857            mSettings.updateExternalDatabaseVersion();
11858
11859            // can downgrade to reader
11860            // Persist settings
11861            mSettings.writeLPr();
11862        }
11863        // Send a broadcast to let everyone know we are done processing
11864        if (pkgList.size() > 0) {
11865            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11866        }
11867        // Force gc to avoid any stale parser references that we might have.
11868        if (doGc) {
11869            Runtime.getRuntime().gc();
11870        }
11871        // List stale containers and destroy stale temporary containers.
11872        if (removeCids != null) {
11873            for (String cid : removeCids) {
11874                if (cid.startsWith(mTempContainerPrefix)) {
11875                    Log.i(TAG, "Destroying stale temporary container " + cid);
11876                    PackageHelper.destroySdDir(cid);
11877                } else {
11878                    Log.w(TAG, "Container " + cid + " is stale");
11879               }
11880           }
11881        }
11882    }
11883
11884   /*
11885     * Utility method to unload a list of specified containers
11886     */
11887    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11888        // Just unmount all valid containers.
11889        for (AsecInstallArgs arg : cidArgs) {
11890            synchronized (mInstallLock) {
11891                arg.doPostDeleteLI(false);
11892           }
11893       }
11894   }
11895
11896    /*
11897     * Unload packages mounted on external media. This involves deleting package
11898     * data from internal structures, sending broadcasts about diabled packages,
11899     * gc'ing to free up references, unmounting all secure containers
11900     * corresponding to packages on external media, and posting a
11901     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11902     * that we always have to post this message if status has been requested no
11903     * matter what.
11904     */
11905    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11906            final boolean reportStatus) {
11907        if (DEBUG_SD_INSTALL)
11908            Log.i(TAG, "unloading media packages");
11909        ArrayList<String> pkgList = new ArrayList<String>();
11910        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11911        final Set<AsecInstallArgs> keys = processCids.keySet();
11912        for (AsecInstallArgs args : keys) {
11913            String pkgName = args.getPackageName();
11914            if (DEBUG_SD_INSTALL)
11915                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11916            // Delete package internally
11917            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11918            synchronized (mInstallLock) {
11919                boolean res = deletePackageLI(pkgName, null, false, null, null,
11920                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11921                if (res) {
11922                    pkgList.add(pkgName);
11923                } else {
11924                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11925                    failedList.add(args);
11926                }
11927            }
11928        }
11929
11930        // reader
11931        synchronized (mPackages) {
11932            // We didn't update the settings after removing each package;
11933            // write them now for all packages.
11934            mSettings.writeLPr();
11935        }
11936
11937        // We have to absolutely send UPDATED_MEDIA_STATUS only
11938        // after confirming that all the receivers processed the ordered
11939        // broadcast when packages get disabled, force a gc to clean things up.
11940        // and unload all the containers.
11941        if (pkgList.size() > 0) {
11942            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11943                    new IIntentReceiver.Stub() {
11944                public void performReceive(Intent intent, int resultCode, String data,
11945                        Bundle extras, boolean ordered, boolean sticky,
11946                        int sendingUser) throws RemoteException {
11947                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11948                            reportStatus ? 1 : 0, 1, keys);
11949                    mHandler.sendMessage(msg);
11950                }
11951            });
11952        } else {
11953            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11954                    keys);
11955            mHandler.sendMessage(msg);
11956        }
11957    }
11958
11959    /** Binder call */
11960    @Override
11961    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11962            final int flags) {
11963        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11964        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11965        int returnCode = PackageManager.MOVE_SUCCEEDED;
11966        int currFlags = 0;
11967        int newFlags = 0;
11968        // reader
11969        synchronized (mPackages) {
11970            PackageParser.Package pkg = mPackages.get(packageName);
11971            if (pkg == null) {
11972                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11973            } else {
11974                // Disable moving fwd locked apps and system packages
11975                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11976                    Slog.w(TAG, "Cannot move system application");
11977                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11978                } else if (pkg.mOperationPending) {
11979                    Slog.w(TAG, "Attempt to move package which has pending operations");
11980                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11981                } else {
11982                    // Find install location first
11983                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11984                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11985                        Slog.w(TAG, "Ambigous flags specified for move location.");
11986                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11987                    } else {
11988                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11989                                : PackageManager.INSTALL_INTERNAL;
11990                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11991                                : PackageManager.INSTALL_INTERNAL;
11992
11993                        if (newFlags == currFlags) {
11994                            Slog.w(TAG, "No move required. Trying to move to same location");
11995                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11996                        } else {
11997                            if (isForwardLocked(pkg)) {
11998                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11999                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12000                            }
12001                        }
12002                    }
12003                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12004                        pkg.mOperationPending = true;
12005                    }
12006                }
12007            }
12008
12009            /*
12010             * TODO this next block probably shouldn't be inside the lock. We
12011             * can't guarantee these won't change after this is fired off
12012             * anyway.
12013             */
12014            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12015                processPendingMove(new MoveParams(null, observer, 0, packageName,
12016                        null, -1, user),
12017                        returnCode);
12018            } else {
12019                Message msg = mHandler.obtainMessage(INIT_COPY);
12020                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12021                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
12022                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12023                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
12024                msg.obj = mp;
12025                mHandler.sendMessage(msg);
12026            }
12027        }
12028    }
12029
12030    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12031        // Queue up an async operation since the package deletion may take a
12032        // little while.
12033        mHandler.post(new Runnable() {
12034            public void run() {
12035                // TODO fix this; this does nothing.
12036                mHandler.removeCallbacks(this);
12037                int returnCode = currentStatus;
12038                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12039                    int uidArr[] = null;
12040                    ArrayList<String> pkgList = null;
12041                    synchronized (mPackages) {
12042                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12043                        if (pkg == null) {
12044                            Slog.w(TAG, " Package " + mp.packageName
12045                                    + " doesn't exist. Aborting move");
12046                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12047                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12048                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12049                                    + mp.srcArgs.getCodePath() + " to "
12050                                    + pkg.applicationInfo.sourceDir
12051                                    + " Aborting move and returning error");
12052                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12053                        } else {
12054                            uidArr = new int[] {
12055                                pkg.applicationInfo.uid
12056                            };
12057                            pkgList = new ArrayList<String>();
12058                            pkgList.add(mp.packageName);
12059                        }
12060                    }
12061                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12062                        // Send resources unavailable broadcast
12063                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12064                        // Update package code and resource paths
12065                        synchronized (mInstallLock) {
12066                            synchronized (mPackages) {
12067                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12068                                // Recheck for package again.
12069                                if (pkg == null) {
12070                                    Slog.w(TAG, " Package " + mp.packageName
12071                                            + " doesn't exist. Aborting move");
12072                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12073                                } else if (!mp.srcArgs.getCodePath().equals(
12074                                        pkg.applicationInfo.sourceDir)) {
12075                                    Slog.w(TAG, "Package " + mp.packageName
12076                                            + " code path changed from " + mp.srcArgs.getCodePath()
12077                                            + " to " + pkg.applicationInfo.sourceDir
12078                                            + " Aborting move and returning error");
12079                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12080                                } else {
12081                                    final String oldCodePath = pkg.mPath;
12082                                    final String newCodePath = mp.targetArgs.getCodePath();
12083                                    final String newResPath = mp.targetArgs.getResourcePath();
12084                                    final String newNativePath = mp.targetArgs
12085                                            .getNativeLibraryPath();
12086
12087                                    final File newNativeDir = new File(newNativePath);
12088
12089                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12090                                        // NOTE: We do not report any errors from the APK scan and library
12091                                        // copy at this point.
12092                                        NativeLibraryHelper.ApkHandle handle =
12093                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12094                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12095                                                handle, Build.SUPPORTED_ABIS);
12096                                        if (abi >= 0) {
12097                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12098                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12099                                        }
12100                                        handle.close();
12101                                    }
12102                                    final int[] users = sUserManager.getUserIds();
12103                                    for (int user : users) {
12104                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12105                                                newNativePath, user) < 0) {
12106                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12107                                        }
12108                                    }
12109
12110                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12111                                        pkg.mPath = newCodePath;
12112                                        // Move dex files around
12113                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12114                                            // Moving of dex files failed. Set
12115                                            // error code and abort move.
12116                                            pkg.mPath = pkg.mScanPath;
12117                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12118                                        }
12119                                    }
12120
12121                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12122                                        pkg.mScanPath = newCodePath;
12123                                        pkg.applicationInfo.sourceDir = newCodePath;
12124                                        pkg.applicationInfo.publicSourceDir = newResPath;
12125                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12126                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12127                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12128                                        ps.codePathString = ps.codePath.getPath();
12129                                        ps.resourcePath = new File(
12130                                                pkg.applicationInfo.publicSourceDir);
12131                                        ps.resourcePathString = ps.resourcePath.getPath();
12132                                        ps.nativeLibraryPathString = newNativePath;
12133                                        // Set the application info flag
12134                                        // correctly.
12135                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12136                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12137                                        } else {
12138                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12139                                        }
12140                                        ps.setFlags(pkg.applicationInfo.flags);
12141                                        mAppDirs.remove(oldCodePath);
12142                                        mAppDirs.put(newCodePath, pkg);
12143                                        // Persist settings
12144                                        mSettings.writeLPr();
12145                                    }
12146                                }
12147                            }
12148                        }
12149                        // Send resources available broadcast
12150                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12151                    }
12152                }
12153                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12154                    // Clean up failed installation
12155                    if (mp.targetArgs != null) {
12156                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12157                                -1);
12158                    }
12159                } else {
12160                    // Force a gc to clear things up.
12161                    Runtime.getRuntime().gc();
12162                    // Delete older code
12163                    synchronized (mInstallLock) {
12164                        mp.srcArgs.doPostDeleteLI(true);
12165                    }
12166                }
12167
12168                // Allow more operations on this file if we didn't fail because
12169                // an operation was already pending for this package.
12170                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12171                    synchronized (mPackages) {
12172                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12173                        if (pkg != null) {
12174                            pkg.mOperationPending = false;
12175                       }
12176                   }
12177                }
12178
12179                IPackageMoveObserver observer = mp.observer;
12180                if (observer != null) {
12181                    try {
12182                        observer.packageMoved(mp.packageName, returnCode);
12183                    } catch (RemoteException e) {
12184                        Log.i(TAG, "Observer no longer exists.");
12185                    }
12186                }
12187            }
12188        });
12189    }
12190
12191    public boolean setInstallLocation(int loc) {
12192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12193                null);
12194        if (getInstallLocation() == loc) {
12195            return true;
12196        }
12197        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12198                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12199            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12200                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12201            return true;
12202        }
12203        return false;
12204   }
12205
12206    public int getInstallLocation() {
12207        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12208                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12209                PackageHelper.APP_INSTALL_AUTO);
12210    }
12211
12212    /** Called by UserManagerService */
12213    void cleanUpUserLILPw(int userHandle) {
12214        mDirtyUsers.remove(userHandle);
12215        mSettings.removeUserLPr(userHandle);
12216        mPendingBroadcasts.remove(userHandle);
12217        if (mInstaller != null) {
12218            // Technically, we shouldn't be doing this with the package lock
12219            // held.  However, this is very rare, and there is already so much
12220            // other disk I/O going on, that we'll let it slide for now.
12221            mInstaller.removeUserDataDirs(userHandle);
12222        }
12223    }
12224
12225    /** Called by UserManagerService */
12226    void createNewUserLILPw(int userHandle, File path) {
12227        if (mInstaller != null) {
12228            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12229        }
12230    }
12231
12232    @Override
12233    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12234        mContext.enforceCallingOrSelfPermission(
12235                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12236                "Only package verification agents can read the verifier device identity");
12237
12238        synchronized (mPackages) {
12239            return mSettings.getVerifierDeviceIdentityLPw();
12240        }
12241    }
12242
12243    @Override
12244    public void setPermissionEnforced(String permission, boolean enforced) {
12245        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12246        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12247            synchronized (mPackages) {
12248                if (mSettings.mReadExternalStorageEnforced == null
12249                        || mSettings.mReadExternalStorageEnforced != enforced) {
12250                    mSettings.mReadExternalStorageEnforced = enforced;
12251                    mSettings.writeLPr();
12252                }
12253            }
12254            // kill any non-foreground processes so we restart them and
12255            // grant/revoke the GID.
12256            final IActivityManager am = ActivityManagerNative.getDefault();
12257            if (am != null) {
12258                final long token = Binder.clearCallingIdentity();
12259                try {
12260                    am.killProcessesBelowForeground("setPermissionEnforcement");
12261                } catch (RemoteException e) {
12262                } finally {
12263                    Binder.restoreCallingIdentity(token);
12264                }
12265            }
12266        } else {
12267            throw new IllegalArgumentException("No selective enforcement for " + permission);
12268        }
12269    }
12270
12271    @Override
12272    @Deprecated
12273    public boolean isPermissionEnforced(String permission) {
12274        return true;
12275    }
12276
12277    @Override
12278    public boolean isStorageLow() {
12279        final long token = Binder.clearCallingIdentity();
12280        try {
12281            final DeviceStorageMonitorInternal
12282                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12283            if (dsm != null) {
12284                return dsm.isMemoryLow();
12285            } else {
12286                return false;
12287            }
12288        } finally {
12289            Binder.restoreCallingIdentity(token);
12290        }
12291    }
12292}
12293