PackageManagerService.java revision ab8a501f255b272af887acb0e66eb71cdf24c755
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 com.android.internal.util.ArrayUtils.appendInt;
27import static com.android.internal.util.ArrayUtils.removeInt;
28import static libcore.io.OsConstants.S_IRWXU;
29import static libcore.io.OsConstants.S_IRGRP;
30import static libcore.io.OsConstants.S_IXGRP;
31import static libcore.io.OsConstants.S_IROTH;
32import static libcore.io.OsConstants.S_IXOTH;
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.ServiceConnection;
64import android.content.IntentSender.SendIntentException;
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.PackageCleanItem;
78import android.content.pm.PackageInfo;
79import android.content.pm.PackageInfoLite;
80import android.content.pm.PackageManager;
81import android.content.pm.PackageParser;
82import android.content.pm.PackageUserState;
83import android.content.pm.PackageParser.ActivityIntentInfo;
84import android.content.pm.PackageStats;
85import android.content.pm.ParceledListSlice;
86import android.content.pm.PermissionGroupInfo;
87import android.content.pm.PermissionInfo;
88import android.content.pm.ProviderInfo;
89import android.content.pm.ResolveInfo;
90import android.content.pm.ServiceInfo;
91import android.content.pm.Signature;
92import android.content.pm.ManifestDigest;
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.FileObserver;
104import android.os.FileUtils;
105import android.os.Handler;
106import android.os.HandlerThread;
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.Environment.UserEnvironment;
120import android.os.UserManager;
121import android.security.KeyStore;
122import android.security.SystemKeyStore;
123import android.text.TextUtils;
124import android.util.DisplayMetrics;
125import android.util.EventLog;
126import android.util.Log;
127import android.util.LogPrinter;
128import android.util.PrintStreamPrinter;
129import android.util.Slog;
130import android.util.SparseArray;
131import android.util.Xml;
132import android.view.Display;
133
134import java.io.BufferedOutputStream;
135import java.io.File;
136import java.io.FileDescriptor;
137import java.io.FileInputStream;
138import java.io.FileNotFoundException;
139import java.io.FileOutputStream;
140import java.io.FileReader;
141import java.io.FilenameFilter;
142import java.io.IOException;
143import java.io.PrintWriter;
144import java.security.NoSuchAlgorithmException;
145import java.security.PublicKey;
146import java.security.cert.CertificateException;
147import java.text.SimpleDateFormat;
148import java.util.ArrayList;
149import java.util.Arrays;
150import java.util.Collection;
151import java.util.Collections;
152import java.util.Comparator;
153import java.util.Date;
154import java.util.HashMap;
155import java.util.HashSet;
156import java.util.Iterator;
157import java.util.List;
158import java.util.Map;
159import java.util.Set;
160
161import libcore.io.ErrnoException;
162import libcore.io.IoUtils;
163import libcore.io.Libcore;
164import libcore.io.StructStat;
165
166import com.android.internal.R;
167import com.android.server.storage.DeviceStorageMonitorInternal;
168
169/**
170 * Keep track of all those .apks everywhere.
171 *
172 * This is very central to the platform's security; please run the unit
173 * tests whenever making modifications here:
174 *
175mmm frameworks/base/tests/AndroidTests
176adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
177adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
178 *
179 * {@hide}
180 */
181public class PackageManagerService extends IPackageManager.Stub {
182    static final String TAG = "PackageManager";
183    static final boolean DEBUG_SETTINGS = false;
184    static final boolean DEBUG_PREFERRED = false;
185    static final boolean DEBUG_UPGRADE = false;
186    private static final boolean DEBUG_INSTALL = false;
187    private static final boolean DEBUG_REMOVE = false;
188    private static final boolean DEBUG_BROADCASTS = false;
189    private static final boolean DEBUG_SHOW_INFO = false;
190    private static final boolean DEBUG_PACKAGE_INFO = false;
191    private static final boolean DEBUG_INTENT_MATCHING = false;
192    private static final boolean DEBUG_PACKAGE_SCANNING = false;
193    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
194    private static final boolean DEBUG_VERIFY = false;
195
196    private static final int RADIO_UID = Process.PHONE_UID;
197    private static final int LOG_UID = Process.LOG_UID;
198    private static final int NFC_UID = Process.NFC_UID;
199    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
200    private static final int SHELL_UID = Process.SHELL_UID;
201
202    private static final boolean GET_CERTIFICATES = true;
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
268    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
269
270    static final String mTempContainerPrefix = "smdl2tmp";
271
272    final ServiceThread mHandlerThread;
273
274    private static final String IDMAP_PREFIX = "/data/resource-cache/";
275    private static final String IDMAP_SUFFIX = "@idmap";
276
277    final PackageHandler mHandler;
278
279    final int mSdkVersion = Build.VERSION.SDK_INT;
280    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
281            ? null : Build.VERSION.CODENAME;
282
283    final Context mContext;
284    final boolean mFactoryTest;
285    final boolean mOnlyCore;
286    final boolean mNoDexOpt;
287    final DisplayMetrics mMetrics;
288    final int mDefParseFlags;
289    final String[] mSeparateProcesses;
290
291    // This is where all application persistent data goes.
292    final File mAppDataDir;
293
294    // This is where all application persistent data goes for secondary users.
295    final File mUserAppDataDir;
296
297    /** The location for ASEC container files on internal storage. */
298    final String mAsecInternalPath;
299
300    // This is the object monitoring the framework dir.
301    final FileObserver mFrameworkInstallObserver;
302
303    // This is the object monitoring the system app dir.
304    final FileObserver mSystemInstallObserver;
305
306    // This is the object monitoring the privileged system app dir.
307    final FileObserver mPrivilegedInstallObserver;
308
309    // This is the object monitoring the vendor app dir.
310    final FileObserver mVendorInstallObserver;
311
312    // This is the object monitoring the vendor overlay package dir.
313    final FileObserver mVendorOverlayInstallObserver;
314
315    // This is the object monitoring the OEM app dir.
316    final FileObserver mOemInstallObserver;
317
318    // This is the object monitoring mAppInstallDir.
319    final FileObserver mAppInstallObserver;
320
321    // This is the object monitoring mDrmAppPrivateInstallDir.
322    final FileObserver mDrmAppInstallObserver;
323
324    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
325    // LOCK HELD.  Can be called with mInstallLock held.
326    final Installer mInstaller;
327
328    final File mAppInstallDir;
329
330    /**
331     * Directory to which applications installed internally have native
332     * libraries copied.
333     */
334    private File mAppLibInstallDir;
335
336    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
337    // apps.
338    final File mDrmAppPrivateInstallDir;
339
340    // ----------------------------------------------------------------
341
342    // Lock for state used when installing and doing other long running
343    // operations.  Methods that must be called with this lock held have
344    // the suffix "LI".
345    final Object mInstallLock = new Object();
346
347    // These are the directories in the 3rd party applications installed dir
348    // that we have currently loaded packages from.  Keys are the application's
349    // installed zip file (absolute codePath), and values are Package.
350    final HashMap<String, PackageParser.Package> mAppDirs =
351            new HashMap<String, PackageParser.Package>();
352
353    // Information for the parser to write more useful error messages.
354    int mLastScanError;
355
356    // ----------------------------------------------------------------
357
358    // Keys are String (package name), values are Package.  This also serves
359    // as the lock for the global state.  Methods that must be called with
360    // this lock held have the prefix "LP".
361    final HashMap<String, PackageParser.Package> mPackages =
362            new HashMap<String, PackageParser.Package>();
363
364    // Tracks available target package names -> overlay package paths.
365    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
366        new HashMap<String, HashMap<String, PackageParser.Package>>();
367
368    final Settings mSettings;
369    boolean mRestoredSettings;
370
371    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
372    int[] mGlobalGids;
373
374    // These are the built-in uid -> permission mappings that were read from the
375    // etc/permissions.xml file.
376    final SparseArray<HashSet<String>> mSystemPermissions =
377            new SparseArray<HashSet<String>>();
378
379    static final class SharedLibraryEntry {
380        final String path;
381        final String apk;
382
383        SharedLibraryEntry(String _path, String _apk) {
384            path = _path;
385            apk = _apk;
386        }
387    }
388
389    // These are the built-in shared libraries that were read from the
390    // etc/permissions.xml file.
391    final HashMap<String, SharedLibraryEntry> mSharedLibraries
392            = new HashMap<String, SharedLibraryEntry>();
393
394    // Temporary for building the final shared libraries for an .apk.
395    String[] mTmpSharedLibraries = null;
396
397    // These are the features this devices supports that were read from the
398    // etc/permissions.xml file.
399    final HashMap<String, FeatureInfo> mAvailableFeatures =
400            new HashMap<String, FeatureInfo>();
401
402    // If mac_permissions.xml was found for seinfo labeling.
403    boolean mFoundPolicyFile;
404
405    // All available activities, for your resolving pleasure.
406    final ActivityIntentResolver mActivities =
407            new ActivityIntentResolver();
408
409    // All available receivers, for your resolving pleasure.
410    final ActivityIntentResolver mReceivers =
411            new ActivityIntentResolver();
412
413    // All available services, for your resolving pleasure.
414    final ServiceIntentResolver mServices = new ServiceIntentResolver();
415
416    // All available providers, for your resolving pleasure.
417    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
418
419    // Mapping from provider base names (first directory in content URI codePath)
420    // to the provider information.
421    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
422            new HashMap<String, PackageParser.Provider>();
423
424    // Mapping from instrumentation class names to info about them.
425    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
426            new HashMap<ComponentName, PackageParser.Instrumentation>();
427
428    // Mapping from permission names to info about them.
429    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
430            new HashMap<String, PackageParser.PermissionGroup>();
431
432    // Packages whose data we have transfered into another package, thus
433    // should no longer exist.
434    final HashSet<String> mTransferedPackages = new HashSet<String>();
435
436    // Broadcast actions that are only available to the system.
437    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
438
439    /** List of packages waiting for verification. */
440    final SparseArray<PackageVerificationState> mPendingVerification
441            = new SparseArray<PackageVerificationState>();
442
443    HashSet<PackageParser.Package> mDeferredDexOpt = null;
444
445    /** Token for keys in mPendingVerification. */
446    private int mPendingVerificationToken = 0;
447
448    boolean mSystemReady;
449    boolean mSafeMode;
450    boolean mHasSystemUidErrors;
451
452    ApplicationInfo mAndroidApplication;
453    final ActivityInfo mResolveActivity = new ActivityInfo();
454    final ResolveInfo mResolveInfo = new ResolveInfo();
455    ComponentName mResolveComponentName;
456    PackageParser.Package mPlatformPackage;
457    ComponentName mCustomResolverComponentName;
458
459    boolean mResolverReplaced = false;
460
461    // Set of pending broadcasts for aggregating enable/disable of components.
462    static class PendingPackageBroadcasts {
463        // for each user id, a map of <package name -> components within that package>
464        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
465
466        public PendingPackageBroadcasts() {
467            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
468        }
469
470        public ArrayList<String> get(int userId, String packageName) {
471            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
472            return packages.get(packageName);
473        }
474
475        public void put(int userId, String packageName, ArrayList<String> components) {
476            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
477            packages.put(packageName, components);
478        }
479
480        public void remove(int userId, String packageName) {
481            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
482            if (packages != null) {
483                packages.remove(packageName);
484            }
485        }
486
487        public void remove(int userId) {
488            mUidMap.remove(userId);
489        }
490
491        public int userIdCount() {
492            return mUidMap.size();
493        }
494
495        public int userIdAt(int n) {
496            return mUidMap.keyAt(n);
497        }
498
499        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
500            return mUidMap.get(userId);
501        }
502
503        public int size() {
504            // total number of pending broadcast entries across all userIds
505            int num = 0;
506            for (int i = 0; i< mUidMap.size(); i++) {
507                num += mUidMap.valueAt(i).size();
508            }
509            return num;
510        }
511
512        public void clear() {
513            mUidMap.clear();
514        }
515
516        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
517            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
518            if (map == null) {
519                map = new HashMap<String, ArrayList<String>>();
520                mUidMap.put(userId, map);
521            }
522            return map;
523        }
524    }
525    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
526
527    // Service Connection to remote media container service to copy
528    // package uri's from external media onto secure containers
529    // or internal storage.
530    private IMediaContainerService mContainerService = null;
531
532    static final int SEND_PENDING_BROADCAST = 1;
533    static final int MCS_BOUND = 3;
534    static final int END_COPY = 4;
535    static final int INIT_COPY = 5;
536    static final int MCS_UNBIND = 6;
537    static final int START_CLEANING_PACKAGE = 7;
538    static final int FIND_INSTALL_LOC = 8;
539    static final int POST_INSTALL = 9;
540    static final int MCS_RECONNECT = 10;
541    static final int MCS_GIVE_UP = 11;
542    static final int UPDATED_MEDIA_STATUS = 12;
543    static final int WRITE_SETTINGS = 13;
544    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
545    static final int PACKAGE_VERIFIED = 15;
546    static final int CHECK_PENDING_VERIFICATION = 16;
547
548    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
549
550    // Delay time in millisecs
551    static final int BROADCAST_DELAY = 10 * 1000;
552
553    static UserManagerService sUserManager;
554
555    // Stores a list of users whose package restrictions file needs to be updated
556    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
557
558    final private DefaultContainerConnection mDefContainerConn =
559            new DefaultContainerConnection();
560    class DefaultContainerConnection implements ServiceConnection {
561        public void onServiceConnected(ComponentName name, IBinder service) {
562            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
563            IMediaContainerService imcs =
564                IMediaContainerService.Stub.asInterface(service);
565            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
566        }
567
568        public void onServiceDisconnected(ComponentName name) {
569            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
570        }
571    };
572
573    // Recordkeeping of restore-after-install operations that are currently in flight
574    // between the Package Manager and the Backup Manager
575    class PostInstallData {
576        public InstallArgs args;
577        public PackageInstalledInfo res;
578
579        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
580            args = _a;
581            res = _r;
582        }
583    };
584    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
585    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
586
587    private final String mRequiredVerifierPackage;
588
589    class PackageHandler extends Handler {
590        private boolean mBound = false;
591        final ArrayList<HandlerParams> mPendingInstalls =
592            new ArrayList<HandlerParams>();
593
594        private boolean connectToService() {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
596                    " DefaultContainerService");
597            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
598            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
599            if (mContext.bindServiceAsUser(service, mDefContainerConn,
600                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
601                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
602                mBound = true;
603                return true;
604            }
605            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
606            return false;
607        }
608
609        private void disconnectService() {
610            mContainerService = null;
611            mBound = false;
612            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
613            mContext.unbindService(mDefContainerConn);
614            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
615        }
616
617        PackageHandler(Looper looper) {
618            super(looper);
619        }
620
621        public void handleMessage(Message msg) {
622            try {
623                doHandleMessage(msg);
624            } finally {
625                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
626            }
627        }
628
629        void doHandleMessage(Message msg) {
630            switch (msg.what) {
631                case INIT_COPY: {
632                    HandlerParams params = (HandlerParams) msg.obj;
633                    int idx = mPendingInstalls.size();
634                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
635                    // If a bind was already initiated we dont really
636                    // need to do anything. The pending install
637                    // will be processed later on.
638                    if (!mBound) {
639                        // If this is the only one pending we might
640                        // have to bind to the service again.
641                        if (!connectToService()) {
642                            Slog.e(TAG, "Failed to bind to media container service");
643                            params.serviceError();
644                            return;
645                        } else {
646                            // Once we bind to the service, the first
647                            // pending request will be processed.
648                            mPendingInstalls.add(idx, params);
649                        }
650                    } else {
651                        mPendingInstalls.add(idx, params);
652                        // Already bound to the service. Just make
653                        // sure we trigger off processing the first request.
654                        if (idx == 0) {
655                            mHandler.sendEmptyMessage(MCS_BOUND);
656                        }
657                    }
658                    break;
659                }
660                case MCS_BOUND: {
661                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
662                    if (msg.obj != null) {
663                        mContainerService = (IMediaContainerService) msg.obj;
664                    }
665                    if (mContainerService == null) {
666                        // Something seriously wrong. Bail out
667                        Slog.e(TAG, "Cannot bind to media container service");
668                        for (HandlerParams params : mPendingInstalls) {
669                            // Indicate service bind error
670                            params.serviceError();
671                        }
672                        mPendingInstalls.clear();
673                    } else if (mPendingInstalls.size() > 0) {
674                        HandlerParams params = mPendingInstalls.get(0);
675                        if (params != null) {
676                            if (params.startCopy()) {
677                                // We are done...  look for more work or to
678                                // go idle.
679                                if (DEBUG_SD_INSTALL) Log.i(TAG,
680                                        "Checking for more work or unbind...");
681                                // Delete pending install
682                                if (mPendingInstalls.size() > 0) {
683                                    mPendingInstalls.remove(0);
684                                }
685                                if (mPendingInstalls.size() == 0) {
686                                    if (mBound) {
687                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
688                                                "Posting delayed MCS_UNBIND");
689                                        removeMessages(MCS_UNBIND);
690                                        Message ubmsg = obtainMessage(MCS_UNBIND);
691                                        // Unbind after a little delay, to avoid
692                                        // continual thrashing.
693                                        sendMessageDelayed(ubmsg, 10000);
694                                    }
695                                } else {
696                                    // There are more pending requests in queue.
697                                    // Just post MCS_BOUND message to trigger processing
698                                    // of next pending install.
699                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
700                                            "Posting MCS_BOUND for next woek");
701                                    mHandler.sendEmptyMessage(MCS_BOUND);
702                                }
703                            }
704                        }
705                    } else {
706                        // Should never happen ideally.
707                        Slog.w(TAG, "Empty queue");
708                    }
709                    break;
710                }
711                case MCS_RECONNECT: {
712                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
713                    if (mPendingInstalls.size() > 0) {
714                        if (mBound) {
715                            disconnectService();
716                        }
717                        if (!connectToService()) {
718                            Slog.e(TAG, "Failed to bind to media container service");
719                            for (HandlerParams params : mPendingInstalls) {
720                                // Indicate service bind error
721                                params.serviceError();
722                            }
723                            mPendingInstalls.clear();
724                        }
725                    }
726                    break;
727                }
728                case MCS_UNBIND: {
729                    // If there is no actual work left, then time to unbind.
730                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
731
732                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
733                        if (mBound) {
734                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
735
736                            disconnectService();
737                        }
738                    } else if (mPendingInstalls.size() > 0) {
739                        // There are more pending requests in queue.
740                        // Just post MCS_BOUND message to trigger processing
741                        // of next pending install.
742                        mHandler.sendEmptyMessage(MCS_BOUND);
743                    }
744
745                    break;
746                }
747                case MCS_GIVE_UP: {
748                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
749                    mPendingInstalls.remove(0);
750                    break;
751                }
752                case SEND_PENDING_BROADCAST: {
753                    String packages[];
754                    ArrayList<String> components[];
755                    int size = 0;
756                    int uids[];
757                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
758                    synchronized (mPackages) {
759                        if (mPendingBroadcasts == null) {
760                            return;
761                        }
762                        size = mPendingBroadcasts.size();
763                        if (size <= 0) {
764                            // Nothing to be done. Just return
765                            return;
766                        }
767                        packages = new String[size];
768                        components = new ArrayList[size];
769                        uids = new int[size];
770                        int i = 0;  // filling out the above arrays
771
772                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
773                            int packageUserId = mPendingBroadcasts.userIdAt(n);
774                            Iterator<Map.Entry<String, ArrayList<String>>> it
775                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
776                                            .entrySet().iterator();
777                            while (it.hasNext() && i < size) {
778                                Map.Entry<String, ArrayList<String>> ent = it.next();
779                                packages[i] = ent.getKey();
780                                components[i] = ent.getValue();
781                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
782                                uids[i] = (ps != null)
783                                        ? UserHandle.getUid(packageUserId, ps.appId)
784                                        : -1;
785                                i++;
786                            }
787                        }
788                        size = i;
789                        mPendingBroadcasts.clear();
790                    }
791                    // Send broadcasts
792                    for (int i = 0; i < size; i++) {
793                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
794                    }
795                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
796                    break;
797                }
798                case START_CLEANING_PACKAGE: {
799                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
800                    final String packageName = (String)msg.obj;
801                    final int userId = msg.arg1;
802                    final boolean andCode = msg.arg2 != 0;
803                    synchronized (mPackages) {
804                        if (userId == UserHandle.USER_ALL) {
805                            int[] users = sUserManager.getUserIds();
806                            for (int user : users) {
807                                mSettings.addPackageToCleanLPw(
808                                        new PackageCleanItem(user, packageName, andCode));
809                            }
810                        } else {
811                            mSettings.addPackageToCleanLPw(
812                                    new PackageCleanItem(userId, packageName, andCode));
813                        }
814                    }
815                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
816                    startCleaningPackages();
817                } break;
818                case POST_INSTALL: {
819                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
820                    PostInstallData data = mRunningInstalls.get(msg.arg1);
821                    mRunningInstalls.delete(msg.arg1);
822                    boolean deleteOld = false;
823
824                    if (data != null) {
825                        InstallArgs args = data.args;
826                        PackageInstalledInfo res = data.res;
827
828                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
829                            res.removedInfo.sendBroadcast(false, true, false);
830                            Bundle extras = new Bundle(1);
831                            extras.putInt(Intent.EXTRA_UID, res.uid);
832                            // Determine the set of users who are adding this
833                            // package for the first time vs. those who are seeing
834                            // an update.
835                            int[] firstUsers;
836                            int[] updateUsers = new int[0];
837                            if (res.origUsers == null || res.origUsers.length == 0) {
838                                firstUsers = res.newUsers;
839                            } else {
840                                firstUsers = new int[0];
841                                for (int i=0; i<res.newUsers.length; i++) {
842                                    int user = res.newUsers[i];
843                                    boolean isNew = true;
844                                    for (int j=0; j<res.origUsers.length; j++) {
845                                        if (res.origUsers[j] == user) {
846                                            isNew = false;
847                                            break;
848                                        }
849                                    }
850                                    if (isNew) {
851                                        int[] newFirst = new int[firstUsers.length+1];
852                                        System.arraycopy(firstUsers, 0, newFirst, 0,
853                                                firstUsers.length);
854                                        newFirst[firstUsers.length] = user;
855                                        firstUsers = newFirst;
856                                    } else {
857                                        int[] newUpdate = new int[updateUsers.length+1];
858                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
859                                                updateUsers.length);
860                                        newUpdate[updateUsers.length] = user;
861                                        updateUsers = newUpdate;
862                                    }
863                                }
864                            }
865                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
866                                    res.pkg.applicationInfo.packageName,
867                                    extras, null, null, firstUsers);
868                            final boolean update = res.removedInfo.removedPackage != null;
869                            if (update) {
870                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
871                            }
872                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
873                                    res.pkg.applicationInfo.packageName,
874                                    extras, null, null, updateUsers);
875                            if (update) {
876                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
877                                        res.pkg.applicationInfo.packageName,
878                                        extras, null, null, updateUsers);
879                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
880                                        null, null,
881                                        res.pkg.applicationInfo.packageName, null, updateUsers);
882
883                                // treat asec-hosted packages like removable media on upgrade
884                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
885                                    if (DEBUG_INSTALL) {
886                                        Slog.i(TAG, "upgrading pkg " + res.pkg
887                                                + " is ASEC-hosted -> AVAILABLE");
888                                    }
889                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
890                                    ArrayList<String> pkgList = new ArrayList<String>(1);
891                                    pkgList.add(res.pkg.applicationInfo.packageName);
892                                    sendResourcesChangedBroadcast(true, true,
893                                            pkgList,uidArray, null);
894                                }
895                            }
896                            if (res.removedInfo.args != null) {
897                                // Remove the replaced package's older resources safely now
898                                deleteOld = true;
899                            }
900
901                            // Log current value of "unknown sources" setting
902                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
903                                getUnknownSourcesSettings());
904                        }
905                        // Force a gc to clear up things
906                        Runtime.getRuntime().gc();
907                        // We delete after a gc for applications  on sdcard.
908                        if (deleteOld) {
909                            synchronized (mInstallLock) {
910                                res.removedInfo.args.doPostDeleteLI(true);
911                            }
912                        }
913                        if (args.observer != null) {
914                            try {
915                                args.observer.packageInstalled(res.name, res.returnCode);
916                            } catch (RemoteException e) {
917                                Slog.i(TAG, "Observer no longer exists.");
918                            }
919                        }
920                        if (args.observer2 != null) {
921                            try {
922                                Bundle extras = extrasForInstallResult(res);
923                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
924                            } catch (RemoteException e) {
925                                Slog.i(TAG, "Observer no longer exists.");
926                            }
927                        }
928                    } else {
929                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
930                    }
931                } break;
932                case UPDATED_MEDIA_STATUS: {
933                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
934                    boolean reportStatus = msg.arg1 == 1;
935                    boolean doGc = msg.arg2 == 1;
936                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
937                    if (doGc) {
938                        // Force a gc to clear up stale containers.
939                        Runtime.getRuntime().gc();
940                    }
941                    if (msg.obj != null) {
942                        @SuppressWarnings("unchecked")
943                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
944                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
945                        // Unload containers
946                        unloadAllContainers(args);
947                    }
948                    if (reportStatus) {
949                        try {
950                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
951                            PackageHelper.getMountService().finishMediaUpdate();
952                        } catch (RemoteException e) {
953                            Log.e(TAG, "MountService not running?");
954                        }
955                    }
956                } break;
957                case WRITE_SETTINGS: {
958                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
959                    synchronized (mPackages) {
960                        removeMessages(WRITE_SETTINGS);
961                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
962                        mSettings.writeLPr();
963                        mDirtyUsers.clear();
964                    }
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
966                } break;
967                case WRITE_PACKAGE_RESTRICTIONS: {
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
969                    synchronized (mPackages) {
970                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
971                        for (int userId : mDirtyUsers) {
972                            mSettings.writePackageRestrictionsLPr(userId);
973                        }
974                        mDirtyUsers.clear();
975                    }
976                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
977                } break;
978                case CHECK_PENDING_VERIFICATION: {
979                    final int verificationId = msg.arg1;
980                    final PackageVerificationState state = mPendingVerification.get(verificationId);
981
982                    if ((state != null) && !state.timeoutExtended()) {
983                        final InstallArgs args = state.getInstallArgs();
984                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
985                        mPendingVerification.remove(verificationId);
986
987                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
988
989                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
990                            Slog.i(TAG, "Continuing with installation of "
991                                    + args.packageURI.toString());
992                            state.setVerifierResponse(Binder.getCallingUid(),
993                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
994                            broadcastPackageVerified(verificationId, args.packageURI,
995                                    PackageManager.VERIFICATION_ALLOW,
996                                    state.getInstallArgs().getUser());
997                            try {
998                                ret = args.copyApk(mContainerService, true);
999                            } catch (RemoteException e) {
1000                                Slog.e(TAG, "Could not contact the ContainerService");
1001                            }
1002                        } else {
1003                            broadcastPackageVerified(verificationId, args.packageURI,
1004                                    PackageManager.VERIFICATION_REJECT,
1005                                    state.getInstallArgs().getUser());
1006                        }
1007
1008                        processPendingInstall(args, ret);
1009                        mHandler.sendEmptyMessage(MCS_UNBIND);
1010                    }
1011                    break;
1012                }
1013                case PACKAGE_VERIFIED: {
1014                    final int verificationId = msg.arg1;
1015
1016                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1017                    if (state == null) {
1018                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1019                        break;
1020                    }
1021
1022                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1023
1024                    state.setVerifierResponse(response.callerUid, response.code);
1025
1026                    if (state.isVerificationComplete()) {
1027                        mPendingVerification.remove(verificationId);
1028
1029                        final InstallArgs args = state.getInstallArgs();
1030
1031                        int ret;
1032                        if (state.isInstallAllowed()) {
1033                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1034                            broadcastPackageVerified(verificationId, args.packageURI,
1035                                    response.code, state.getInstallArgs().getUser());
1036                            try {
1037                                ret = args.copyApk(mContainerService, true);
1038                            } catch (RemoteException e) {
1039                                Slog.e(TAG, "Could not contact the ContainerService");
1040                            }
1041                        } else {
1042                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1043                        }
1044
1045                        processPendingInstall(args, ret);
1046
1047                        mHandler.sendEmptyMessage(MCS_UNBIND);
1048                    }
1049
1050                    break;
1051                }
1052            }
1053        }
1054    }
1055
1056    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1057        Bundle extras = null;
1058        switch (res.returnCode) {
1059            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1060                extras = new Bundle();
1061                extras.putString(PackageManager.EXTRA_EXISTING_PERMISSION, res.origPermission);
1062                extras.putString(PackageManager.EXTRA_EXISTING_PACKAGE, res.origPackage);
1063                break;
1064            }
1065        }
1066        return extras;
1067    }
1068
1069    void scheduleWriteSettingsLocked() {
1070        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1071            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1072        }
1073    }
1074
1075    void scheduleWritePackageRestrictionsLocked(int userId) {
1076        if (!sUserManager.exists(userId)) return;
1077        mDirtyUsers.add(userId);
1078        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1079            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1080        }
1081    }
1082
1083    public static final IPackageManager main(Context context, Installer installer,
1084            boolean factoryTest, boolean onlyCore) {
1085        PackageManagerService m = new PackageManagerService(context, installer,
1086                factoryTest, onlyCore);
1087        ServiceManager.addService("package", m);
1088        return m;
1089    }
1090
1091    static String[] splitString(String str, char sep) {
1092        int count = 1;
1093        int i = 0;
1094        while ((i=str.indexOf(sep, i)) >= 0) {
1095            count++;
1096            i++;
1097        }
1098
1099        String[] res = new String[count];
1100        i=0;
1101        count = 0;
1102        int lastI=0;
1103        while ((i=str.indexOf(sep, i)) >= 0) {
1104            res[count] = str.substring(lastI, i);
1105            count++;
1106            i++;
1107            lastI = i;
1108        }
1109        res[count] = str.substring(lastI, str.length());
1110        return res;
1111    }
1112
1113    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1114        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1115                Context.DISPLAY_SERVICE);
1116        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1117    }
1118
1119    public PackageManagerService(Context context, Installer installer,
1120            boolean factoryTest, boolean onlyCore) {
1121        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1122                SystemClock.uptimeMillis());
1123
1124        if (mSdkVersion <= 0) {
1125            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1126        }
1127
1128        mContext = context;
1129        mFactoryTest = factoryTest;
1130        mOnlyCore = onlyCore;
1131        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1132        mMetrics = new DisplayMetrics();
1133        mSettings = new Settings(context);
1134        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1135                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1136        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1137                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1138        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1139                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1140        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1141                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1142        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1143                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1144        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1145                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1146
1147        String separateProcesses = SystemProperties.get("debug.separate_processes");
1148        if (separateProcesses != null && separateProcesses.length() > 0) {
1149            if ("*".equals(separateProcesses)) {
1150                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1151                mSeparateProcesses = null;
1152                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1153            } else {
1154                mDefParseFlags = 0;
1155                mSeparateProcesses = separateProcesses.split(",");
1156                Slog.w(TAG, "Running with debug.separate_processes: "
1157                        + separateProcesses);
1158            }
1159        } else {
1160            mDefParseFlags = 0;
1161            mSeparateProcesses = null;
1162        }
1163
1164        mInstaller = installer;
1165
1166        getDefaultDisplayMetrics(context, mMetrics);
1167
1168        synchronized (mInstallLock) {
1169        // writer
1170        synchronized (mPackages) {
1171            mHandlerThread = new ServiceThread(TAG,
1172                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1173            mHandlerThread.start();
1174            mHandler = new PackageHandler(mHandlerThread.getLooper());
1175            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1176
1177            File dataDir = Environment.getDataDirectory();
1178            mAppDataDir = new File(dataDir, "data");
1179            mAppInstallDir = new File(dataDir, "app");
1180            mAppLibInstallDir = new File(dataDir, "app-lib");
1181            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1182            mUserAppDataDir = new File(dataDir, "user");
1183            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1184
1185            sUserManager = new UserManagerService(context, this,
1186                    mInstallLock, mPackages);
1187
1188            // Read permissions and features from system
1189            readPermissions(Environment.buildPath(
1190                    Environment.getRootDirectory(), "etc", "permissions"), false);
1191            // Only read features from OEM
1192            readPermissions(Environment.buildPath(
1193                    Environment.getOemDirectory(), "etc", "permissions"), true);
1194
1195            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1196
1197            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1198                    mSdkVersion, mOnlyCore);
1199
1200            String customResolverActivity = Resources.getSystem().getString(
1201                    R.string.config_customResolverActivity);
1202            if (TextUtils.isEmpty(customResolverActivity)) {
1203                customResolverActivity = null;
1204            } else {
1205                mCustomResolverComponentName = ComponentName.unflattenFromString(
1206                        customResolverActivity);
1207            }
1208
1209            long startTime = SystemClock.uptimeMillis();
1210
1211            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1212                    startTime);
1213
1214            // Set flag to monitor and not change apk file paths when
1215            // scanning install directories.
1216            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1217            if (mNoDexOpt) {
1218                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1219                scanMode |= SCAN_NO_DEX;
1220            }
1221
1222            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1223
1224            /**
1225             * Add everything in the in the boot class path to the
1226             * list of process files because dexopt will have been run
1227             * if necessary during zygote startup.
1228             */
1229            String bootClassPath = System.getProperty("java.boot.class.path");
1230            if (bootClassPath != null) {
1231                String[] paths = splitString(bootClassPath, ':');
1232                for (int i=0; i<paths.length; i++) {
1233                    alreadyDexOpted.add(paths[i]);
1234                }
1235            } else {
1236                Slog.w(TAG, "No BOOTCLASSPATH found!");
1237            }
1238
1239            boolean didDexOpt = false;
1240
1241            /**
1242             * Ensure all external libraries have had dexopt run on them.
1243             */
1244            if (mSharedLibraries.size() > 0) {
1245                Iterator<SharedLibraryEntry> libs = mSharedLibraries.values().iterator();
1246                while (libs.hasNext()) {
1247                    String lib = libs.next().path;
1248                    if (lib == null) {
1249                        continue;
1250                    }
1251                    try {
1252                        if (dalvik.system.DexFile.isDexOptNeededInternal(lib, null, false)) {
1253                            alreadyDexOpted.add(lib);
1254                            mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1255                            didDexOpt = true;
1256                        }
1257                    } catch (FileNotFoundException e) {
1258                        Slog.w(TAG, "Library not found: " + lib);
1259                    } catch (IOException e) {
1260                        Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1261                                + e.getMessage());
1262                    }
1263                }
1264            }
1265
1266            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1267
1268            // Gross hack for now: we know this file doesn't contain any
1269            // code, so don't dexopt it to avoid the resulting log spew.
1270            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1271
1272            // Gross hack for now: we know this file is only part of
1273            // the boot class path for art, so don't dexopt it to
1274            // avoid the resulting log spew.
1275            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1276
1277            /**
1278             * And there are a number of commands implemented in Java, which
1279             * we currently need to do the dexopt on so that they can be
1280             * run from a non-root shell.
1281             */
1282            String[] frameworkFiles = frameworkDir.list();
1283            if (frameworkFiles != null) {
1284                for (int i=0; i<frameworkFiles.length; i++) {
1285                    File libPath = new File(frameworkDir, frameworkFiles[i]);
1286                    String path = libPath.getPath();
1287                    // Skip the file if we alrady did it.
1288                    if (alreadyDexOpted.contains(path)) {
1289                        continue;
1290                    }
1291                    // Skip the file if it is not a type we want to dexopt.
1292                    if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1293                        continue;
1294                    }
1295                    try {
1296                        if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, false)) {
1297                            mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1298                            didDexOpt = true;
1299                        }
1300                    } catch (FileNotFoundException e) {
1301                        Slog.w(TAG, "Jar not found: " + path);
1302                    } catch (IOException e) {
1303                        Slog.w(TAG, "Exception reading jar: " + path, e);
1304                    }
1305                }
1306            }
1307
1308            if (didDexOpt) {
1309                File dalvikCacheDir = new File(dataDir, "dalvik-cache");
1310
1311                // If we had to do a dexopt of one of the previous
1312                // things, then something on the system has changed.
1313                // Consider this significant, and wipe away all other
1314                // existing dexopt files to ensure we don't leave any
1315                // dangling around.
1316                String[] files = dalvikCacheDir.list();
1317                if (files != null) {
1318                    for (int i=0; i<files.length; i++) {
1319                        String fn = files[i];
1320                        if (fn.startsWith("data@app@")
1321                                || fn.startsWith("data@app-private@")) {
1322                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1323                            (new File(dalvikCacheDir, fn)).delete();
1324                        }
1325                    }
1326                }
1327            }
1328
1329            // Collect vendor overlay packages.
1330            // (Do this before scanning any apps.)
1331            // For security and version matching reason, only consider
1332            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1333            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1334            mVendorOverlayInstallObserver = new AppDirObserver(
1335                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1336            mVendorOverlayInstallObserver.startWatching();
1337            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1338                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1339
1340            // Find base frameworks (resource packages without code).
1341            mFrameworkInstallObserver = new AppDirObserver(
1342                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1343            mFrameworkInstallObserver.startWatching();
1344            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1345                    | PackageParser.PARSE_IS_SYSTEM_DIR
1346                    | PackageParser.PARSE_IS_PRIVILEGED,
1347                    scanMode | SCAN_NO_DEX, 0);
1348
1349            // Collected privileged system packages.
1350            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1351            mPrivilegedInstallObserver = new AppDirObserver(
1352                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1353            mPrivilegedInstallObserver.startWatching();
1354                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1355                        | PackageParser.PARSE_IS_SYSTEM_DIR
1356                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1357
1358            // Collect ordinary system packages.
1359            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1360            mSystemInstallObserver = new AppDirObserver(
1361                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1362            mSystemInstallObserver.startWatching();
1363            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1364                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1365
1366            // Collect all vendor packages.
1367            File vendorAppDir = new File("/vendor/app");
1368            try {
1369                vendorAppDir = vendorAppDir.getCanonicalFile();
1370            } catch (IOException e) {
1371                // failed to look up canonical path, continue with original one
1372            }
1373            mVendorInstallObserver = new AppDirObserver(
1374                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1375            mVendorInstallObserver.startWatching();
1376            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1377                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1378
1379            // Collect all OEM packages.
1380            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1381            mOemInstallObserver = new AppDirObserver(
1382                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1383            mOemInstallObserver.startWatching();
1384            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1385                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1386
1387            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1388            mInstaller.moveFiles();
1389
1390            // Prune any system packages that no longer exist.
1391            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1392            if (!mOnlyCore) {
1393                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1394                while (psit.hasNext()) {
1395                    PackageSetting ps = psit.next();
1396
1397                    /*
1398                     * If this is not a system app, it can't be a
1399                     * disable system app.
1400                     */
1401                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1402                        continue;
1403                    }
1404
1405                    /*
1406                     * If the package is scanned, it's not erased.
1407                     */
1408                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1409                    if (scannedPkg != null) {
1410                        /*
1411                         * If the system app is both scanned and in the
1412                         * disabled packages list, then it must have been
1413                         * added via OTA. Remove it from the currently
1414                         * scanned package so the previously user-installed
1415                         * application can be scanned.
1416                         */
1417                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1418                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1419                                    + "; removing system app");
1420                            removePackageLI(ps, true);
1421                        }
1422
1423                        continue;
1424                    }
1425
1426                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1427                        psit.remove();
1428                        String msg = "System package " + ps.name
1429                                + " no longer exists; wiping its data";
1430                        reportSettingsProblem(Log.WARN, msg);
1431                        removeDataDirsLI(ps.name);
1432                    } else {
1433                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1434                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1435                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1436                        }
1437                    }
1438                }
1439            }
1440
1441            //look for any incomplete package installations
1442            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1443            //clean up list
1444            for(int i = 0; i < deletePkgsList.size(); i++) {
1445                //clean up here
1446                cleanupInstallFailedPackage(deletePkgsList.get(i));
1447            }
1448            //delete tmp files
1449            deleteTempPackageFiles();
1450
1451            // Remove any shared userIDs that have no associated packages
1452            mSettings.pruneSharedUsersLPw();
1453
1454            if (!mOnlyCore) {
1455                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1456                        SystemClock.uptimeMillis());
1457                mAppInstallObserver = new AppDirObserver(
1458                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1459                mAppInstallObserver.startWatching();
1460                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1461
1462                mDrmAppInstallObserver = new AppDirObserver(
1463                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1464                mDrmAppInstallObserver.startWatching();
1465                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1466                        scanMode, 0);
1467
1468                /**
1469                 * Remove disable package settings for any updated system
1470                 * apps that were removed via an OTA. If they're not a
1471                 * previously-updated app, remove them completely.
1472                 * Otherwise, just revoke their system-level permissions.
1473                 */
1474                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1475                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1476                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1477
1478                    String msg;
1479                    if (deletedPkg == null) {
1480                        msg = "Updated system package " + deletedAppName
1481                                + " no longer exists; wiping its data";
1482                        removeDataDirsLI(deletedAppName);
1483                    } else {
1484                        msg = "Updated system app + " + deletedAppName
1485                                + " no longer present; removing system privileges for "
1486                                + deletedAppName;
1487
1488                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1489
1490                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1491                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1492                    }
1493                    reportSettingsProblem(Log.WARN, msg);
1494                }
1495            } else {
1496                mAppInstallObserver = null;
1497                mDrmAppInstallObserver = null;
1498            }
1499
1500            // Now that we know all of the shared libraries, update all clients to have
1501            // the correct library paths.
1502            updateAllSharedLibrariesLPw();
1503
1504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1505                    SystemClock.uptimeMillis());
1506            Slog.i(TAG, "Time to scan packages: "
1507                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1508                    + " seconds");
1509
1510            // If the platform SDK has changed since the last time we booted,
1511            // we need to re-grant app permission to catch any new ones that
1512            // appear.  This is really a hack, and means that apps can in some
1513            // cases get permissions that the user didn't initially explicitly
1514            // allow...  it would be nice to have some better way to handle
1515            // this situation.
1516            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1517                    != mSdkVersion;
1518            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1519                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1520                    + "; regranting permissions for internal storage");
1521            mSettings.mInternalSdkPlatform = mSdkVersion;
1522
1523            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1524                    | (regrantPermissions
1525                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1526                            : 0));
1527
1528            // If this is the first boot, and it is a normal boot, then
1529            // we need to initialize the default preferred apps.
1530            if (!mRestoredSettings && !onlyCore) {
1531                mSettings.readDefaultPreferredAppsLPw(this, 0);
1532            }
1533
1534            // can downgrade to reader
1535            mSettings.writeLPr();
1536
1537            if (SELinuxMMAC.shouldRestorecon()) {
1538                Slog.i(TAG, "Relabeling of /data/data and /data/user issued.");
1539                if (mInstaller.restoreconData()) {
1540                    SELinuxMMAC.setRestoreconDone();
1541                }
1542            }
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            }
2060            return generatePackageInfo(pkg, flags, userId);
2061        }
2062        return null;
2063    }
2064
2065    @Override
2066    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2067        if (!sUserManager.exists(userId)) return null;
2068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2069        // writer
2070        synchronized (mPackages) {
2071            PackageParser.Package p = mPackages.get(packageName);
2072            if (DEBUG_PACKAGE_INFO) Log.v(
2073                    TAG, "getApplicationInfo " + packageName
2074                    + ": " + p);
2075            if (p != null) {
2076                PackageSetting ps = mSettings.mPackages.get(packageName);
2077                if (ps == null) return null;
2078                // Note: isEnabledLP() does not apply here - always return info
2079                return PackageParser.generateApplicationInfo(
2080                        p, flags, ps.readUserState(userId), userId);
2081            }
2082            if ("android".equals(packageName)||"system".equals(packageName)) {
2083                return mAndroidApplication;
2084            }
2085            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2086                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2087            }
2088        }
2089        return null;
2090    }
2091
2092
2093    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2094        mContext.enforceCallingOrSelfPermission(
2095                android.Manifest.permission.CLEAR_APP_CACHE, null);
2096        // Queue up an async operation since clearing cache may take a little while.
2097        mHandler.post(new Runnable() {
2098            public void run() {
2099                mHandler.removeCallbacks(this);
2100                int retCode = -1;
2101                synchronized (mInstallLock) {
2102                    retCode = mInstaller.freeCache(freeStorageSize);
2103                    if (retCode < 0) {
2104                        Slog.w(TAG, "Couldn't clear application caches");
2105                    }
2106                }
2107                if (observer != null) {
2108                    try {
2109                        observer.onRemoveCompleted(null, (retCode >= 0));
2110                    } catch (RemoteException e) {
2111                        Slog.w(TAG, "RemoveException when invoking call back");
2112                    }
2113                }
2114            }
2115        });
2116    }
2117
2118    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2119        mContext.enforceCallingOrSelfPermission(
2120                android.Manifest.permission.CLEAR_APP_CACHE, null);
2121        // Queue up an async operation since clearing cache may take a little while.
2122        mHandler.post(new Runnable() {
2123            public void run() {
2124                mHandler.removeCallbacks(this);
2125                int retCode = -1;
2126                synchronized (mInstallLock) {
2127                    retCode = mInstaller.freeCache(freeStorageSize);
2128                    if (retCode < 0) {
2129                        Slog.w(TAG, "Couldn't clear application caches");
2130                    }
2131                }
2132                if(pi != null) {
2133                    try {
2134                        // Callback via pending intent
2135                        int code = (retCode >= 0) ? 1 : 0;
2136                        pi.sendIntent(null, code, null,
2137                                null, null);
2138                    } catch (SendIntentException e1) {
2139                        Slog.i(TAG, "Failed to send pending intent");
2140                    }
2141                }
2142            }
2143        });
2144    }
2145
2146    @Override
2147    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2148        if (!sUserManager.exists(userId)) return null;
2149        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2150        synchronized (mPackages) {
2151            PackageParser.Activity a = mActivities.mActivities.get(component);
2152
2153            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2154            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2155                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2156                if (ps == null) return null;
2157                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2158                        userId);
2159            }
2160            if (mResolveComponentName.equals(component)) {
2161                return mResolveActivity;
2162            }
2163        }
2164        return null;
2165    }
2166
2167    @Override
2168    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2169        if (!sUserManager.exists(userId)) return null;
2170        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2171        synchronized (mPackages) {
2172            PackageParser.Activity a = mReceivers.mActivities.get(component);
2173            if (DEBUG_PACKAGE_INFO) Log.v(
2174                TAG, "getReceiverInfo " + component + ": " + a);
2175            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2176                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2177                if (ps == null) return null;
2178                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2179                        userId);
2180            }
2181        }
2182        return null;
2183    }
2184
2185    @Override
2186    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2187        if (!sUserManager.exists(userId)) return null;
2188        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2189        synchronized (mPackages) {
2190            PackageParser.Service s = mServices.mServices.get(component);
2191            if (DEBUG_PACKAGE_INFO) Log.v(
2192                TAG, "getServiceInfo " + component + ": " + s);
2193            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2194                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2195                if (ps == null) return null;
2196                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2197                        userId);
2198            }
2199        }
2200        return null;
2201    }
2202
2203    @Override
2204    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2205        if (!sUserManager.exists(userId)) return null;
2206        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2207        synchronized (mPackages) {
2208            PackageParser.Provider p = mProviders.mProviders.get(component);
2209            if (DEBUG_PACKAGE_INFO) Log.v(
2210                TAG, "getProviderInfo " + component + ": " + p);
2211            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2212                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2213                if (ps == null) return null;
2214                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2215                        userId);
2216            }
2217        }
2218        return null;
2219    }
2220
2221    public String[] getSystemSharedLibraryNames() {
2222        Set<String> libSet;
2223        synchronized (mPackages) {
2224            libSet = mSharedLibraries.keySet();
2225            int size = libSet.size();
2226            if (size > 0) {
2227                String[] libs = new String[size];
2228                libSet.toArray(libs);
2229                return libs;
2230            }
2231        }
2232        return null;
2233    }
2234
2235    public FeatureInfo[] getSystemAvailableFeatures() {
2236        Collection<FeatureInfo> featSet;
2237        synchronized (mPackages) {
2238            featSet = mAvailableFeatures.values();
2239            int size = featSet.size();
2240            if (size > 0) {
2241                FeatureInfo[] features = new FeatureInfo[size+1];
2242                featSet.toArray(features);
2243                FeatureInfo fi = new FeatureInfo();
2244                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2245                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2246                features[size] = fi;
2247                return features;
2248            }
2249        }
2250        return null;
2251    }
2252
2253    public boolean hasSystemFeature(String name) {
2254        synchronized (mPackages) {
2255            return mAvailableFeatures.containsKey(name);
2256        }
2257    }
2258
2259    private void checkValidCaller(int uid, int userId) {
2260        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2261            return;
2262
2263        throw new SecurityException("Caller uid=" + uid
2264                + " is not privileged to communicate with user=" + userId);
2265    }
2266
2267    public int checkPermission(String permName, String pkgName) {
2268        synchronized (mPackages) {
2269            PackageParser.Package p = mPackages.get(pkgName);
2270            if (p != null && p.mExtras != null) {
2271                PackageSetting ps = (PackageSetting)p.mExtras;
2272                if (ps.sharedUser != null) {
2273                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2274                        return PackageManager.PERMISSION_GRANTED;
2275                    }
2276                } else if (ps.grantedPermissions.contains(permName)) {
2277                    return PackageManager.PERMISSION_GRANTED;
2278                }
2279            }
2280        }
2281        return PackageManager.PERMISSION_DENIED;
2282    }
2283
2284    public int checkUidPermission(String permName, int uid) {
2285        synchronized (mPackages) {
2286            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2287            if (obj != null) {
2288                GrantedPermissions gp = (GrantedPermissions)obj;
2289                if (gp.grantedPermissions.contains(permName)) {
2290                    return PackageManager.PERMISSION_GRANTED;
2291                }
2292            } else {
2293                HashSet<String> perms = mSystemPermissions.get(uid);
2294                if (perms != null && perms.contains(permName)) {
2295                    return PackageManager.PERMISSION_GRANTED;
2296                }
2297            }
2298        }
2299        return PackageManager.PERMISSION_DENIED;
2300    }
2301
2302    /**
2303     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2304     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2305     * @param message the message to log on security exception
2306     * @return
2307     */
2308    private void enforceCrossUserPermission(int callingUid, int userId,
2309            boolean requireFullPermission, String message) {
2310        if (userId < 0) {
2311            throw new IllegalArgumentException("Invalid userId " + userId);
2312        }
2313        if (userId == UserHandle.getUserId(callingUid)) return;
2314        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2315            if (requireFullPermission) {
2316                mContext.enforceCallingOrSelfPermission(
2317                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2318            } else {
2319                try {
2320                    mContext.enforceCallingOrSelfPermission(
2321                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2322                } catch (SecurityException se) {
2323                    mContext.enforceCallingOrSelfPermission(
2324                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2325                }
2326            }
2327        }
2328    }
2329
2330    private BasePermission findPermissionTreeLP(String permName) {
2331        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2332            if (permName.startsWith(bp.name) &&
2333                    permName.length() > bp.name.length() &&
2334                    permName.charAt(bp.name.length()) == '.') {
2335                return bp;
2336            }
2337        }
2338        return null;
2339    }
2340
2341    private BasePermission checkPermissionTreeLP(String permName) {
2342        if (permName != null) {
2343            BasePermission bp = findPermissionTreeLP(permName);
2344            if (bp != null) {
2345                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2346                    return bp;
2347                }
2348                throw new SecurityException("Calling uid "
2349                        + Binder.getCallingUid()
2350                        + " is not allowed to add to permission tree "
2351                        + bp.name + " owned by uid " + bp.uid);
2352            }
2353        }
2354        throw new SecurityException("No permission tree found for " + permName);
2355    }
2356
2357    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2358        if (s1 == null) {
2359            return s2 == null;
2360        }
2361        if (s2 == null) {
2362            return false;
2363        }
2364        if (s1.getClass() != s2.getClass()) {
2365            return false;
2366        }
2367        return s1.equals(s2);
2368    }
2369
2370    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2371        if (pi1.icon != pi2.icon) return false;
2372        if (pi1.logo != pi2.logo) return false;
2373        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2374        if (!compareStrings(pi1.name, pi2.name)) return false;
2375        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2376        // We'll take care of setting this one.
2377        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2378        // These are not currently stored in settings.
2379        //if (!compareStrings(pi1.group, pi2.group)) return false;
2380        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2381        //if (pi1.labelRes != pi2.labelRes) return false;
2382        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2383        return true;
2384    }
2385
2386    int permissionInfoFootprint(PermissionInfo info) {
2387        int size = info.name.length();
2388        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2389        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2390        return size;
2391    }
2392
2393    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2394        int size = 0;
2395        for (BasePermission perm : mSettings.mPermissions.values()) {
2396            if (perm.uid == tree.uid) {
2397                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2398            }
2399        }
2400        return size;
2401    }
2402
2403    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2404        // We calculate the max size of permissions defined by this uid and throw
2405        // if that plus the size of 'info' would exceed our stated maximum.
2406        if (tree.uid != Process.SYSTEM_UID) {
2407            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2408            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2409                throw new SecurityException("Permission tree size cap exceeded");
2410            }
2411        }
2412    }
2413
2414    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2415        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2416            throw new SecurityException("Label must be specified in permission");
2417        }
2418        BasePermission tree = checkPermissionTreeLP(info.name);
2419        BasePermission bp = mSettings.mPermissions.get(info.name);
2420        boolean added = bp == null;
2421        boolean changed = true;
2422        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2423        if (added) {
2424            enforcePermissionCapLocked(info, tree);
2425            bp = new BasePermission(info.name, tree.sourcePackage,
2426                    BasePermission.TYPE_DYNAMIC);
2427        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2428            throw new SecurityException(
2429                    "Not allowed to modify non-dynamic permission "
2430                    + info.name);
2431        } else {
2432            if (bp.protectionLevel == fixedLevel
2433                    && bp.perm.owner.equals(tree.perm.owner)
2434                    && bp.uid == tree.uid
2435                    && comparePermissionInfos(bp.perm.info, info)) {
2436                changed = false;
2437            }
2438        }
2439        bp.protectionLevel = fixedLevel;
2440        info = new PermissionInfo(info);
2441        info.protectionLevel = fixedLevel;
2442        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2443        bp.perm.info.packageName = tree.perm.info.packageName;
2444        bp.uid = tree.uid;
2445        if (added) {
2446            mSettings.mPermissions.put(info.name, bp);
2447        }
2448        if (changed) {
2449            if (!async) {
2450                mSettings.writeLPr();
2451            } else {
2452                scheduleWriteSettingsLocked();
2453            }
2454        }
2455        return added;
2456    }
2457
2458    public boolean addPermission(PermissionInfo info) {
2459        synchronized (mPackages) {
2460            return addPermissionLocked(info, false);
2461        }
2462    }
2463
2464    public boolean addPermissionAsync(PermissionInfo info) {
2465        synchronized (mPackages) {
2466            return addPermissionLocked(info, true);
2467        }
2468    }
2469
2470    public void removePermission(String name) {
2471        synchronized (mPackages) {
2472            checkPermissionTreeLP(name);
2473            BasePermission bp = mSettings.mPermissions.get(name);
2474            if (bp != null) {
2475                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2476                    throw new SecurityException(
2477                            "Not allowed to modify non-dynamic permission "
2478                            + name);
2479                }
2480                mSettings.mPermissions.remove(name);
2481                mSettings.writeLPr();
2482            }
2483        }
2484    }
2485
2486    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2487        int index = pkg.requestedPermissions.indexOf(bp.name);
2488        if (index == -1) {
2489            throw new SecurityException("Package " + pkg.packageName
2490                    + " has not requested permission " + bp.name);
2491        }
2492        boolean isNormal =
2493                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2494                        == PermissionInfo.PROTECTION_NORMAL);
2495        boolean isDangerous =
2496                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2497                        == PermissionInfo.PROTECTION_DANGEROUS);
2498        boolean isDevelopment =
2499                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2500
2501        if (!isNormal && !isDangerous && !isDevelopment) {
2502            throw new SecurityException("Permission " + bp.name
2503                    + " is not a changeable permission type");
2504        }
2505
2506        if (isNormal || isDangerous) {
2507            if (pkg.requestedPermissionsRequired.get(index)) {
2508                throw new SecurityException("Can't change " + bp.name
2509                        + ". It is required by the application");
2510            }
2511        }
2512    }
2513
2514    public void grantPermission(String packageName, String permissionName) {
2515        mContext.enforceCallingOrSelfPermission(
2516                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2517        synchronized (mPackages) {
2518            final PackageParser.Package pkg = mPackages.get(packageName);
2519            if (pkg == null) {
2520                throw new IllegalArgumentException("Unknown package: " + packageName);
2521            }
2522            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2523            if (bp == null) {
2524                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2525            }
2526
2527            checkGrantRevokePermissions(pkg, bp);
2528
2529            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2530            if (ps == null) {
2531                return;
2532            }
2533            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2534            if (gp.grantedPermissions.add(permissionName)) {
2535                if (ps.haveGids) {
2536                    gp.gids = appendInts(gp.gids, bp.gids);
2537                }
2538                mSettings.writeLPr();
2539            }
2540        }
2541    }
2542
2543    public void revokePermission(String packageName, String permissionName) {
2544        int changedAppId = -1;
2545
2546        synchronized (mPackages) {
2547            final PackageParser.Package pkg = mPackages.get(packageName);
2548            if (pkg == null) {
2549                throw new IllegalArgumentException("Unknown package: " + packageName);
2550            }
2551            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2552                mContext.enforceCallingOrSelfPermission(
2553                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2554            }
2555            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2556            if (bp == null) {
2557                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2558            }
2559
2560            checkGrantRevokePermissions(pkg, bp);
2561
2562            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2563            if (ps == null) {
2564                return;
2565            }
2566            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2567            if (gp.grantedPermissions.remove(permissionName)) {
2568                gp.grantedPermissions.remove(permissionName);
2569                if (ps.haveGids) {
2570                    gp.gids = removeInts(gp.gids, bp.gids);
2571                }
2572                mSettings.writeLPr();
2573                changedAppId = ps.appId;
2574            }
2575        }
2576
2577        if (changedAppId >= 0) {
2578            // We changed the perm on someone, kill its processes.
2579            IActivityManager am = ActivityManagerNative.getDefault();
2580            if (am != null) {
2581                final int callingUserId = UserHandle.getCallingUserId();
2582                final long ident = Binder.clearCallingIdentity();
2583                try {
2584                    //XXX we should only revoke for the calling user's app permissions,
2585                    // but for now we impact all users.
2586                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2587                    //        "revoke " + permissionName);
2588                    int[] users = sUserManager.getUserIds();
2589                    for (int user : users) {
2590                        am.killUid(UserHandle.getUid(user, changedAppId),
2591                                "revoke " + permissionName);
2592                    }
2593                } catch (RemoteException e) {
2594                } finally {
2595                    Binder.restoreCallingIdentity(ident);
2596                }
2597            }
2598        }
2599    }
2600
2601    public boolean isProtectedBroadcast(String actionName) {
2602        synchronized (mPackages) {
2603            return mProtectedBroadcasts.contains(actionName);
2604        }
2605    }
2606
2607    public int checkSignatures(String pkg1, String pkg2) {
2608        synchronized (mPackages) {
2609            final PackageParser.Package p1 = mPackages.get(pkg1);
2610            final PackageParser.Package p2 = mPackages.get(pkg2);
2611            if (p1 == null || p1.mExtras == null
2612                    || p2 == null || p2.mExtras == null) {
2613                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2614            }
2615            return compareSignatures(p1.mSignatures, p2.mSignatures);
2616        }
2617    }
2618
2619    public int checkUidSignatures(int uid1, int uid2) {
2620        // Map to base uids.
2621        uid1 = UserHandle.getAppId(uid1);
2622        uid2 = UserHandle.getAppId(uid2);
2623        // reader
2624        synchronized (mPackages) {
2625            Signature[] s1;
2626            Signature[] s2;
2627            Object obj = mSettings.getUserIdLPr(uid1);
2628            if (obj != null) {
2629                if (obj instanceof SharedUserSetting) {
2630                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2631                } else if (obj instanceof PackageSetting) {
2632                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2633                } else {
2634                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2635                }
2636            } else {
2637                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2638            }
2639            obj = mSettings.getUserIdLPr(uid2);
2640            if (obj != null) {
2641                if (obj instanceof SharedUserSetting) {
2642                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2643                } else if (obj instanceof PackageSetting) {
2644                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2645                } else {
2646                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2647                }
2648            } else {
2649                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2650            }
2651            return compareSignatures(s1, s2);
2652        }
2653    }
2654
2655    /**
2656     * Compares two sets of signatures. Returns:
2657     * <br />
2658     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2659     * <br />
2660     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2661     * <br />
2662     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2663     * <br />
2664     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2665     * <br />
2666     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2667     */
2668    static int compareSignatures(Signature[] s1, Signature[] s2) {
2669        if (s1 == null) {
2670            return s2 == null
2671                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2672                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2673        }
2674
2675        if (s2 == null) {
2676            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2677        }
2678
2679        if (s1.length != s2.length) {
2680            return PackageManager.SIGNATURE_NO_MATCH;
2681        }
2682
2683        // Since both signature sets are of size 1, we can compare without HashSets.
2684        if (s1.length == 1) {
2685            return s1[0].equals(s2[0]) ?
2686                    PackageManager.SIGNATURE_MATCH :
2687                    PackageManager.SIGNATURE_NO_MATCH;
2688        }
2689
2690        HashSet<Signature> set1 = new HashSet<Signature>();
2691        for (Signature sig : s1) {
2692            set1.add(sig);
2693        }
2694        HashSet<Signature> set2 = new HashSet<Signature>();
2695        for (Signature sig : s2) {
2696            set2.add(sig);
2697        }
2698        // Make sure s2 contains all signatures in s1.
2699        if (set1.equals(set2)) {
2700            return PackageManager.SIGNATURE_MATCH;
2701        }
2702        return PackageManager.SIGNATURE_NO_MATCH;
2703    }
2704
2705    public String[] getPackagesForUid(int uid) {
2706        uid = UserHandle.getAppId(uid);
2707        // reader
2708        synchronized (mPackages) {
2709            Object obj = mSettings.getUserIdLPr(uid);
2710            if (obj instanceof SharedUserSetting) {
2711                final SharedUserSetting sus = (SharedUserSetting) obj;
2712                final int N = sus.packages.size();
2713                final String[] res = new String[N];
2714                final Iterator<PackageSetting> it = sus.packages.iterator();
2715                int i = 0;
2716                while (it.hasNext()) {
2717                    res[i++] = it.next().name;
2718                }
2719                return res;
2720            } else if (obj instanceof PackageSetting) {
2721                final PackageSetting ps = (PackageSetting) obj;
2722                return new String[] { ps.name };
2723            }
2724        }
2725        return null;
2726    }
2727
2728    public String getNameForUid(int uid) {
2729        // reader
2730        synchronized (mPackages) {
2731            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2732            if (obj instanceof SharedUserSetting) {
2733                final SharedUserSetting sus = (SharedUserSetting) obj;
2734                return sus.name + ":" + sus.userId;
2735            } else if (obj instanceof PackageSetting) {
2736                final PackageSetting ps = (PackageSetting) obj;
2737                return ps.name;
2738            }
2739        }
2740        return null;
2741    }
2742
2743    public int getUidForSharedUser(String sharedUserName) {
2744        if(sharedUserName == null) {
2745            return -1;
2746        }
2747        // reader
2748        synchronized (mPackages) {
2749            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2750            if (suid == null) {
2751                return -1;
2752            }
2753            return suid.userId;
2754        }
2755    }
2756
2757    public int getFlagsForUid(int uid) {
2758        synchronized (mPackages) {
2759            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2760            if (obj instanceof SharedUserSetting) {
2761                final SharedUserSetting sus = (SharedUserSetting) obj;
2762                return sus.pkgFlags;
2763            } else if (obj instanceof PackageSetting) {
2764                final PackageSetting ps = (PackageSetting) obj;
2765                return ps.pkgFlags;
2766            }
2767        }
2768        return 0;
2769    }
2770
2771    @Override
2772    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2773            int flags, int userId) {
2774        if (!sUserManager.exists(userId)) return null;
2775        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2776        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2777        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2778    }
2779
2780    @Override
2781    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2782            IntentFilter filter, int match, ComponentName activity) {
2783        final int userId = UserHandle.getCallingUserId();
2784        if (DEBUG_PREFERRED) {
2785            Log.v(TAG, "setLastChosenActivity intent=" + intent
2786                + " resolvedType=" + resolvedType
2787                + " flags=" + flags
2788                + " filter=" + filter
2789                + " match=" + match
2790                + " activity=" + activity);
2791            filter.dump(new PrintStreamPrinter(System.out), "    ");
2792        }
2793        intent.setComponent(null);
2794        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2795        // Find any earlier preferred or last chosen entries and nuke them
2796        findPreferredActivity(intent, resolvedType,
2797                flags, query, 0, false, true, false, userId);
2798        // Add the new activity as the last chosen for this filter
2799        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2800    }
2801
2802    @Override
2803    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2804        final int userId = UserHandle.getCallingUserId();
2805        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2806        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2807        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2808                false, false, false, userId);
2809    }
2810
2811    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2812            int flags, List<ResolveInfo> query, int userId) {
2813        if (query != null) {
2814            final int N = query.size();
2815            if (N == 1) {
2816                return query.get(0);
2817            } else if (N > 1) {
2818                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2819                // If there is more than one activity with the same priority,
2820                // then let the user decide between them.
2821                ResolveInfo r0 = query.get(0);
2822                ResolveInfo r1 = query.get(1);
2823                if (DEBUG_INTENT_MATCHING || debug) {
2824                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2825                            + r1.activityInfo.name + "=" + r1.priority);
2826                }
2827                // If the first activity has a higher priority, or a different
2828                // default, then it is always desireable to pick it.
2829                if (r0.priority != r1.priority
2830                        || r0.preferredOrder != r1.preferredOrder
2831                        || r0.isDefault != r1.isDefault) {
2832                    return query.get(0);
2833                }
2834                // If we have saved a preference for a preferred activity for
2835                // this Intent, use that.
2836                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2837                        flags, query, r0.priority, true, false, debug, userId);
2838                if (ri != null) {
2839                    return ri;
2840                }
2841                if (userId != 0) {
2842                    ri = new ResolveInfo(mResolveInfo);
2843                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2844                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2845                            ri.activityInfo.applicationInfo);
2846                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2847                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2848                    return ri;
2849                }
2850                return mResolveInfo;
2851            }
2852        }
2853        return null;
2854    }
2855
2856    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2857            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2858        final int N = query.size();
2859        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2860                .get(userId);
2861        // Get the list of persistent preferred activities that handle the intent
2862        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2863        List<PersistentPreferredActivity> pprefs = ppir != null
2864                ? ppir.queryIntent(intent, resolvedType,
2865                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2866                : null;
2867        if (pprefs != null && pprefs.size() > 0) {
2868            final int M = pprefs.size();
2869            for (int i=0; i<M; i++) {
2870                final PersistentPreferredActivity ppa = pprefs.get(i);
2871                if (DEBUG_PREFERRED || debug) {
2872                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2873                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2874                            + "\n  component=" + ppa.mComponent);
2875                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2876                }
2877                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2878                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2879                if (DEBUG_PREFERRED || debug) {
2880                    Slog.v(TAG, "Found persistent preferred activity:");
2881                    if (ai != null) {
2882                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2883                    } else {
2884                        Slog.v(TAG, "  null");
2885                    }
2886                }
2887                if (ai == null) {
2888                    // This previously registered persistent preferred activity
2889                    // component is no longer known. Ignore it and do NOT remove it.
2890                    continue;
2891                }
2892                for (int j=0; j<N; j++) {
2893                    final ResolveInfo ri = query.get(j);
2894                    if (!ri.activityInfo.applicationInfo.packageName
2895                            .equals(ai.applicationInfo.packageName)) {
2896                        continue;
2897                    }
2898                    if (!ri.activityInfo.name.equals(ai.name)) {
2899                        continue;
2900                    }
2901                    //  Found a persistent preference that can handle the intent.
2902                    if (DEBUG_PREFERRED || debug) {
2903                        Slog.v(TAG, "Returning persistent preferred activity: " +
2904                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
2905                    }
2906                    return ri;
2907                }
2908            }
2909        }
2910        return null;
2911    }
2912
2913    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
2914            List<ResolveInfo> query, int priority, boolean always,
2915            boolean removeMatches, boolean debug, int userId) {
2916        if (!sUserManager.exists(userId)) return null;
2917        // writer
2918        synchronized (mPackages) {
2919            if (intent.getSelector() != null) {
2920                intent = intent.getSelector();
2921            }
2922            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2923
2924            // Try to find a matching persistent preferred activity.
2925            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
2926                    debug, userId);
2927
2928            // If a persistent preferred activity matched, use it.
2929            if (pri != null) {
2930                return pri;
2931            }
2932
2933            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2934            // Get the list of preferred activities that handle the intent
2935            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
2936            List<PreferredActivity> prefs = pir != null
2937                    ? pir.queryIntent(intent, resolvedType,
2938                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2939                    : null;
2940            if (prefs != null && prefs.size() > 0) {
2941                // First figure out how good the original match set is.
2942                // We will only allow preferred activities that came
2943                // from the same match quality.
2944                int match = 0;
2945
2946                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
2947
2948                final int N = query.size();
2949                for (int j=0; j<N; j++) {
2950                    final ResolveInfo ri = query.get(j);
2951                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
2952                            + ": 0x" + Integer.toHexString(match));
2953                    if (ri.match > match) {
2954                        match = ri.match;
2955                    }
2956                }
2957
2958                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
2959                        + Integer.toHexString(match));
2960
2961                match &= IntentFilter.MATCH_CATEGORY_MASK;
2962                final int M = prefs.size();
2963                for (int i=0; i<M; i++) {
2964                    final PreferredActivity pa = prefs.get(i);
2965                    if (DEBUG_PREFERRED || debug) {
2966                        Slog.v(TAG, "Checking PreferredActivity ds="
2967                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
2968                                + "\n  component=" + pa.mPref.mComponent);
2969                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2970                    }
2971                    if (pa.mPref.mMatch != match) {
2972                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
2973                                + Integer.toHexString(pa.mPref.mMatch));
2974                        continue;
2975                    }
2976                    // If it's not an "always" type preferred activity and that's what we're
2977                    // looking for, skip it.
2978                    if (always && !pa.mPref.mAlways) {
2979                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
2980                        continue;
2981                    }
2982                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
2983                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2984                    if (DEBUG_PREFERRED || debug) {
2985                        Slog.v(TAG, "Found preferred activity:");
2986                        if (ai != null) {
2987                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2988                        } else {
2989                            Slog.v(TAG, "  null");
2990                        }
2991                    }
2992                    if (ai == null) {
2993                        // This previously registered preferred activity
2994                        // component is no longer known.  Most likely an update
2995                        // to the app was installed and in the new version this
2996                        // component no longer exists.  Clean it up by removing
2997                        // it from the preferred activities list, and skip it.
2998                        Slog.w(TAG, "Removing dangling preferred activity: "
2999                                + pa.mPref.mComponent);
3000                        pir.removeFilter(pa);
3001                        continue;
3002                    }
3003                    for (int j=0; j<N; j++) {
3004                        final ResolveInfo ri = query.get(j);
3005                        if (!ri.activityInfo.applicationInfo.packageName
3006                                .equals(ai.applicationInfo.packageName)) {
3007                            continue;
3008                        }
3009                        if (!ri.activityInfo.name.equals(ai.name)) {
3010                            continue;
3011                        }
3012
3013                        if (removeMatches) {
3014                            pir.removeFilter(pa);
3015                            if (DEBUG_PREFERRED) {
3016                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3017                            }
3018                            break;
3019                        }
3020
3021                        // Okay we found a previously set preferred or last chosen app.
3022                        // If the result set is different from when this
3023                        // was created, we need to clear it and re-ask the
3024                        // user their preference, if we're looking for an "always" type entry.
3025                        if (always && !pa.mPref.sameSet(query, priority)) {
3026                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3027                                    + intent + " type " + resolvedType);
3028                            if (DEBUG_PREFERRED) {
3029                                Slog.v(TAG, "Removing preferred activity since set changed "
3030                                        + pa.mPref.mComponent);
3031                            }
3032                            pir.removeFilter(pa);
3033                            // Re-add the filter as a "last chosen" entry (!always)
3034                            PreferredActivity lastChosen = new PreferredActivity(
3035                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3036                            pir.addFilter(lastChosen);
3037                            mSettings.writePackageRestrictionsLPr(userId);
3038                            return null;
3039                        }
3040
3041                        // Yay! Either the set matched or we're looking for the last chosen
3042                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3043                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3044                        mSettings.writePackageRestrictionsLPr(userId);
3045                        return ri;
3046                    }
3047                }
3048            }
3049            mSettings.writePackageRestrictionsLPr(userId);
3050        }
3051        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3052        return null;
3053    }
3054
3055    @Override
3056    public List<ResolveInfo> queryIntentActivities(Intent intent,
3057            String resolvedType, int flags, int userId) {
3058        if (!sUserManager.exists(userId)) return Collections.emptyList();
3059        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3060        ComponentName comp = intent.getComponent();
3061        if (comp == null) {
3062            if (intent.getSelector() != null) {
3063                intent = intent.getSelector();
3064                comp = intent.getComponent();
3065            }
3066        }
3067
3068        if (comp != null) {
3069            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3070            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3071            if (ai != null) {
3072                final ResolveInfo ri = new ResolveInfo();
3073                ri.activityInfo = ai;
3074                list.add(ri);
3075            }
3076            return list;
3077        }
3078
3079        // reader
3080        synchronized (mPackages) {
3081            final String pkgName = intent.getPackage();
3082            if (pkgName == null) {
3083                return mActivities.queryIntent(intent, resolvedType, flags, userId);
3084            }
3085            final PackageParser.Package pkg = mPackages.get(pkgName);
3086            if (pkg != null) {
3087                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3088                        pkg.activities, userId);
3089            }
3090            return new ArrayList<ResolveInfo>();
3091        }
3092    }
3093
3094    @Override
3095    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3096            Intent[] specifics, String[] specificTypes, Intent intent,
3097            String resolvedType, int flags, int userId) {
3098        if (!sUserManager.exists(userId)) return Collections.emptyList();
3099        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3100                "query intent activity options");
3101        final String resultsAction = intent.getAction();
3102
3103        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3104                | PackageManager.GET_RESOLVED_FILTER, userId);
3105
3106        if (DEBUG_INTENT_MATCHING) {
3107            Log.v(TAG, "Query " + intent + ": " + results);
3108        }
3109
3110        int specificsPos = 0;
3111        int N;
3112
3113        // todo: note that the algorithm used here is O(N^2).  This
3114        // isn't a problem in our current environment, but if we start running
3115        // into situations where we have more than 5 or 10 matches then this
3116        // should probably be changed to something smarter...
3117
3118        // First we go through and resolve each of the specific items
3119        // that were supplied, taking care of removing any corresponding
3120        // duplicate items in the generic resolve list.
3121        if (specifics != null) {
3122            for (int i=0; i<specifics.length; i++) {
3123                final Intent sintent = specifics[i];
3124                if (sintent == null) {
3125                    continue;
3126                }
3127
3128                if (DEBUG_INTENT_MATCHING) {
3129                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3130                }
3131
3132                String action = sintent.getAction();
3133                if (resultsAction != null && resultsAction.equals(action)) {
3134                    // If this action was explicitly requested, then don't
3135                    // remove things that have it.
3136                    action = null;
3137                }
3138
3139                ResolveInfo ri = null;
3140                ActivityInfo ai = null;
3141
3142                ComponentName comp = sintent.getComponent();
3143                if (comp == null) {
3144                    ri = resolveIntent(
3145                        sintent,
3146                        specificTypes != null ? specificTypes[i] : null,
3147                            flags, userId);
3148                    if (ri == null) {
3149                        continue;
3150                    }
3151                    if (ri == mResolveInfo) {
3152                        // ACK!  Must do something better with this.
3153                    }
3154                    ai = ri.activityInfo;
3155                    comp = new ComponentName(ai.applicationInfo.packageName,
3156                            ai.name);
3157                } else {
3158                    ai = getActivityInfo(comp, flags, userId);
3159                    if (ai == null) {
3160                        continue;
3161                    }
3162                }
3163
3164                // Look for any generic query activities that are duplicates
3165                // of this specific one, and remove them from the results.
3166                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3167                N = results.size();
3168                int j;
3169                for (j=specificsPos; j<N; j++) {
3170                    ResolveInfo sri = results.get(j);
3171                    if ((sri.activityInfo.name.equals(comp.getClassName())
3172                            && sri.activityInfo.applicationInfo.packageName.equals(
3173                                    comp.getPackageName()))
3174                        || (action != null && sri.filter.matchAction(action))) {
3175                        results.remove(j);
3176                        if (DEBUG_INTENT_MATCHING) Log.v(
3177                            TAG, "Removing duplicate item from " + j
3178                            + " due to specific " + specificsPos);
3179                        if (ri == null) {
3180                            ri = sri;
3181                        }
3182                        j--;
3183                        N--;
3184                    }
3185                }
3186
3187                // Add this specific item to its proper place.
3188                if (ri == null) {
3189                    ri = new ResolveInfo();
3190                    ri.activityInfo = ai;
3191                }
3192                results.add(specificsPos, ri);
3193                ri.specificIndex = i;
3194                specificsPos++;
3195            }
3196        }
3197
3198        // Now we go through the remaining generic results and remove any
3199        // duplicate actions that are found here.
3200        N = results.size();
3201        for (int i=specificsPos; i<N-1; i++) {
3202            final ResolveInfo rii = results.get(i);
3203            if (rii.filter == null) {
3204                continue;
3205            }
3206
3207            // Iterate over all of the actions of this result's intent
3208            // filter...  typically this should be just one.
3209            final Iterator<String> it = rii.filter.actionsIterator();
3210            if (it == null) {
3211                continue;
3212            }
3213            while (it.hasNext()) {
3214                final String action = it.next();
3215                if (resultsAction != null && resultsAction.equals(action)) {
3216                    // If this action was explicitly requested, then don't
3217                    // remove things that have it.
3218                    continue;
3219                }
3220                for (int j=i+1; j<N; j++) {
3221                    final ResolveInfo rij = results.get(j);
3222                    if (rij.filter != null && rij.filter.hasAction(action)) {
3223                        results.remove(j);
3224                        if (DEBUG_INTENT_MATCHING) Log.v(
3225                            TAG, "Removing duplicate item from " + j
3226                            + " due to action " + action + " at " + i);
3227                        j--;
3228                        N--;
3229                    }
3230                }
3231            }
3232
3233            // If the caller didn't request filter information, drop it now
3234            // so we don't have to marshall/unmarshall it.
3235            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3236                rii.filter = null;
3237            }
3238        }
3239
3240        // Filter out the caller activity if so requested.
3241        if (caller != null) {
3242            N = results.size();
3243            for (int i=0; i<N; i++) {
3244                ActivityInfo ainfo = results.get(i).activityInfo;
3245                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3246                        && caller.getClassName().equals(ainfo.name)) {
3247                    results.remove(i);
3248                    break;
3249                }
3250            }
3251        }
3252
3253        // If the caller didn't request filter information,
3254        // drop them now so we don't have to
3255        // marshall/unmarshall it.
3256        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3257            N = results.size();
3258            for (int i=0; i<N; i++) {
3259                results.get(i).filter = null;
3260            }
3261        }
3262
3263        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3264        return results;
3265    }
3266
3267    @Override
3268    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3269            int userId) {
3270        if (!sUserManager.exists(userId)) return Collections.emptyList();
3271        ComponentName comp = intent.getComponent();
3272        if (comp == null) {
3273            if (intent.getSelector() != null) {
3274                intent = intent.getSelector();
3275                comp = intent.getComponent();
3276            }
3277        }
3278        if (comp != null) {
3279            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3280            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3281            if (ai != null) {
3282                ResolveInfo ri = new ResolveInfo();
3283                ri.activityInfo = ai;
3284                list.add(ri);
3285            }
3286            return list;
3287        }
3288
3289        // reader
3290        synchronized (mPackages) {
3291            String pkgName = intent.getPackage();
3292            if (pkgName == null) {
3293                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3294            }
3295            final PackageParser.Package pkg = mPackages.get(pkgName);
3296            if (pkg != null) {
3297                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3298                        userId);
3299            }
3300            return null;
3301        }
3302    }
3303
3304    @Override
3305    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3306        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3307        if (!sUserManager.exists(userId)) return null;
3308        if (query != null) {
3309            if (query.size() >= 1) {
3310                // If there is more than one service with the same priority,
3311                // just arbitrarily pick the first one.
3312                return query.get(0);
3313            }
3314        }
3315        return null;
3316    }
3317
3318    @Override
3319    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3320            int userId) {
3321        if (!sUserManager.exists(userId)) return Collections.emptyList();
3322        ComponentName comp = intent.getComponent();
3323        if (comp == null) {
3324            if (intent.getSelector() != null) {
3325                intent = intent.getSelector();
3326                comp = intent.getComponent();
3327            }
3328        }
3329        if (comp != null) {
3330            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3331            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3332            if (si != null) {
3333                final ResolveInfo ri = new ResolveInfo();
3334                ri.serviceInfo = si;
3335                list.add(ri);
3336            }
3337            return list;
3338        }
3339
3340        // reader
3341        synchronized (mPackages) {
3342            String pkgName = intent.getPackage();
3343            if (pkgName == null) {
3344                return mServices.queryIntent(intent, resolvedType, flags, userId);
3345            }
3346            final PackageParser.Package pkg = mPackages.get(pkgName);
3347            if (pkg != null) {
3348                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3349                        userId);
3350            }
3351            return null;
3352        }
3353    }
3354
3355    @Override
3356    public List<ResolveInfo> queryIntentContentProviders(
3357            Intent intent, String resolvedType, int flags, int userId) {
3358        if (!sUserManager.exists(userId)) return Collections.emptyList();
3359        ComponentName comp = intent.getComponent();
3360        if (comp == null) {
3361            if (intent.getSelector() != null) {
3362                intent = intent.getSelector();
3363                comp = intent.getComponent();
3364            }
3365        }
3366        if (comp != null) {
3367            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3368            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3369            if (pi != null) {
3370                final ResolveInfo ri = new ResolveInfo();
3371                ri.providerInfo = pi;
3372                list.add(ri);
3373            }
3374            return list;
3375        }
3376
3377        // reader
3378        synchronized (mPackages) {
3379            String pkgName = intent.getPackage();
3380            if (pkgName == null) {
3381                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3382            }
3383            final PackageParser.Package pkg = mPackages.get(pkgName);
3384            if (pkg != null) {
3385                return mProviders.queryIntentForPackage(
3386                        intent, resolvedType, flags, pkg.providers, userId);
3387            }
3388            return null;
3389        }
3390    }
3391
3392    @Override
3393    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3394        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3395
3396        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3397
3398        // writer
3399        synchronized (mPackages) {
3400            ArrayList<PackageInfo> list;
3401            if (listUninstalled) {
3402                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3403                for (PackageSetting ps : mSettings.mPackages.values()) {
3404                    PackageInfo pi;
3405                    if (ps.pkg != null) {
3406                        pi = generatePackageInfo(ps.pkg, flags, userId);
3407                    } else {
3408                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3409                    }
3410                    if (pi != null) {
3411                        list.add(pi);
3412                    }
3413                }
3414            } else {
3415                list = new ArrayList<PackageInfo>(mPackages.size());
3416                for (PackageParser.Package p : mPackages.values()) {
3417                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3418                    if (pi != null) {
3419                        list.add(pi);
3420                    }
3421                }
3422            }
3423
3424            return new ParceledListSlice<PackageInfo>(list);
3425        }
3426    }
3427
3428    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3429            String[] permissions, boolean[] tmp, int flags, int userId) {
3430        int numMatch = 0;
3431        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3432        for (int i=0; i<permissions.length; i++) {
3433            if (gp.grantedPermissions.contains(permissions[i])) {
3434                tmp[i] = true;
3435                numMatch++;
3436            } else {
3437                tmp[i] = false;
3438            }
3439        }
3440        if (numMatch == 0) {
3441            return;
3442        }
3443        PackageInfo pi;
3444        if (ps.pkg != null) {
3445            pi = generatePackageInfo(ps.pkg, flags, userId);
3446        } else {
3447            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3448        }
3449        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3450            if (numMatch == permissions.length) {
3451                pi.requestedPermissions = permissions;
3452            } else {
3453                pi.requestedPermissions = new String[numMatch];
3454                numMatch = 0;
3455                for (int i=0; i<permissions.length; i++) {
3456                    if (tmp[i]) {
3457                        pi.requestedPermissions[numMatch] = permissions[i];
3458                        numMatch++;
3459                    }
3460                }
3461            }
3462        }
3463        list.add(pi);
3464    }
3465
3466    @Override
3467    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3468            String[] permissions, int flags, int userId) {
3469        if (!sUserManager.exists(userId)) return null;
3470        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3471
3472        // writer
3473        synchronized (mPackages) {
3474            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3475            boolean[] tmpBools = new boolean[permissions.length];
3476            if (listUninstalled) {
3477                for (PackageSetting ps : mSettings.mPackages.values()) {
3478                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3479                }
3480            } else {
3481                for (PackageParser.Package pkg : mPackages.values()) {
3482                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3483                    if (ps != null) {
3484                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3485                                userId);
3486                    }
3487                }
3488            }
3489
3490            return new ParceledListSlice<PackageInfo>(list);
3491        }
3492    }
3493
3494    @Override
3495    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3496        if (!sUserManager.exists(userId)) return null;
3497        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3498
3499        // writer
3500        synchronized (mPackages) {
3501            ArrayList<ApplicationInfo> list;
3502            if (listUninstalled) {
3503                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3504                for (PackageSetting ps : mSettings.mPackages.values()) {
3505                    ApplicationInfo ai;
3506                    if (ps.pkg != null) {
3507                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3508                                ps.readUserState(userId), userId);
3509                    } else {
3510                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3511                    }
3512                    if (ai != null) {
3513                        list.add(ai);
3514                    }
3515                }
3516            } else {
3517                list = new ArrayList<ApplicationInfo>(mPackages.size());
3518                for (PackageParser.Package p : mPackages.values()) {
3519                    if (p.mExtras != null) {
3520                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3521                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3522                        if (ai != null) {
3523                            list.add(ai);
3524                        }
3525                    }
3526                }
3527            }
3528
3529            return new ParceledListSlice<ApplicationInfo>(list);
3530        }
3531    }
3532
3533    public List<ApplicationInfo> getPersistentApplications(int flags) {
3534        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3535
3536        // reader
3537        synchronized (mPackages) {
3538            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3539            final int userId = UserHandle.getCallingUserId();
3540            while (i.hasNext()) {
3541                final PackageParser.Package p = i.next();
3542                if (p.applicationInfo != null
3543                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3544                        && (!mSafeMode || isSystemApp(p))) {
3545                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3546                    if (ps != null) {
3547                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3548                                ps.readUserState(userId), userId);
3549                        if (ai != null) {
3550                            finalList.add(ai);
3551                        }
3552                    }
3553                }
3554            }
3555        }
3556
3557        return finalList;
3558    }
3559
3560    @Override
3561    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3562        if (!sUserManager.exists(userId)) return null;
3563        // reader
3564        synchronized (mPackages) {
3565            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3566            PackageSetting ps = provider != null
3567                    ? mSettings.mPackages.get(provider.owner.packageName)
3568                    : null;
3569            return ps != null
3570                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3571                    && (!mSafeMode || (provider.info.applicationInfo.flags
3572                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3573                    ? PackageParser.generateProviderInfo(provider, flags,
3574                            ps.readUserState(userId), userId)
3575                    : null;
3576        }
3577    }
3578
3579    /**
3580     * @deprecated
3581     */
3582    @Deprecated
3583    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3584        // reader
3585        synchronized (mPackages) {
3586            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3587                    .entrySet().iterator();
3588            final int userId = UserHandle.getCallingUserId();
3589            while (i.hasNext()) {
3590                Map.Entry<String, PackageParser.Provider> entry = i.next();
3591                PackageParser.Provider p = entry.getValue();
3592                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3593
3594                if (ps != null && p.syncable
3595                        && (!mSafeMode || (p.info.applicationInfo.flags
3596                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3597                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3598                            ps.readUserState(userId), userId);
3599                    if (info != null) {
3600                        outNames.add(entry.getKey());
3601                        outInfo.add(info);
3602                    }
3603                }
3604            }
3605        }
3606    }
3607
3608    public List<ProviderInfo> queryContentProviders(String processName,
3609            int uid, int flags) {
3610        ArrayList<ProviderInfo> finalList = null;
3611        // reader
3612        synchronized (mPackages) {
3613            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3614            final int userId = processName != null ?
3615                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3616            while (i.hasNext()) {
3617                final PackageParser.Provider p = i.next();
3618                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3619                if (ps != null && p.info.authority != null
3620                        && (processName == null
3621                                || (p.info.processName.equals(processName)
3622                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3623                        && mSettings.isEnabledLPr(p.info, flags, userId)
3624                        && (!mSafeMode
3625                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3626                    if (finalList == null) {
3627                        finalList = new ArrayList<ProviderInfo>(3);
3628                    }
3629                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3630                            ps.readUserState(userId), userId);
3631                    if (info != null) {
3632                        finalList.add(info);
3633                    }
3634                }
3635            }
3636        }
3637
3638        if (finalList != null) {
3639            Collections.sort(finalList, mProviderInitOrderSorter);
3640        }
3641
3642        return finalList;
3643    }
3644
3645    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3646            int flags) {
3647        // reader
3648        synchronized (mPackages) {
3649            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3650            return PackageParser.generateInstrumentationInfo(i, flags);
3651        }
3652    }
3653
3654    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3655            int flags) {
3656        ArrayList<InstrumentationInfo> finalList =
3657            new ArrayList<InstrumentationInfo>();
3658
3659        // reader
3660        synchronized (mPackages) {
3661            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3662            while (i.hasNext()) {
3663                final PackageParser.Instrumentation p = i.next();
3664                if (targetPackage == null
3665                        || targetPackage.equals(p.info.targetPackage)) {
3666                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3667                            flags);
3668                    if (ii != null) {
3669                        finalList.add(ii);
3670                    }
3671                }
3672            }
3673        }
3674
3675        return finalList;
3676    }
3677
3678    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3679        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3680        if (overlays == null) {
3681            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3682            return;
3683        }
3684        for (PackageParser.Package opkg : overlays.values()) {
3685            // Not much to do if idmap fails: we already logged the error
3686            // and we certainly don't want to abort installation of pkg simply
3687            // because an overlay didn't fit properly. For these reasons,
3688            // ignore the return value of createIdmapForPackagePairLI.
3689            createIdmapForPackagePairLI(pkg, opkg);
3690        }
3691    }
3692
3693    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3694            PackageParser.Package opkg) {
3695        if (!opkg.mTrustedOverlay) {
3696            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3697                    opkg.mScanPath + ": overlay not trusted");
3698            return false;
3699        }
3700        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3701        if (overlaySet == null) {
3702            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3703                    opkg.mScanPath + " but target package has no known overlays");
3704            return false;
3705        }
3706        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3707        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3708            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3709            return false;
3710        }
3711        PackageParser.Package[] overlayArray =
3712            overlaySet.values().toArray(new PackageParser.Package[0]);
3713        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3714            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3715                return p1.mOverlayPriority - p2.mOverlayPriority;
3716            }
3717        };
3718        Arrays.sort(overlayArray, cmp);
3719
3720        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3721        int i = 0;
3722        for (PackageParser.Package p : overlayArray) {
3723            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3724        }
3725        return true;
3726    }
3727
3728    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3729        String[] files = dir.list();
3730        if (files == null) {
3731            Log.d(TAG, "No files in app dir " + dir);
3732            return;
3733        }
3734
3735        if (DEBUG_PACKAGE_SCANNING) {
3736            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3737                    + " flags=0x" + Integer.toHexString(flags));
3738        }
3739
3740        int i;
3741        for (i=0; i<files.length; i++) {
3742            File file = new File(dir, files[i]);
3743            if (!isPackageFilename(files[i])) {
3744                // Ignore entries which are not apk's
3745                continue;
3746            }
3747            PackageParser.Package pkg = scanPackageLI(file,
3748                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3749            // Don't mess around with apps in system partition.
3750            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3751                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3752                // Delete the apk
3753                Slog.w(TAG, "Cleaning up failed install of " + file);
3754                file.delete();
3755            }
3756        }
3757    }
3758
3759    private static File getSettingsProblemFile() {
3760        File dataDir = Environment.getDataDirectory();
3761        File systemDir = new File(dataDir, "system");
3762        File fname = new File(systemDir, "uiderrors.txt");
3763        return fname;
3764    }
3765
3766    static void reportSettingsProblem(int priority, String msg) {
3767        try {
3768            File fname = getSettingsProblemFile();
3769            FileOutputStream out = new FileOutputStream(fname, true);
3770            PrintWriter pw = new FastPrintWriter(out);
3771            SimpleDateFormat formatter = new SimpleDateFormat();
3772            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3773            pw.println(dateString + ": " + msg);
3774            pw.close();
3775            FileUtils.setPermissions(
3776                    fname.toString(),
3777                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3778                    -1, -1);
3779        } catch (java.io.IOException e) {
3780        }
3781        Slog.println(priority, TAG, msg);
3782    }
3783
3784    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3785            PackageParser.Package pkg, File srcFile, int parseFlags) {
3786        if (GET_CERTIFICATES) {
3787            if (ps != null
3788                    && ps.codePath.equals(srcFile)
3789                    && ps.timeStamp == srcFile.lastModified()) {
3790                if (ps.signatures.mSignatures != null
3791                        && ps.signatures.mSignatures.length != 0) {
3792                    // Optimization: reuse the existing cached certificates
3793                    // if the package appears to be unchanged.
3794                    pkg.mSignatures = ps.signatures.mSignatures;
3795                    return true;
3796                }
3797
3798                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3799            } else {
3800                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3801            }
3802
3803            if (!pp.collectCertificates(pkg, parseFlags)) {
3804                mLastScanError = pp.getParseError();
3805                return false;
3806            }
3807        }
3808        return true;
3809    }
3810
3811    /*
3812     *  Scan a package and return the newly parsed package.
3813     *  Returns null in case of errors and the error code is stored in mLastScanError
3814     */
3815    private PackageParser.Package scanPackageLI(File scanFile,
3816            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3817        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3818        String scanPath = scanFile.getPath();
3819        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3820        parseFlags |= mDefParseFlags;
3821        PackageParser pp = new PackageParser(scanPath);
3822        pp.setSeparateProcesses(mSeparateProcesses);
3823        pp.setOnlyCoreApps(mOnlyCore);
3824        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3825                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3826
3827        if (pkg == null) {
3828            mLastScanError = pp.getParseError();
3829            return null;
3830        }
3831
3832        PackageSetting ps = null;
3833        PackageSetting updatedPkg;
3834        // reader
3835        synchronized (mPackages) {
3836            // Look to see if we already know about this package.
3837            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3838            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3839                // This package has been renamed to its original name.  Let's
3840                // use that.
3841                ps = mSettings.peekPackageLPr(oldName);
3842            }
3843            // If there was no original package, see one for the real package name.
3844            if (ps == null) {
3845                ps = mSettings.peekPackageLPr(pkg.packageName);
3846            }
3847            // Check to see if this package could be hiding/updating a system
3848            // package.  Must look for it either under the original or real
3849            // package name depending on our state.
3850            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3851            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3852        }
3853        boolean updatedPkgBetter = false;
3854        // First check if this is a system package that may involve an update
3855        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3856            if (ps != null && !ps.codePath.equals(scanFile)) {
3857                // The path has changed from what was last scanned...  check the
3858                // version of the new path against what we have stored to determine
3859                // what to do.
3860                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3861                if (pkg.mVersionCode < ps.versionCode) {
3862                    // The system package has been updated and the code path does not match
3863                    // Ignore entry. Skip it.
3864                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3865                            + " ignored: updated version " + ps.versionCode
3866                            + " better than this " + pkg.mVersionCode);
3867                    if (!updatedPkg.codePath.equals(scanFile)) {
3868                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3869                                + ps.name + " changing from " + updatedPkg.codePathString
3870                                + " to " + scanFile);
3871                        updatedPkg.codePath = scanFile;
3872                        updatedPkg.codePathString = scanFile.toString();
3873                        // This is the point at which we know that the system-disk APK
3874                        // for this package has moved during a reboot (e.g. due to an OTA),
3875                        // so we need to reevaluate it for privilege policy.
3876                        if (locationIsPrivileged(scanFile)) {
3877                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3878                        }
3879                    }
3880                    updatedPkg.pkg = pkg;
3881                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3882                    return null;
3883                } else {
3884                    // The current app on the system partion is better than
3885                    // what we have updated to on the data partition; switch
3886                    // back to the system partition version.
3887                    // At this point, its safely assumed that package installation for
3888                    // apps in system partition will go through. If not there won't be a working
3889                    // version of the app
3890                    // writer
3891                    synchronized (mPackages) {
3892                        // Just remove the loaded entries from package lists.
3893                        mPackages.remove(ps.name);
3894                    }
3895                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3896                            + "reverting from " + ps.codePathString
3897                            + ": new version " + pkg.mVersionCode
3898                            + " better than installed " + ps.versionCode);
3899
3900                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3901                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3902                    synchronized (mInstallLock) {
3903                        args.cleanUpResourcesLI();
3904                    }
3905                    synchronized (mPackages) {
3906                        mSettings.enableSystemPackageLPw(ps.name);
3907                    }
3908                    updatedPkgBetter = true;
3909                }
3910            }
3911        }
3912
3913        if (updatedPkg != null) {
3914            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3915            // initially
3916            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3917
3918            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
3919            // flag set initially
3920            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3921                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
3922            }
3923        }
3924        // Verify certificates against what was last scanned
3925        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3926            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3927            return null;
3928        }
3929
3930        /*
3931         * A new system app appeared, but we already had a non-system one of the
3932         * same name installed earlier.
3933         */
3934        boolean shouldHideSystemApp = false;
3935        if (updatedPkg == null && ps != null
3936                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3937            /*
3938             * Check to make sure the signatures match first. If they don't,
3939             * wipe the installed application and its data.
3940             */
3941            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3942                    != PackageManager.SIGNATURE_MATCH) {
3943                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
3944                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
3945                ps = null;
3946            } else {
3947                /*
3948                 * If the newly-added system app is an older version than the
3949                 * already installed version, hide it. It will be scanned later
3950                 * and re-added like an update.
3951                 */
3952                if (pkg.mVersionCode < ps.versionCode) {
3953                    shouldHideSystemApp = true;
3954                } else {
3955                    /*
3956                     * The newly found system app is a newer version that the
3957                     * one previously installed. Simply remove the
3958                     * already-installed application and replace it with our own
3959                     * while keeping the application data.
3960                     */
3961                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3962                            + ps.codePathString + ": new version " + pkg.mVersionCode
3963                            + " better than installed " + ps.versionCode);
3964                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3965                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3966                    synchronized (mInstallLock) {
3967                        args.cleanUpResourcesLI();
3968                    }
3969                }
3970            }
3971        }
3972
3973        // The apk is forward locked (not public) if its code and resources
3974        // are kept in different files. (except for app in either system or
3975        // vendor path).
3976        // TODO grab this value from PackageSettings
3977        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3978            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3979                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3980            }
3981        }
3982
3983        String codePath = null;
3984        String resPath = null;
3985        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
3986            if (ps != null && ps.resourcePathString != null) {
3987                resPath = ps.resourcePathString;
3988            } else {
3989                // Should not happen at all. Just log an error.
3990                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3991            }
3992        } else {
3993            resPath = pkg.mScanPath;
3994        }
3995
3996        codePath = pkg.mScanPath;
3997        // Set application objects path explicitly.
3998        setApplicationInfoPaths(pkg, codePath, resPath);
3999        // Note that we invoke the following method only if we are about to unpack an application
4000        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4001                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4002
4003        /*
4004         * If the system app should be overridden by a previously installed
4005         * data, hide the system app now and let the /data/app scan pick it up
4006         * again.
4007         */
4008        if (shouldHideSystemApp) {
4009            synchronized (mPackages) {
4010                /*
4011                 * We have to grant systems permissions before we hide, because
4012                 * grantPermissions will assume the package update is trying to
4013                 * expand its permissions.
4014                 */
4015                grantPermissionsLPw(pkg, true);
4016                mSettings.disableSystemPackageLPw(pkg.packageName);
4017            }
4018        }
4019
4020        return scannedPkg;
4021    }
4022
4023    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4024            String destResPath) {
4025        pkg.mPath = pkg.mScanPath = destCodePath;
4026        pkg.applicationInfo.sourceDir = destCodePath;
4027        pkg.applicationInfo.publicSourceDir = destResPath;
4028    }
4029
4030    private static String fixProcessName(String defProcessName,
4031            String processName, int uid) {
4032        if (processName == null) {
4033            return defProcessName;
4034        }
4035        return processName;
4036    }
4037
4038    private boolean verifySignaturesLP(PackageSetting pkgSetting,
4039            PackageParser.Package pkg) {
4040        if (pkgSetting.signatures.mSignatures != null) {
4041            // Already existing package. Make sure signatures match
4042            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
4043                PackageManager.SIGNATURE_MATCH) {
4044                    Slog.e(TAG, "Package " + pkg.packageName
4045                            + " signatures do not match the previously installed version; ignoring!");
4046                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4047                    return false;
4048                }
4049        }
4050        // Check for shared user signatures
4051        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4052            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4053                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4054                Slog.e(TAG, "Package " + pkg.packageName
4055                        + " has no signatures that match those in shared user "
4056                        + pkgSetting.sharedUser.name + "; ignoring!");
4057                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4058                return false;
4059            }
4060        }
4061        return true;
4062    }
4063
4064    /**
4065     * Enforces that only the system UID or root's UID can call a method exposed
4066     * via Binder.
4067     *
4068     * @param message used as message if SecurityException is thrown
4069     * @throws SecurityException if the caller is not system or root
4070     */
4071    private static final void enforceSystemOrRoot(String message) {
4072        final int uid = Binder.getCallingUid();
4073        if (uid != Process.SYSTEM_UID && uid != 0) {
4074            throw new SecurityException(message);
4075        }
4076    }
4077
4078    public void performBootDexOpt() {
4079        HashSet<PackageParser.Package> pkgs = null;
4080        synchronized (mPackages) {
4081            pkgs = mDeferredDexOpt;
4082            mDeferredDexOpt = null;
4083        }
4084        if (pkgs != null) {
4085            int i = 0;
4086            for (PackageParser.Package pkg : pkgs) {
4087                if (!isFirstBoot()) {
4088                    i++;
4089                    try {
4090                        ActivityManagerNative.getDefault().showBootMessage(
4091                                mContext.getResources().getString(
4092                                        com.android.internal.R.string.android_upgrading_apk,
4093                                        i, pkgs.size()), true);
4094                    } catch (RemoteException e) {
4095                    }
4096                }
4097                PackageParser.Package p = pkg;
4098                synchronized (mInstallLock) {
4099                    if (!p.mDidDexOpt) {
4100                        performDexOptLI(p, false, false, true);
4101                    }
4102                }
4103            }
4104        }
4105    }
4106
4107    public boolean performDexOpt(String packageName) {
4108        enforceSystemOrRoot("Only the system can request dexopt be performed");
4109
4110        if (!mNoDexOpt) {
4111            return false;
4112        }
4113
4114        PackageParser.Package p;
4115        synchronized (mPackages) {
4116            p = mPackages.get(packageName);
4117            if (p == null || p.mDidDexOpt) {
4118                return false;
4119            }
4120        }
4121        synchronized (mInstallLock) {
4122            return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED;
4123        }
4124    }
4125
4126    private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer,
4127            HashSet<String> done) {
4128        for (int i=0; i<libs.size(); i++) {
4129            PackageParser.Package libPkg;
4130            String libName;
4131            synchronized (mPackages) {
4132                libName = libs.get(i);
4133                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4134                if (lib != null && lib.apk != null) {
4135                    libPkg = mPackages.get(lib.apk);
4136                } else {
4137                    libPkg = null;
4138                }
4139            }
4140            if (libPkg != null && !done.contains(libName)) {
4141                performDexOptLI(libPkg, forceDex, defer, done);
4142            }
4143        }
4144    }
4145
4146    static final int DEX_OPT_SKIPPED = 0;
4147    static final int DEX_OPT_PERFORMED = 1;
4148    static final int DEX_OPT_DEFERRED = 2;
4149    static final int DEX_OPT_FAILED = -1;
4150
4151    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4152            HashSet<String> done) {
4153        boolean performed = false;
4154        if (done != null) {
4155            done.add(pkg.packageName);
4156            if (pkg.usesLibraries != null) {
4157                performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done);
4158            }
4159            if (pkg.usesOptionalLibraries != null) {
4160                performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done);
4161            }
4162        }
4163        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4164            String path = pkg.mScanPath;
4165            int ret = 0;
4166            try {
4167                if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, pkg.packageName,
4168                                                                             defer)) {
4169                    if (!forceDex && defer) {
4170                        if (mDeferredDexOpt == null) {
4171                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4172                        }
4173                        mDeferredDexOpt.add(pkg);
4174                        return DEX_OPT_DEFERRED;
4175                    } else {
4176                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4177                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4178                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4179                                                pkg.packageName);
4180                        pkg.mDidDexOpt = true;
4181                        performed = true;
4182                    }
4183                }
4184            } catch (FileNotFoundException e) {
4185                Slog.w(TAG, "Apk not found for dexopt: " + path);
4186                ret = -1;
4187            } catch (IOException e) {
4188                Slog.w(TAG, "IOException reading apk: " + path, e);
4189                ret = -1;
4190            } catch (dalvik.system.StaleDexCacheError e) {
4191                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4192                ret = -1;
4193            } catch (Exception e) {
4194                Slog.w(TAG, "Exception when doing dexopt : ", e);
4195                ret = -1;
4196            }
4197            if (ret < 0) {
4198                //error from installer
4199                return DEX_OPT_FAILED;
4200            }
4201        }
4202
4203        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4204    }
4205
4206    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4207            boolean inclDependencies) {
4208        HashSet<String> done;
4209        boolean performed = false;
4210        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4211            done = new HashSet<String>();
4212            done.add(pkg.packageName);
4213        } else {
4214            done = null;
4215        }
4216        return performDexOptLI(pkg, forceDex, defer, done);
4217    }
4218
4219    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4220        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4221            Slog.w(TAG, "Unable to update from " + oldPkg.name
4222                    + " to " + newPkg.packageName
4223                    + ": old package not in system partition");
4224            return false;
4225        } else if (mPackages.get(oldPkg.name) != null) {
4226            Slog.w(TAG, "Unable to update from " + oldPkg.name
4227                    + " to " + newPkg.packageName
4228                    + ": old package still exists");
4229            return false;
4230        }
4231        return true;
4232    }
4233
4234    File getDataPathForUser(int userId) {
4235        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4236    }
4237
4238    private File getDataPathForPackage(String packageName, int userId) {
4239        /*
4240         * Until we fully support multiple users, return the directory we
4241         * previously would have. The PackageManagerTests will need to be
4242         * revised when this is changed back..
4243         */
4244        if (userId == 0) {
4245            return new File(mAppDataDir, packageName);
4246        } else {
4247            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4248                + File.separator + packageName);
4249        }
4250    }
4251
4252    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4253        int[] users = sUserManager.getUserIds();
4254        int res = mInstaller.install(packageName, uid, uid, seinfo);
4255        if (res < 0) {
4256            return res;
4257        }
4258        for (int user : users) {
4259            if (user != 0) {
4260                res = mInstaller.createUserData(packageName,
4261                        UserHandle.getUid(user, uid), user, seinfo);
4262                if (res < 0) {
4263                    return res;
4264                }
4265            }
4266        }
4267        return res;
4268    }
4269
4270    private int removeDataDirsLI(String packageName) {
4271        int[] users = sUserManager.getUserIds();
4272        int res = 0;
4273        for (int user : users) {
4274            int resInner = mInstaller.remove(packageName, user);
4275            if (resInner < 0) {
4276                res = resInner;
4277            }
4278        }
4279
4280        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4281        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4282        if (!nativeLibraryFile.delete()) {
4283            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4284        }
4285
4286        return res;
4287    }
4288
4289    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4290            PackageParser.Package changingLib) {
4291        if (file.path != null) {
4292            mTmpSharedLibraries[num] = file.path;
4293            return num+1;
4294        }
4295        PackageParser.Package p = mPackages.get(file.apk);
4296        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4297            // If we are doing this while in the middle of updating a library apk,
4298            // then we need to make sure to use that new apk for determining the
4299            // dependencies here.  (We haven't yet finished committing the new apk
4300            // to the package manager state.)
4301            if (p == null || p.packageName.equals(changingLib.packageName)) {
4302                p = changingLib;
4303            }
4304        }
4305        if (p != null) {
4306            String path = p.mPath;
4307            for (int i=0; i<num; i++) {
4308                if (mTmpSharedLibraries[i].equals(path)) {
4309                    return num;
4310                }
4311            }
4312            mTmpSharedLibraries[num] = p.mPath;
4313            return num+1;
4314        }
4315        return num;
4316    }
4317
4318    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4319            PackageParser.Package changingLib) {
4320        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4321            if (mTmpSharedLibraries == null ||
4322                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4323                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4324            }
4325            int num = 0;
4326            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4327            for (int i=0; i<N; i++) {
4328                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4329                if (file == null) {
4330                    Slog.e(TAG, "Package " + pkg.packageName
4331                            + " requires unavailable shared library "
4332                            + pkg.usesLibraries.get(i) + "; failing!");
4333                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4334                    return false;
4335                }
4336                num = addSharedLibraryLPw(file, num, changingLib);
4337            }
4338            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4339            for (int i=0; i<N; i++) {
4340                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4341                if (file == null) {
4342                    Slog.w(TAG, "Package " + pkg.packageName
4343                            + " desires unavailable shared library "
4344                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4345                } else {
4346                    num = addSharedLibraryLPw(file, num, changingLib);
4347                }
4348            }
4349            if (num > 0) {
4350                pkg.usesLibraryFiles = new String[num];
4351                System.arraycopy(mTmpSharedLibraries, 0,
4352                        pkg.usesLibraryFiles, 0, num);
4353            } else {
4354                pkg.usesLibraryFiles = null;
4355            }
4356        }
4357        return true;
4358    }
4359
4360    private static boolean hasString(List<String> list, List<String> which) {
4361        if (list == null) {
4362            return false;
4363        }
4364        for (int i=list.size()-1; i>=0; i--) {
4365            for (int j=which.size()-1; j>=0; j--) {
4366                if (which.get(j).equals(list.get(i))) {
4367                    return true;
4368                }
4369            }
4370        }
4371        return false;
4372    }
4373
4374    private void updateAllSharedLibrariesLPw() {
4375        for (PackageParser.Package pkg : mPackages.values()) {
4376            updateSharedLibrariesLPw(pkg, null);
4377        }
4378    }
4379
4380    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4381            PackageParser.Package changingPkg) {
4382        ArrayList<PackageParser.Package> res = null;
4383        for (PackageParser.Package pkg : mPackages.values()) {
4384            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4385                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4386                if (res == null) {
4387                    res = new ArrayList<PackageParser.Package>();
4388                }
4389                res.add(pkg);
4390                updateSharedLibrariesLPw(pkg, changingPkg);
4391            }
4392        }
4393        return res;
4394    }
4395
4396    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4397            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4398        File scanFile = new File(pkg.mScanPath);
4399        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4400                pkg.applicationInfo.publicSourceDir == null) {
4401            // Bail out. The resource and code paths haven't been set.
4402            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4403            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4404            return null;
4405        }
4406
4407        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4408            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4409        }
4410
4411        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4412            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4413        }
4414
4415        if (mCustomResolverComponentName != null &&
4416                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4417            setUpCustomResolverActivity(pkg);
4418        }
4419
4420        if (pkg.packageName.equals("android")) {
4421            synchronized (mPackages) {
4422                if (mAndroidApplication != null) {
4423                    Slog.w(TAG, "*************************************************");
4424                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4425                    Slog.w(TAG, " file=" + scanFile);
4426                    Slog.w(TAG, "*************************************************");
4427                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4428                    return null;
4429                }
4430
4431                // Set up information for our fall-back user intent resolution activity.
4432                mPlatformPackage = pkg;
4433                pkg.mVersionCode = mSdkVersion;
4434                mAndroidApplication = pkg.applicationInfo;
4435
4436                if (!mResolverReplaced) {
4437                    mResolveActivity.applicationInfo = mAndroidApplication;
4438                    mResolveActivity.name = ResolverActivity.class.getName();
4439                    mResolveActivity.packageName = mAndroidApplication.packageName;
4440                    mResolveActivity.processName = "system:ui";
4441                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4442                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4443                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4444                    mResolveActivity.exported = true;
4445                    mResolveActivity.enabled = true;
4446                    mResolveInfo.activityInfo = mResolveActivity;
4447                    mResolveInfo.priority = 0;
4448                    mResolveInfo.preferredOrder = 0;
4449                    mResolveInfo.match = 0;
4450                    mResolveComponentName = new ComponentName(
4451                            mAndroidApplication.packageName, mResolveActivity.name);
4452                }
4453            }
4454        }
4455
4456        if (DEBUG_PACKAGE_SCANNING) {
4457            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4458                Log.d(TAG, "Scanning package " + pkg.packageName);
4459        }
4460
4461        if (mPackages.containsKey(pkg.packageName)
4462                || mSharedLibraries.containsKey(pkg.packageName)) {
4463            Slog.w(TAG, "Application package " + pkg.packageName
4464                    + " already installed.  Skipping duplicate.");
4465            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4466            return null;
4467        }
4468
4469        // Initialize package source and resource directories
4470        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4471        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4472
4473        SharedUserSetting suid = null;
4474        PackageSetting pkgSetting = null;
4475
4476        if (!isSystemApp(pkg)) {
4477            // Only system apps can use these features.
4478            pkg.mOriginalPackages = null;
4479            pkg.mRealPackage = null;
4480            pkg.mAdoptPermissions = null;
4481        }
4482
4483        // writer
4484        synchronized (mPackages) {
4485            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4486                // Check all shared libraries and map to their actual file path.
4487                // We only do this here for apps not on a system dir, because those
4488                // are the only ones that can fail an install due to this.  We
4489                // will take care of the system apps by updating all of their
4490                // library paths after the scan is done.
4491                if (!updateSharedLibrariesLPw(pkg, null)) {
4492                    return null;
4493                }
4494            }
4495
4496            if (pkg.mSharedUserId != null) {
4497                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4498                if (suid == null) {
4499                    Slog.w(TAG, "Creating application package " + pkg.packageName
4500                            + " for shared user failed");
4501                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4502                    return null;
4503                }
4504                if (DEBUG_PACKAGE_SCANNING) {
4505                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4506                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4507                                + "): packages=" + suid.packages);
4508                }
4509            }
4510
4511            // Check if we are renaming from an original package name.
4512            PackageSetting origPackage = null;
4513            String realName = null;
4514            if (pkg.mOriginalPackages != null) {
4515                // This package may need to be renamed to a previously
4516                // installed name.  Let's check on that...
4517                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4518                if (pkg.mOriginalPackages.contains(renamed)) {
4519                    // This package had originally been installed as the
4520                    // original name, and we have already taken care of
4521                    // transitioning to the new one.  Just update the new
4522                    // one to continue using the old name.
4523                    realName = pkg.mRealPackage;
4524                    if (!pkg.packageName.equals(renamed)) {
4525                        // Callers into this function may have already taken
4526                        // care of renaming the package; only do it here if
4527                        // it is not already done.
4528                        pkg.setPackageName(renamed);
4529                    }
4530
4531                } else {
4532                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4533                        if ((origPackage = mSettings.peekPackageLPr(
4534                                pkg.mOriginalPackages.get(i))) != null) {
4535                            // We do have the package already installed under its
4536                            // original name...  should we use it?
4537                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4538                                // New package is not compatible with original.
4539                                origPackage = null;
4540                                continue;
4541                            } else if (origPackage.sharedUser != null) {
4542                                // Make sure uid is compatible between packages.
4543                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4544                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4545                                            + " to " + pkg.packageName + ": old uid "
4546                                            + origPackage.sharedUser.name
4547                                            + " differs from " + pkg.mSharedUserId);
4548                                    origPackage = null;
4549                                    continue;
4550                                }
4551                            } else {
4552                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4553                                        + pkg.packageName + " to old name " + origPackage.name);
4554                            }
4555                            break;
4556                        }
4557                    }
4558                }
4559            }
4560
4561            if (mTransferedPackages.contains(pkg.packageName)) {
4562                Slog.w(TAG, "Package " + pkg.packageName
4563                        + " was transferred to another, but its .apk remains");
4564            }
4565
4566            // Just create the setting, don't add it yet. For already existing packages
4567            // the PkgSetting exists already and doesn't have to be created.
4568            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4569                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4570                    pkg.applicationInfo.flags, user, false);
4571            if (pkgSetting == null) {
4572                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4573                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4574                return null;
4575            }
4576
4577            if (pkgSetting.origPackage != null) {
4578                // If we are first transitioning from an original package,
4579                // fix up the new package's name now.  We need to do this after
4580                // looking up the package under its new name, so getPackageLP
4581                // can take care of fiddling things correctly.
4582                pkg.setPackageName(origPackage.name);
4583
4584                // File a report about this.
4585                String msg = "New package " + pkgSetting.realName
4586                        + " renamed to replace old package " + pkgSetting.name;
4587                reportSettingsProblem(Log.WARN, msg);
4588
4589                // Make a note of it.
4590                mTransferedPackages.add(origPackage.name);
4591
4592                // No longer need to retain this.
4593                pkgSetting.origPackage = null;
4594            }
4595
4596            if (realName != null) {
4597                // Make a note of it.
4598                mTransferedPackages.add(pkg.packageName);
4599            }
4600
4601            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4602                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4603            }
4604
4605            if (mFoundPolicyFile) {
4606                SELinuxMMAC.assignSeinfoValue(pkg);
4607            }
4608
4609            pkg.applicationInfo.uid = pkgSetting.appId;
4610            pkg.mExtras = pkgSetting;
4611
4612            if (!verifySignaturesLP(pkgSetting, pkg)) {
4613                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4614                    return null;
4615                }
4616                // The signature has changed, but this package is in the system
4617                // image...  let's recover!
4618                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4619                // However...  if this package is part of a shared user, but it
4620                // doesn't match the signature of the shared user, let's fail.
4621                // What this means is that you can't change the signatures
4622                // associated with an overall shared user, which doesn't seem all
4623                // that unreasonable.
4624                if (pkgSetting.sharedUser != null) {
4625                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4626                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4627                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4628                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4629                        return null;
4630                    }
4631                }
4632                // File a report about this.
4633                String msg = "System package " + pkg.packageName
4634                        + " signature changed; retaining data.";
4635                reportSettingsProblem(Log.WARN, msg);
4636            }
4637
4638            // Verify that this new package doesn't have any content providers
4639            // that conflict with existing packages.  Only do this if the
4640            // package isn't already installed, since we don't want to break
4641            // things that are installed.
4642            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4643                final int N = pkg.providers.size();
4644                int i;
4645                for (i=0; i<N; i++) {
4646                    PackageParser.Provider p = pkg.providers.get(i);
4647                    if (p.info.authority != null) {
4648                        String names[] = p.info.authority.split(";");
4649                        for (int j = 0; j < names.length; j++) {
4650                            if (mProvidersByAuthority.containsKey(names[j])) {
4651                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4652                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4653                                        " (in package " + pkg.applicationInfo.packageName +
4654                                        ") is already used by "
4655                                        + ((other != null && other.getComponentName() != null)
4656                                                ? other.getComponentName().getPackageName() : "?"));
4657                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4658                                return null;
4659                            }
4660                        }
4661                    }
4662                }
4663            }
4664
4665            if (pkg.mAdoptPermissions != null) {
4666                // This package wants to adopt ownership of permissions from
4667                // another package.
4668                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4669                    final String origName = pkg.mAdoptPermissions.get(i);
4670                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4671                    if (orig != null) {
4672                        if (verifyPackageUpdateLPr(orig, pkg)) {
4673                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4674                                    + pkg.packageName);
4675                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4676                        }
4677                    }
4678                }
4679            }
4680        }
4681
4682        final String pkgName = pkg.packageName;
4683
4684        final long scanFileTime = scanFile.lastModified();
4685        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4686        pkg.applicationInfo.processName = fixProcessName(
4687                pkg.applicationInfo.packageName,
4688                pkg.applicationInfo.processName,
4689                pkg.applicationInfo.uid);
4690
4691        File dataPath;
4692        if (mPlatformPackage == pkg) {
4693            // The system package is special.
4694            dataPath = new File (Environment.getDataDirectory(), "system");
4695            pkg.applicationInfo.dataDir = dataPath.getPath();
4696        } else {
4697            // This is a normal package, need to make its data directory.
4698            dataPath = getDataPathForPackage(pkg.packageName, 0);
4699
4700            boolean uidError = false;
4701
4702            if (dataPath.exists()) {
4703                int currentUid = 0;
4704                try {
4705                    StructStat stat = Libcore.os.stat(dataPath.getPath());
4706                    currentUid = stat.st_uid;
4707                } catch (ErrnoException e) {
4708                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4709                }
4710
4711                // If we have mismatched owners for the data path, we have a problem.
4712                if (currentUid != pkg.applicationInfo.uid) {
4713                    boolean recovered = false;
4714                    if (currentUid == 0) {
4715                        // The directory somehow became owned by root.  Wow.
4716                        // This is probably because the system was stopped while
4717                        // installd was in the middle of messing with its libs
4718                        // directory.  Ask installd to fix that.
4719                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4720                                pkg.applicationInfo.uid);
4721                        if (ret >= 0) {
4722                            recovered = true;
4723                            String msg = "Package " + pkg.packageName
4724                                    + " unexpectedly changed to uid 0; recovered to " +
4725                                    + pkg.applicationInfo.uid;
4726                            reportSettingsProblem(Log.WARN, msg);
4727                        }
4728                    }
4729                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4730                            || (scanMode&SCAN_BOOTING) != 0)) {
4731                        // If this is a system app, we can at least delete its
4732                        // current data so the application will still work.
4733                        int ret = removeDataDirsLI(pkgName);
4734                        if (ret >= 0) {
4735                            // TODO: Kill the processes first
4736                            // Old data gone!
4737                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4738                                    ? "System package " : "Third party package ";
4739                            String msg = prefix + pkg.packageName
4740                                    + " has changed from uid: "
4741                                    + currentUid + " to "
4742                                    + pkg.applicationInfo.uid + "; old data erased";
4743                            reportSettingsProblem(Log.WARN, msg);
4744                            recovered = true;
4745
4746                            // And now re-install the app.
4747                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4748                                                   pkg.applicationInfo.seinfo);
4749                            if (ret == -1) {
4750                                // Ack should not happen!
4751                                msg = prefix + pkg.packageName
4752                                        + " could not have data directory re-created after delete.";
4753                                reportSettingsProblem(Log.WARN, msg);
4754                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4755                                return null;
4756                            }
4757                        }
4758                        if (!recovered) {
4759                            mHasSystemUidErrors = true;
4760                        }
4761                    } else if (!recovered) {
4762                        // If we allow this install to proceed, we will be broken.
4763                        // Abort, abort!
4764                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4765                        return null;
4766                    }
4767                    if (!recovered) {
4768                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4769                            + pkg.applicationInfo.uid + "/fs_"
4770                            + currentUid;
4771                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4772                        String msg = "Package " + pkg.packageName
4773                                + " has mismatched uid: "
4774                                + currentUid + " on disk, "
4775                                + pkg.applicationInfo.uid + " in settings";
4776                        // writer
4777                        synchronized (mPackages) {
4778                            mSettings.mReadMessages.append(msg);
4779                            mSettings.mReadMessages.append('\n');
4780                            uidError = true;
4781                            if (!pkgSetting.uidError) {
4782                                reportSettingsProblem(Log.ERROR, msg);
4783                            }
4784                        }
4785                    }
4786                }
4787                pkg.applicationInfo.dataDir = dataPath.getPath();
4788            } else {
4789                if (DEBUG_PACKAGE_SCANNING) {
4790                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4791                        Log.v(TAG, "Want this data dir: " + dataPath);
4792                }
4793                //invoke installer to do the actual installation
4794                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4795                                           pkg.applicationInfo.seinfo);
4796                if (ret < 0) {
4797                    // Error from installer
4798                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4799                    return null;
4800                }
4801
4802                if (dataPath.exists()) {
4803                    pkg.applicationInfo.dataDir = dataPath.getPath();
4804                } else {
4805                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4806                    pkg.applicationInfo.dataDir = null;
4807                }
4808            }
4809
4810            /*
4811             * Set the data dir to the default "/data/data/<package name>/lib"
4812             * if we got here without anyone telling us different (e.g., apps
4813             * stored on SD card have their native libraries stored in the ASEC
4814             * container with the APK).
4815             *
4816             * This happens during an upgrade from a package settings file that
4817             * doesn't have a native library path attribute at all.
4818             */
4819            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4820                if (pkgSetting.nativeLibraryPathString == null) {
4821                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4822                } else {
4823                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4824                }
4825            }
4826
4827            pkgSetting.uidError = uidError;
4828        }
4829
4830        String path = scanFile.getPath();
4831        /* Note: We don't want to unpack the native binaries for
4832         *        system applications, unless they have been updated
4833         *        (the binaries are already under /system/lib).
4834         *        Also, don't unpack libs for apps on the external card
4835         *        since they should have their libraries in the ASEC
4836         *        container already.
4837         *
4838         *        In other words, we're going to unpack the binaries
4839         *        only for non-system apps and system app upgrades.
4840         */
4841        if (pkg.applicationInfo.nativeLibraryDir != null) {
4842            try {
4843                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4844                final String dataPathString = dataPath.getCanonicalPath();
4845
4846                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4847                    /*
4848                     * Upgrading from a previous version of the OS sometimes
4849                     * leaves native libraries in the /data/data/<app>/lib
4850                     * directory for system apps even when they shouldn't be.
4851                     * Recent changes in the JNI library search path
4852                     * necessitates we remove those to match previous behavior.
4853                     */
4854                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4855                        Log.i(TAG, "removed obsolete native libraries for system package "
4856                                + path);
4857                    }
4858                } else {
4859                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4860                        /*
4861                         * Update native library dir if it starts with
4862                         * /data/data
4863                         */
4864                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4865                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
4866                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4867                        }
4868
4869                        try {
4870                            if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4871                                Slog.e(TAG, "Unable to copy native libraries");
4872                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4873                                return null;
4874                            }
4875                        } catch (IOException e) {
4876                            Slog.e(TAG, "Unable to copy native libraries", e);
4877                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4878                            return null;
4879                        }
4880                    }
4881
4882                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4883                    final int[] userIds = sUserManager.getUserIds();
4884                    synchronized (mInstallLock) {
4885                        for (int userId : userIds) {
4886                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4887                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4888                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4889                                        + ")");
4890                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4891                                return null;
4892                            }
4893                        }
4894                    }
4895                }
4896            } catch (IOException ioe) {
4897                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4898            }
4899        }
4900        pkg.mScanPath = path;
4901
4902        if ((scanMode&SCAN_NO_DEX) == 0) {
4903            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4904                    == DEX_OPT_FAILED) {
4905                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4906                    removeDataDirsLI(pkg.packageName);
4907                }
4908
4909                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4910                return null;
4911            }
4912        }
4913
4914        if (mFactoryTest && pkg.requestedPermissions.contains(
4915                android.Manifest.permission.FACTORY_TEST)) {
4916            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4917        }
4918
4919        ArrayList<PackageParser.Package> clientLibPkgs = null;
4920
4921        // writer
4922        synchronized (mPackages) {
4923            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4924                // Only system apps can add new shared libraries.
4925                if (pkg.libraryNames != null) {
4926                    for (int i=0; i<pkg.libraryNames.size(); i++) {
4927                        String name = pkg.libraryNames.get(i);
4928                        boolean allowed = false;
4929                        if (isUpdatedSystemApp(pkg)) {
4930                            // New library entries can only be added through the
4931                            // system image.  This is important to get rid of a lot
4932                            // of nasty edge cases: for example if we allowed a non-
4933                            // system update of the app to add a library, then uninstalling
4934                            // the update would make the library go away, and assumptions
4935                            // we made such as through app install filtering would now
4936                            // have allowed apps on the device which aren't compatible
4937                            // with it.  Better to just have the restriction here, be
4938                            // conservative, and create many fewer cases that can negatively
4939                            // impact the user experience.
4940                            final PackageSetting sysPs = mSettings
4941                                    .getDisabledSystemPkgLPr(pkg.packageName);
4942                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4943                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4944                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4945                                        allowed = true;
4946                                        allowed = true;
4947                                        break;
4948                                    }
4949                                }
4950                            }
4951                        } else {
4952                            allowed = true;
4953                        }
4954                        if (allowed) {
4955                            if (!mSharedLibraries.containsKey(name)) {
4956                                mSharedLibraries.put(name, new SharedLibraryEntry(null,
4957                                        pkg.packageName));
4958                            } else if (!name.equals(pkg.packageName)) {
4959                                Slog.w(TAG, "Package " + pkg.packageName + " library "
4960                                        + name + " already exists; skipping");
4961                            }
4962                        } else {
4963                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4964                                    + name + " that is not declared on system image; skipping");
4965                        }
4966                    }
4967                    if ((scanMode&SCAN_BOOTING) == 0) {
4968                        // If we are not booting, we need to update any applications
4969                        // that are clients of our shared library.  If we are booting,
4970                        // this will all be done once the scan is complete.
4971                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4972                    }
4973                }
4974            }
4975        }
4976
4977        // We also need to dexopt any apps that are dependent on this library.  Note that
4978        // if these fail, we should abort the install since installing the library will
4979        // result in some apps being broken.
4980        if (clientLibPkgs != null) {
4981            if ((scanMode&SCAN_NO_DEX) == 0) {
4982                for (int i=0; i<clientLibPkgs.size(); i++) {
4983                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
4984                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4985                            == DEX_OPT_FAILED) {
4986                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4987                            removeDataDirsLI(pkg.packageName);
4988                        }
4989
4990                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4991                        return null;
4992                    }
4993                }
4994            }
4995        }
4996
4997        // Request the ActivityManager to kill the process(only for existing packages)
4998        // so that we do not end up in a confused state while the user is still using the older
4999        // version of the application while the new one gets installed.
5000        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5001            // If the package lives in an asec, tell everyone that the container is going
5002            // away so they can clean up any references to its resources (which would prevent
5003            // vold from being able to unmount the asec)
5004            if (isForwardLocked(pkg) || isExternal(pkg)) {
5005                if (DEBUG_INSTALL) {
5006                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5007                }
5008                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5009                final ArrayList<String> pkgList = new ArrayList<String>(1);
5010                pkgList.add(pkg.applicationInfo.packageName);
5011                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5012            }
5013
5014            // Post the request that it be killed now that the going-away broadcast is en route
5015            killApplication(pkg.applicationInfo.packageName,
5016                        pkg.applicationInfo.uid, "update pkg");
5017        }
5018
5019        // Also need to kill any apps that are dependent on the library.
5020        if (clientLibPkgs != null) {
5021            for (int i=0; i<clientLibPkgs.size(); i++) {
5022                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5023                killApplication(clientPkg.applicationInfo.packageName,
5024                        clientPkg.applicationInfo.uid, "update lib");
5025            }
5026        }
5027
5028        // writer
5029        synchronized (mPackages) {
5030            // We don't expect installation to fail beyond this point,
5031            if ((scanMode&SCAN_MONITOR) != 0) {
5032                mAppDirs.put(pkg.mPath, pkg);
5033            }
5034            // Add the new setting to mSettings
5035            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5036            // Add the new setting to mPackages
5037            mPackages.put(pkg.applicationInfo.packageName, pkg);
5038            // Make sure we don't accidentally delete its data.
5039            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5040            while (iter.hasNext()) {
5041                PackageCleanItem item = iter.next();
5042                if (pkgName.equals(item.packageName)) {
5043                    iter.remove();
5044                }
5045            }
5046
5047            // Take care of first install / last update times.
5048            if (currentTime != 0) {
5049                if (pkgSetting.firstInstallTime == 0) {
5050                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5051                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5052                    pkgSetting.lastUpdateTime = currentTime;
5053                }
5054            } else if (pkgSetting.firstInstallTime == 0) {
5055                // We need *something*.  Take time time stamp of the file.
5056                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5057            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5058                if (scanFileTime != pkgSetting.timeStamp) {
5059                    // A package on the system image has changed; consider this
5060                    // to be an update.
5061                    pkgSetting.lastUpdateTime = scanFileTime;
5062                }
5063            }
5064
5065            // Add the package's KeySets to the global KeySetManager
5066            KeySetManager ksm = mSettings.mKeySetManager;
5067            try {
5068                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5069                if (pkg.mKeySetMapping != null) {
5070                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5071                        if (entry.getValue() != null) {
5072                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5073                                entry.getValue(), entry.getKey());
5074                        }
5075                    }
5076                }
5077            } catch (NullPointerException e) {
5078                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5079            } catch (IllegalArgumentException e) {
5080                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5081            }
5082
5083            int N = pkg.providers.size();
5084            StringBuilder r = null;
5085            int i;
5086            for (i=0; i<N; i++) {
5087                PackageParser.Provider p = pkg.providers.get(i);
5088                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5089                        p.info.processName, pkg.applicationInfo.uid);
5090                mProviders.addProvider(p);
5091                p.syncable = p.info.isSyncable;
5092                if (p.info.authority != null) {
5093                    String names[] = p.info.authority.split(";");
5094                    p.info.authority = null;
5095                    for (int j = 0; j < names.length; j++) {
5096                        if (j == 1 && p.syncable) {
5097                            // We only want the first authority for a provider to possibly be
5098                            // syncable, so if we already added this provider using a different
5099                            // authority clear the syncable flag. We copy the provider before
5100                            // changing it because the mProviders object contains a reference
5101                            // to a provider that we don't want to change.
5102                            // Only do this for the second authority since the resulting provider
5103                            // object can be the same for all future authorities for this provider.
5104                            p = new PackageParser.Provider(p);
5105                            p.syncable = false;
5106                        }
5107                        if (!mProvidersByAuthority.containsKey(names[j])) {
5108                            mProvidersByAuthority.put(names[j], p);
5109                            if (p.info.authority == null) {
5110                                p.info.authority = names[j];
5111                            } else {
5112                                p.info.authority = p.info.authority + ";" + names[j];
5113                            }
5114                            if (DEBUG_PACKAGE_SCANNING) {
5115                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5116                                    Log.d(TAG, "Registered content provider: " + names[j]
5117                                            + ", className = " + p.info.name + ", isSyncable = "
5118                                            + p.info.isSyncable);
5119                            }
5120                        } else {
5121                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5122                            Slog.w(TAG, "Skipping provider name " + names[j] +
5123                                    " (in package " + pkg.applicationInfo.packageName +
5124                                    "): name already used by "
5125                                    + ((other != null && other.getComponentName() != null)
5126                                            ? other.getComponentName().getPackageName() : "?"));
5127                        }
5128                    }
5129                }
5130                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5131                    if (r == null) {
5132                        r = new StringBuilder(256);
5133                    } else {
5134                        r.append(' ');
5135                    }
5136                    r.append(p.info.name);
5137                }
5138            }
5139            if (r != null) {
5140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5141            }
5142
5143            N = pkg.services.size();
5144            r = null;
5145            for (i=0; i<N; i++) {
5146                PackageParser.Service s = pkg.services.get(i);
5147                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5148                        s.info.processName, pkg.applicationInfo.uid);
5149                mServices.addService(s);
5150                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5151                    if (r == null) {
5152                        r = new StringBuilder(256);
5153                    } else {
5154                        r.append(' ');
5155                    }
5156                    r.append(s.info.name);
5157                }
5158            }
5159            if (r != null) {
5160                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5161            }
5162
5163            N = pkg.receivers.size();
5164            r = null;
5165            for (i=0; i<N; i++) {
5166                PackageParser.Activity a = pkg.receivers.get(i);
5167                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5168                        a.info.processName, pkg.applicationInfo.uid);
5169                mReceivers.addActivity(a, "receiver");
5170                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5171                    if (r == null) {
5172                        r = new StringBuilder(256);
5173                    } else {
5174                        r.append(' ');
5175                    }
5176                    r.append(a.info.name);
5177                }
5178            }
5179            if (r != null) {
5180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5181            }
5182
5183            N = pkg.activities.size();
5184            r = null;
5185            for (i=0; i<N; i++) {
5186                PackageParser.Activity a = pkg.activities.get(i);
5187                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5188                        a.info.processName, pkg.applicationInfo.uid);
5189                mActivities.addActivity(a, "activity");
5190                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5191                    if (r == null) {
5192                        r = new StringBuilder(256);
5193                    } else {
5194                        r.append(' ');
5195                    }
5196                    r.append(a.info.name);
5197                }
5198            }
5199            if (r != null) {
5200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5201            }
5202
5203            N = pkg.permissionGroups.size();
5204            r = null;
5205            for (i=0; i<N; i++) {
5206                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5207                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5208                if (cur == null) {
5209                    mPermissionGroups.put(pg.info.name, pg);
5210                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5211                        if (r == null) {
5212                            r = new StringBuilder(256);
5213                        } else {
5214                            r.append(' ');
5215                        }
5216                        r.append(pg.info.name);
5217                    }
5218                } else {
5219                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5220                            + pg.info.packageName + " ignored: original from "
5221                            + cur.info.packageName);
5222                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5223                        if (r == null) {
5224                            r = new StringBuilder(256);
5225                        } else {
5226                            r.append(' ');
5227                        }
5228                        r.append("DUP:");
5229                        r.append(pg.info.name);
5230                    }
5231                }
5232            }
5233            if (r != null) {
5234                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5235            }
5236
5237            N = pkg.permissions.size();
5238            r = null;
5239            for (i=0; i<N; i++) {
5240                PackageParser.Permission p = pkg.permissions.get(i);
5241                HashMap<String, BasePermission> permissionMap =
5242                        p.tree ? mSettings.mPermissionTrees
5243                        : mSettings.mPermissions;
5244                p.group = mPermissionGroups.get(p.info.group);
5245                if (p.info.group == null || p.group != null) {
5246                    BasePermission bp = permissionMap.get(p.info.name);
5247                    if (bp == null) {
5248                        bp = new BasePermission(p.info.name, p.info.packageName,
5249                                BasePermission.TYPE_NORMAL);
5250                        permissionMap.put(p.info.name, bp);
5251                    }
5252                    if (bp.perm == null) {
5253                        if (bp.sourcePackage != null
5254                                && !bp.sourcePackage.equals(p.info.packageName)) {
5255                            // If this is a permission that was formerly defined by a non-system
5256                            // app, but is now defined by a system app (following an upgrade),
5257                            // discard the previous declaration and consider the system's to be
5258                            // canonical.
5259                            if (isSystemApp(p.owner)) {
5260                                String msg = "New decl " + p.owner + " of permission  "
5261                                        + p.info.name + " is system";
5262                                reportSettingsProblem(Log.WARN, msg);
5263                                bp.sourcePackage = null;
5264                            }
5265                        }
5266                        if (bp.sourcePackage == null
5267                                || bp.sourcePackage.equals(p.info.packageName)) {
5268                            BasePermission tree = findPermissionTreeLP(p.info.name);
5269                            if (tree == null
5270                                    || tree.sourcePackage.equals(p.info.packageName)) {
5271                                bp.packageSetting = pkgSetting;
5272                                bp.perm = p;
5273                                bp.uid = pkg.applicationInfo.uid;
5274                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5275                                    if (r == null) {
5276                                        r = new StringBuilder(256);
5277                                    } else {
5278                                        r.append(' ');
5279                                    }
5280                                    r.append(p.info.name);
5281                                }
5282                            } else {
5283                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5284                                        + p.info.packageName + " ignored: base tree "
5285                                        + tree.name + " is from package "
5286                                        + tree.sourcePackage);
5287                            }
5288                        } else {
5289                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5290                                    + p.info.packageName + " ignored: original from "
5291                                    + bp.sourcePackage);
5292                        }
5293                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5294                        if (r == null) {
5295                            r = new StringBuilder(256);
5296                        } else {
5297                            r.append(' ');
5298                        }
5299                        r.append("DUP:");
5300                        r.append(p.info.name);
5301                    }
5302                    if (bp.perm == p) {
5303                        bp.protectionLevel = p.info.protectionLevel;
5304                    }
5305                } else {
5306                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5307                            + p.info.packageName + " ignored: no group "
5308                            + p.group);
5309                }
5310            }
5311            if (r != null) {
5312                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5313            }
5314
5315            N = pkg.instrumentation.size();
5316            r = null;
5317            for (i=0; i<N; i++) {
5318                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5319                a.info.packageName = pkg.applicationInfo.packageName;
5320                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5321                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5322                a.info.dataDir = pkg.applicationInfo.dataDir;
5323                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5324                mInstrumentation.put(a.getComponentName(), a);
5325                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5326                    if (r == null) {
5327                        r = new StringBuilder(256);
5328                    } else {
5329                        r.append(' ');
5330                    }
5331                    r.append(a.info.name);
5332                }
5333            }
5334            if (r != null) {
5335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5336            }
5337
5338            if (pkg.protectedBroadcasts != null) {
5339                N = pkg.protectedBroadcasts.size();
5340                for (i=0; i<N; i++) {
5341                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5342                }
5343            }
5344
5345            pkgSetting.setTimeStamp(scanFileTime);
5346
5347            // Create idmap files for pairs of (packages, overlay packages).
5348            // Note: "android", ie framework-res.apk, is handled by native layers.
5349            if (pkg.mOverlayTarget != null) {
5350                // This is an overlay package.
5351                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5352                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5353                        mOverlays.put(pkg.mOverlayTarget,
5354                                new HashMap<String, PackageParser.Package>());
5355                    }
5356                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5357                    map.put(pkg.packageName, pkg);
5358                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5359                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5360                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5361                        return null;
5362                    }
5363                }
5364            } else if (mOverlays.containsKey(pkg.packageName) &&
5365                    !pkg.packageName.equals("android")) {
5366                // This is a regular package, with one or more known overlay packages.
5367                createIdmapsForPackageLI(pkg);
5368            }
5369        }
5370
5371        return pkg;
5372    }
5373
5374    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5375        synchronized (mPackages) {
5376            mResolverReplaced = true;
5377            // Set up information for custom user intent resolution activity.
5378            mResolveActivity.applicationInfo = pkg.applicationInfo;
5379            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5380            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5381            mResolveActivity.processName = null;
5382            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5383            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5384                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5385            mResolveActivity.theme = 0;
5386            mResolveActivity.exported = true;
5387            mResolveActivity.enabled = true;
5388            mResolveInfo.activityInfo = mResolveActivity;
5389            mResolveInfo.priority = 0;
5390            mResolveInfo.preferredOrder = 0;
5391            mResolveInfo.match = 0;
5392            mResolveComponentName = mCustomResolverComponentName;
5393            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5394                    mResolveComponentName);
5395        }
5396    }
5397
5398    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5399            PackageSetting pkgSetting) {
5400        final String apkLibPath = getApkName(pkgSetting.codePathString);
5401        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
5402        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5403        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5404    }
5405
5406    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5407            throws IOException {
5408        if (!nativeLibraryDir.isDirectory()) {
5409            nativeLibraryDir.delete();
5410
5411            if (!nativeLibraryDir.mkdir()) {
5412                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5413            }
5414
5415            try {
5416                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
5417                        | S_IXOTH);
5418            } catch (ErrnoException e) {
5419                throw new IOException("Cannot chmod native library directory "
5420                        + nativeLibraryDir.getPath(), e);
5421            }
5422        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5423            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5424        }
5425
5426        /*
5427         * If this is an internal application or our nativeLibraryPath points to
5428         * the app-lib directory, unpack the libraries if necessary.
5429         */
5430        return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
5431    }
5432
5433    private void killApplication(String pkgName, int appId, String reason) {
5434        // Request the ActivityManager to kill the process(only for existing packages)
5435        // so that we do not end up in a confused state while the user is still using the older
5436        // version of the application while the new one gets installed.
5437        IActivityManager am = ActivityManagerNative.getDefault();
5438        if (am != null) {
5439            try {
5440                am.killApplicationWithAppId(pkgName, appId, reason);
5441            } catch (RemoteException e) {
5442            }
5443        }
5444    }
5445
5446    void removePackageLI(PackageSetting ps, boolean chatty) {
5447        if (DEBUG_INSTALL) {
5448            if (chatty)
5449                Log.d(TAG, "Removing package " + ps.name);
5450        }
5451
5452        // writer
5453        synchronized (mPackages) {
5454            mPackages.remove(ps.name);
5455            if (ps.codePathString != null) {
5456                mAppDirs.remove(ps.codePathString);
5457            }
5458
5459            final PackageParser.Package pkg = ps.pkg;
5460            if (pkg != null) {
5461                cleanPackageDataStructuresLILPw(pkg, chatty);
5462            }
5463        }
5464    }
5465
5466    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5467        if (DEBUG_INSTALL) {
5468            if (chatty)
5469                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5470        }
5471
5472        // writer
5473        synchronized (mPackages) {
5474            mPackages.remove(pkg.applicationInfo.packageName);
5475            if (pkg.mPath != null) {
5476                mAppDirs.remove(pkg.mPath);
5477            }
5478            cleanPackageDataStructuresLILPw(pkg, chatty);
5479        }
5480    }
5481
5482    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5483        int N = pkg.providers.size();
5484        StringBuilder r = null;
5485        int i;
5486        for (i=0; i<N; i++) {
5487            PackageParser.Provider p = pkg.providers.get(i);
5488            mProviders.removeProvider(p);
5489            if (p.info.authority == null) {
5490
5491                /* There was another ContentProvider with this authority when
5492                 * this app was installed so this authority is null,
5493                 * Ignore it as we don't have to unregister the provider.
5494                 */
5495                continue;
5496            }
5497            String names[] = p.info.authority.split(";");
5498            for (int j = 0; j < names.length; j++) {
5499                if (mProvidersByAuthority.get(names[j]) == p) {
5500                    mProvidersByAuthority.remove(names[j]);
5501                    if (DEBUG_REMOVE) {
5502                        if (chatty)
5503                            Log.d(TAG, "Unregistered content provider: " + names[j]
5504                                    + ", className = " + p.info.name + ", isSyncable = "
5505                                    + p.info.isSyncable);
5506                    }
5507                }
5508            }
5509            if (DEBUG_REMOVE && chatty) {
5510                if (r == null) {
5511                    r = new StringBuilder(256);
5512                } else {
5513                    r.append(' ');
5514                }
5515                r.append(p.info.name);
5516            }
5517        }
5518        if (r != null) {
5519            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5520        }
5521
5522        N = pkg.services.size();
5523        r = null;
5524        for (i=0; i<N; i++) {
5525            PackageParser.Service s = pkg.services.get(i);
5526            mServices.removeService(s);
5527            if (chatty) {
5528                if (r == null) {
5529                    r = new StringBuilder(256);
5530                } else {
5531                    r.append(' ');
5532                }
5533                r.append(s.info.name);
5534            }
5535        }
5536        if (r != null) {
5537            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5538        }
5539
5540        N = pkg.receivers.size();
5541        r = null;
5542        for (i=0; i<N; i++) {
5543            PackageParser.Activity a = pkg.receivers.get(i);
5544            mReceivers.removeActivity(a, "receiver");
5545            if (DEBUG_REMOVE && chatty) {
5546                if (r == null) {
5547                    r = new StringBuilder(256);
5548                } else {
5549                    r.append(' ');
5550                }
5551                r.append(a.info.name);
5552            }
5553        }
5554        if (r != null) {
5555            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5556        }
5557
5558        N = pkg.activities.size();
5559        r = null;
5560        for (i=0; i<N; i++) {
5561            PackageParser.Activity a = pkg.activities.get(i);
5562            mActivities.removeActivity(a, "activity");
5563            if (DEBUG_REMOVE && chatty) {
5564                if (r == null) {
5565                    r = new StringBuilder(256);
5566                } else {
5567                    r.append(' ');
5568                }
5569                r.append(a.info.name);
5570            }
5571        }
5572        if (r != null) {
5573            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5574        }
5575
5576        N = pkg.permissions.size();
5577        r = null;
5578        for (i=0; i<N; i++) {
5579            PackageParser.Permission p = pkg.permissions.get(i);
5580            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5581            if (bp == null) {
5582                bp = mSettings.mPermissionTrees.get(p.info.name);
5583            }
5584            if (bp != null && bp.perm == p) {
5585                bp.perm = null;
5586                if (DEBUG_REMOVE && chatty) {
5587                    if (r == null) {
5588                        r = new StringBuilder(256);
5589                    } else {
5590                        r.append(' ');
5591                    }
5592                    r.append(p.info.name);
5593                }
5594            }
5595        }
5596        if (r != null) {
5597            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5598        }
5599
5600        N = pkg.instrumentation.size();
5601        r = null;
5602        for (i=0; i<N; i++) {
5603            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5604            mInstrumentation.remove(a.getComponentName());
5605            if (DEBUG_REMOVE && chatty) {
5606                if (r == null) {
5607                    r = new StringBuilder(256);
5608                } else {
5609                    r.append(' ');
5610                }
5611                r.append(a.info.name);
5612            }
5613        }
5614        if (r != null) {
5615            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5616        }
5617
5618        r = null;
5619        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5620            // Only system apps can hold shared libraries.
5621            if (pkg.libraryNames != null) {
5622                for (i=0; i<pkg.libraryNames.size(); i++) {
5623                    String name = pkg.libraryNames.get(i);
5624                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5625                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5626                        mSharedLibraries.remove(name);
5627                        if (DEBUG_REMOVE && chatty) {
5628                            if (r == null) {
5629                                r = new StringBuilder(256);
5630                            } else {
5631                                r.append(' ');
5632                            }
5633                            r.append(name);
5634                        }
5635                    }
5636                }
5637            }
5638        }
5639        if (r != null) {
5640            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5641        }
5642    }
5643
5644    private static final boolean isPackageFilename(String name) {
5645        return name != null && name.endsWith(".apk");
5646    }
5647
5648    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5649        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5650            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5651                return true;
5652            }
5653        }
5654        return false;
5655    }
5656
5657    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5658    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5659    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5660
5661    private void updatePermissionsLPw(String changingPkg,
5662            PackageParser.Package pkgInfo, int flags) {
5663        // Make sure there are no dangling permission trees.
5664        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5665        while (it.hasNext()) {
5666            final BasePermission bp = it.next();
5667            if (bp.packageSetting == null) {
5668                // We may not yet have parsed the package, so just see if
5669                // we still know about its settings.
5670                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5671            }
5672            if (bp.packageSetting == null) {
5673                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5674                        + " from package " + bp.sourcePackage);
5675                it.remove();
5676            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5677                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5678                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5679                            + " from package " + bp.sourcePackage);
5680                    flags |= UPDATE_PERMISSIONS_ALL;
5681                    it.remove();
5682                }
5683            }
5684        }
5685
5686        // Make sure all dynamic permissions have been assigned to a package,
5687        // and make sure there are no dangling permissions.
5688        it = mSettings.mPermissions.values().iterator();
5689        while (it.hasNext()) {
5690            final BasePermission bp = it.next();
5691            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5692                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5693                        + bp.name + " pkg=" + bp.sourcePackage
5694                        + " info=" + bp.pendingInfo);
5695                if (bp.packageSetting == null && bp.pendingInfo != null) {
5696                    final BasePermission tree = findPermissionTreeLP(bp.name);
5697                    if (tree != null && tree.perm != null) {
5698                        bp.packageSetting = tree.packageSetting;
5699                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5700                                new PermissionInfo(bp.pendingInfo));
5701                        bp.perm.info.packageName = tree.perm.info.packageName;
5702                        bp.perm.info.name = bp.name;
5703                        bp.uid = tree.uid;
5704                    }
5705                }
5706            }
5707            if (bp.packageSetting == null) {
5708                // We may not yet have parsed the package, so just see if
5709                // we still know about its settings.
5710                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5711            }
5712            if (bp.packageSetting == null) {
5713                Slog.w(TAG, "Removing dangling permission: " + bp.name
5714                        + " from package " + bp.sourcePackage);
5715                it.remove();
5716            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5717                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5718                    Slog.i(TAG, "Removing old permission: " + bp.name
5719                            + " from package " + bp.sourcePackage);
5720                    flags |= UPDATE_PERMISSIONS_ALL;
5721                    it.remove();
5722                }
5723            }
5724        }
5725
5726        // Now update the permissions for all packages, in particular
5727        // replace the granted permissions of the system packages.
5728        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5729            for (PackageParser.Package pkg : mPackages.values()) {
5730                if (pkg != pkgInfo) {
5731                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5732                }
5733            }
5734        }
5735
5736        if (pkgInfo != null) {
5737            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5738        }
5739    }
5740
5741    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5742        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5743        if (ps == null) {
5744            return;
5745        }
5746        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5747        HashSet<String> origPermissions = gp.grantedPermissions;
5748        boolean changedPermission = false;
5749
5750        if (replace) {
5751            ps.permissionsFixed = false;
5752            if (gp == ps) {
5753                origPermissions = new HashSet<String>(gp.grantedPermissions);
5754                gp.grantedPermissions.clear();
5755                gp.gids = mGlobalGids;
5756            }
5757        }
5758
5759        if (gp.gids == null) {
5760            gp.gids = mGlobalGids;
5761        }
5762
5763        final int N = pkg.requestedPermissions.size();
5764        for (int i=0; i<N; i++) {
5765            final String name = pkg.requestedPermissions.get(i);
5766            final boolean required = pkg.requestedPermissionsRequired.get(i);
5767            final BasePermission bp = mSettings.mPermissions.get(name);
5768            if (DEBUG_INSTALL) {
5769                if (gp != ps) {
5770                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5771                }
5772            }
5773
5774            if (bp == null || bp.packageSetting == null) {
5775                Slog.w(TAG, "Unknown permission " + name
5776                        + " in package " + pkg.packageName);
5777                continue;
5778            }
5779
5780            final String perm = bp.name;
5781            boolean allowed;
5782            boolean allowedSig = false;
5783            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5784            if (level == PermissionInfo.PROTECTION_NORMAL
5785                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5786                // We grant a normal or dangerous permission if any of the following
5787                // are true:
5788                // 1) The permission is required
5789                // 2) The permission is optional, but was granted in the past
5790                // 3) The permission is optional, but was requested by an
5791                //    app in /system (not /data)
5792                //
5793                // Otherwise, reject the permission.
5794                allowed = (required || origPermissions.contains(perm)
5795                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5796            } else if (bp.packageSetting == null) {
5797                // This permission is invalid; skip it.
5798                allowed = false;
5799            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5800                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5801                if (allowed) {
5802                    allowedSig = true;
5803                }
5804            } else {
5805                allowed = false;
5806            }
5807            if (DEBUG_INSTALL) {
5808                if (gp != ps) {
5809                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5810                }
5811            }
5812            if (allowed) {
5813                if (!isSystemApp(ps) && ps.permissionsFixed) {
5814                    // If this is an existing, non-system package, then
5815                    // we can't add any new permissions to it.
5816                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5817                        // Except...  if this is a permission that was added
5818                        // to the platform (note: need to only do this when
5819                        // updating the platform).
5820                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5821                    }
5822                }
5823                if (allowed) {
5824                    if (!gp.grantedPermissions.contains(perm)) {
5825                        changedPermission = true;
5826                        gp.grantedPermissions.add(perm);
5827                        gp.gids = appendInts(gp.gids, bp.gids);
5828                    } else if (!ps.haveGids) {
5829                        gp.gids = appendInts(gp.gids, bp.gids);
5830                    }
5831                } else {
5832                    Slog.w(TAG, "Not granting permission " + perm
5833                            + " to package " + pkg.packageName
5834                            + " because it was previously installed without");
5835                }
5836            } else {
5837                if (gp.grantedPermissions.remove(perm)) {
5838                    changedPermission = true;
5839                    gp.gids = removeInts(gp.gids, bp.gids);
5840                    Slog.i(TAG, "Un-granting permission " + perm
5841                            + " from package " + pkg.packageName
5842                            + " (protectionLevel=" + bp.protectionLevel
5843                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5844                            + ")");
5845                } else {
5846                    Slog.w(TAG, "Not granting permission " + perm
5847                            + " to package " + pkg.packageName
5848                            + " (protectionLevel=" + bp.protectionLevel
5849                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5850                            + ")");
5851                }
5852            }
5853        }
5854
5855        if ((changedPermission || replace) && !ps.permissionsFixed &&
5856                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
5857            // This is the first that we have heard about this package, so the
5858            // permissions we have now selected are fixed until explicitly
5859            // changed.
5860            ps.permissionsFixed = true;
5861        }
5862        ps.haveGids = true;
5863    }
5864
5865    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5866        boolean allowed = false;
5867        final int NP = PackageParser.NEW_PERMISSIONS.length;
5868        for (int ip=0; ip<NP; ip++) {
5869            final PackageParser.NewPermissionInfo npi
5870                    = PackageParser.NEW_PERMISSIONS[ip];
5871            if (npi.name.equals(perm)
5872                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5873                allowed = true;
5874                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5875                        + pkg.packageName);
5876                break;
5877            }
5878        }
5879        return allowed;
5880    }
5881
5882    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
5883                                          BasePermission bp, HashSet<String> origPermissions) {
5884        boolean allowed;
5885        allowed = (compareSignatures(
5886                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5887                        == PackageManager.SIGNATURE_MATCH)
5888                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5889                        == PackageManager.SIGNATURE_MATCH);
5890        if (!allowed && (bp.protectionLevel
5891                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5892            if (isSystemApp(pkg)) {
5893                // For updated system applications, a system permission
5894                // is granted only if it had been defined by the original application.
5895                if (isUpdatedSystemApp(pkg)) {
5896                    final PackageSetting sysPs = mSettings
5897                            .getDisabledSystemPkgLPr(pkg.packageName);
5898                    final GrantedPermissions origGp = sysPs.sharedUser != null
5899                            ? sysPs.sharedUser : sysPs;
5900
5901                    if (origGp.grantedPermissions.contains(perm)) {
5902                        // If the original was granted this permission, we take
5903                        // that grant decision as read and propagate it to the
5904                        // update.
5905                        allowed = true;
5906                    } else {
5907                        // The system apk may have been updated with an older
5908                        // version of the one on the data partition, but which
5909                        // granted a new system permission that it didn't have
5910                        // before.  In this case we do want to allow the app to
5911                        // now get the new permission if the ancestral apk is
5912                        // privileged to get it.
5913                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
5914                            for (int j=0;
5915                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
5916                                if (perm.equals(
5917                                        sysPs.pkg.requestedPermissions.get(j))) {
5918                                    allowed = true;
5919                                    break;
5920                                }
5921                            }
5922                        }
5923                    }
5924                } else {
5925                    allowed = isPrivilegedApp(pkg);
5926                }
5927            }
5928        }
5929        if (!allowed && (bp.protectionLevel
5930                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5931            // For development permissions, a development permission
5932            // is granted only if it was already granted.
5933            allowed = origPermissions.contains(perm);
5934        }
5935        return allowed;
5936    }
5937
5938    final class ActivityIntentResolver
5939            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
5940        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5941                boolean defaultOnly, int userId) {
5942            if (!sUserManager.exists(userId)) return null;
5943            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5944            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5945        }
5946
5947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5948                int userId) {
5949            if (!sUserManager.exists(userId)) return null;
5950            mFlags = flags;
5951            return super.queryIntent(intent, resolvedType,
5952                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5953        }
5954
5955        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5956                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
5957            if (!sUserManager.exists(userId)) return null;
5958            if (packageActivities == null) {
5959                return null;
5960            }
5961            mFlags = flags;
5962            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5963            final int N = packageActivities.size();
5964            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
5965                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
5966
5967            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
5968            for (int i = 0; i < N; ++i) {
5969                intentFilters = packageActivities.get(i).intents;
5970                if (intentFilters != null && intentFilters.size() > 0) {
5971                    PackageParser.ActivityIntentInfo[] array =
5972                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
5973                    intentFilters.toArray(array);
5974                    listCut.add(array);
5975                }
5976            }
5977            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5978        }
5979
5980        public final void addActivity(PackageParser.Activity a, String type) {
5981            final boolean systemApp = isSystemApp(a.info.applicationInfo);
5982            mActivities.put(a.getComponentName(), a);
5983            if (DEBUG_SHOW_INFO)
5984                Log.v(
5985                TAG, "  " + type + " " +
5986                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
5987            if (DEBUG_SHOW_INFO)
5988                Log.v(TAG, "    Class=" + a.info.name);
5989            final int NI = a.intents.size();
5990            for (int j=0; j<NI; j++) {
5991                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5992                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
5993                    intent.setPriority(0);
5994                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5995                            + a.className + " with priority > 0, forcing to 0");
5996                }
5997                if (DEBUG_SHOW_INFO) {
5998                    Log.v(TAG, "    IntentFilter:");
5999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6000                }
6001                if (!intent.debugCheck()) {
6002                    Log.w(TAG, "==> For Activity " + a.info.name);
6003                }
6004                addFilter(intent);
6005            }
6006        }
6007
6008        public final void removeActivity(PackageParser.Activity a, String type) {
6009            mActivities.remove(a.getComponentName());
6010            if (DEBUG_SHOW_INFO) {
6011                Log.v(TAG, "  " + type + " "
6012                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6013                                : a.info.name) + ":");
6014                Log.v(TAG, "    Class=" + a.info.name);
6015            }
6016            final int NI = a.intents.size();
6017            for (int j=0; j<NI; j++) {
6018                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6019                if (DEBUG_SHOW_INFO) {
6020                    Log.v(TAG, "    IntentFilter:");
6021                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6022                }
6023                removeFilter(intent);
6024            }
6025        }
6026
6027        @Override
6028        protected boolean allowFilterResult(
6029                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6030            ActivityInfo filterAi = filter.activity.info;
6031            for (int i=dest.size()-1; i>=0; i--) {
6032                ActivityInfo destAi = dest.get(i).activityInfo;
6033                if (destAi.name == filterAi.name
6034                        && destAi.packageName == filterAi.packageName) {
6035                    return false;
6036                }
6037            }
6038            return true;
6039        }
6040
6041        @Override
6042        protected ActivityIntentInfo[] newArray(int size) {
6043            return new ActivityIntentInfo[size];
6044        }
6045
6046        @Override
6047        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6048            if (!sUserManager.exists(userId)) return true;
6049            PackageParser.Package p = filter.activity.owner;
6050            if (p != null) {
6051                PackageSetting ps = (PackageSetting)p.mExtras;
6052                if (ps != null) {
6053                    // System apps are never considered stopped for purposes of
6054                    // filtering, because there may be no way for the user to
6055                    // actually re-launch them.
6056                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6057                            && ps.getStopped(userId);
6058                }
6059            }
6060            return false;
6061        }
6062
6063        @Override
6064        protected boolean isPackageForFilter(String packageName,
6065                PackageParser.ActivityIntentInfo info) {
6066            return packageName.equals(info.activity.owner.packageName);
6067        }
6068
6069        @Override
6070        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6071                int match, int userId) {
6072            if (!sUserManager.exists(userId)) return null;
6073            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6074                return null;
6075            }
6076            final PackageParser.Activity activity = info.activity;
6077            if (mSafeMode && (activity.info.applicationInfo.flags
6078                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6079                return null;
6080            }
6081            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6082            if (ps == null) {
6083                return null;
6084            }
6085            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6086                    ps.readUserState(userId), userId);
6087            if (ai == null) {
6088                return null;
6089            }
6090            final ResolveInfo res = new ResolveInfo();
6091            res.activityInfo = ai;
6092            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6093                res.filter = info;
6094            }
6095            res.priority = info.getPriority();
6096            res.preferredOrder = activity.owner.mPreferredOrder;
6097            //System.out.println("Result: " + res.activityInfo.className +
6098            //                   " = " + res.priority);
6099            res.match = match;
6100            res.isDefault = info.hasDefault;
6101            res.labelRes = info.labelRes;
6102            res.nonLocalizedLabel = info.nonLocalizedLabel;
6103            res.icon = info.icon;
6104            res.system = isSystemApp(res.activityInfo.applicationInfo);
6105            return res;
6106        }
6107
6108        @Override
6109        protected void sortResults(List<ResolveInfo> results) {
6110            Collections.sort(results, mResolvePrioritySorter);
6111        }
6112
6113        @Override
6114        protected void dumpFilter(PrintWriter out, String prefix,
6115                PackageParser.ActivityIntentInfo filter) {
6116            out.print(prefix); out.print(
6117                    Integer.toHexString(System.identityHashCode(filter.activity)));
6118                    out.print(' ');
6119                    filter.activity.printComponentShortName(out);
6120                    out.print(" filter ");
6121                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6122        }
6123
6124//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6125//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6126//            final List<ResolveInfo> retList = Lists.newArrayList();
6127//            while (i.hasNext()) {
6128//                final ResolveInfo resolveInfo = i.next();
6129//                if (isEnabledLP(resolveInfo.activityInfo)) {
6130//                    retList.add(resolveInfo);
6131//                }
6132//            }
6133//            return retList;
6134//        }
6135
6136        // Keys are String (activity class name), values are Activity.
6137        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6138                = new HashMap<ComponentName, PackageParser.Activity>();
6139        private int mFlags;
6140    }
6141
6142    private final class ServiceIntentResolver
6143            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6144        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6145                boolean defaultOnly, int userId) {
6146            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6147            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6148        }
6149
6150        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6151                int userId) {
6152            if (!sUserManager.exists(userId)) return null;
6153            mFlags = flags;
6154            return super.queryIntent(intent, resolvedType,
6155                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6156        }
6157
6158        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6159                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6160            if (!sUserManager.exists(userId)) return null;
6161            if (packageServices == null) {
6162                return null;
6163            }
6164            mFlags = flags;
6165            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6166            final int N = packageServices.size();
6167            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6168                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6169
6170            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6171            for (int i = 0; i < N; ++i) {
6172                intentFilters = packageServices.get(i).intents;
6173                if (intentFilters != null && intentFilters.size() > 0) {
6174                    PackageParser.ServiceIntentInfo[] array =
6175                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6176                    intentFilters.toArray(array);
6177                    listCut.add(array);
6178                }
6179            }
6180            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6181        }
6182
6183        public final void addService(PackageParser.Service s) {
6184            mServices.put(s.getComponentName(), s);
6185            if (DEBUG_SHOW_INFO) {
6186                Log.v(TAG, "  "
6187                        + (s.info.nonLocalizedLabel != null
6188                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6189                Log.v(TAG, "    Class=" + s.info.name);
6190            }
6191            final int NI = s.intents.size();
6192            int j;
6193            for (j=0; j<NI; j++) {
6194                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6195                if (DEBUG_SHOW_INFO) {
6196                    Log.v(TAG, "    IntentFilter:");
6197                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6198                }
6199                if (!intent.debugCheck()) {
6200                    Log.w(TAG, "==> For Service " + s.info.name);
6201                }
6202                addFilter(intent);
6203            }
6204        }
6205
6206        public final void removeService(PackageParser.Service s) {
6207            mServices.remove(s.getComponentName());
6208            if (DEBUG_SHOW_INFO) {
6209                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6210                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6211                Log.v(TAG, "    Class=" + s.info.name);
6212            }
6213            final int NI = s.intents.size();
6214            int j;
6215            for (j=0; j<NI; j++) {
6216                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6217                if (DEBUG_SHOW_INFO) {
6218                    Log.v(TAG, "    IntentFilter:");
6219                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6220                }
6221                removeFilter(intent);
6222            }
6223        }
6224
6225        @Override
6226        protected boolean allowFilterResult(
6227                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6228            ServiceInfo filterSi = filter.service.info;
6229            for (int i=dest.size()-1; i>=0; i--) {
6230                ServiceInfo destAi = dest.get(i).serviceInfo;
6231                if (destAi.name == filterSi.name
6232                        && destAi.packageName == filterSi.packageName) {
6233                    return false;
6234                }
6235            }
6236            return true;
6237        }
6238
6239        @Override
6240        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6241            return new PackageParser.ServiceIntentInfo[size];
6242        }
6243
6244        @Override
6245        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6246            if (!sUserManager.exists(userId)) return true;
6247            PackageParser.Package p = filter.service.owner;
6248            if (p != null) {
6249                PackageSetting ps = (PackageSetting)p.mExtras;
6250                if (ps != null) {
6251                    // System apps are never considered stopped for purposes of
6252                    // filtering, because there may be no way for the user to
6253                    // actually re-launch them.
6254                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6255                            && ps.getStopped(userId);
6256                }
6257            }
6258            return false;
6259        }
6260
6261        @Override
6262        protected boolean isPackageForFilter(String packageName,
6263                PackageParser.ServiceIntentInfo info) {
6264            return packageName.equals(info.service.owner.packageName);
6265        }
6266
6267        @Override
6268        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6269                int match, int userId) {
6270            if (!sUserManager.exists(userId)) return null;
6271            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6272            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6273                return null;
6274            }
6275            final PackageParser.Service service = info.service;
6276            if (mSafeMode && (service.info.applicationInfo.flags
6277                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6278                return null;
6279            }
6280            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6281            if (ps == null) {
6282                return null;
6283            }
6284            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6285                    ps.readUserState(userId), userId);
6286            if (si == null) {
6287                return null;
6288            }
6289            final ResolveInfo res = new ResolveInfo();
6290            res.serviceInfo = si;
6291            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6292                res.filter = filter;
6293            }
6294            res.priority = info.getPriority();
6295            res.preferredOrder = service.owner.mPreferredOrder;
6296            //System.out.println("Result: " + res.activityInfo.className +
6297            //                   " = " + res.priority);
6298            res.match = match;
6299            res.isDefault = info.hasDefault;
6300            res.labelRes = info.labelRes;
6301            res.nonLocalizedLabel = info.nonLocalizedLabel;
6302            res.icon = info.icon;
6303            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6304            return res;
6305        }
6306
6307        @Override
6308        protected void sortResults(List<ResolveInfo> results) {
6309            Collections.sort(results, mResolvePrioritySorter);
6310        }
6311
6312        @Override
6313        protected void dumpFilter(PrintWriter out, String prefix,
6314                PackageParser.ServiceIntentInfo filter) {
6315            out.print(prefix); out.print(
6316                    Integer.toHexString(System.identityHashCode(filter.service)));
6317                    out.print(' ');
6318                    filter.service.printComponentShortName(out);
6319                    out.print(" filter ");
6320                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6321        }
6322
6323//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6324//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6325//            final List<ResolveInfo> retList = Lists.newArrayList();
6326//            while (i.hasNext()) {
6327//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6328//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6329//                    retList.add(resolveInfo);
6330//                }
6331//            }
6332//            return retList;
6333//        }
6334
6335        // Keys are String (activity class name), values are Activity.
6336        private final HashMap<ComponentName, PackageParser.Service> mServices
6337                = new HashMap<ComponentName, PackageParser.Service>();
6338        private int mFlags;
6339    };
6340
6341    private final class ProviderIntentResolver
6342            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6343        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6344                boolean defaultOnly, int userId) {
6345            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6346            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6347        }
6348
6349        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6350                int userId) {
6351            if (!sUserManager.exists(userId))
6352                return null;
6353            mFlags = flags;
6354            return super.queryIntent(intent, resolvedType,
6355                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6356        }
6357
6358        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6359                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6360            if (!sUserManager.exists(userId))
6361                return null;
6362            if (packageProviders == null) {
6363                return null;
6364            }
6365            mFlags = flags;
6366            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6367            final int N = packageProviders.size();
6368            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6369                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6370
6371            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6372            for (int i = 0; i < N; ++i) {
6373                intentFilters = packageProviders.get(i).intents;
6374                if (intentFilters != null && intentFilters.size() > 0) {
6375                    PackageParser.ProviderIntentInfo[] array =
6376                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6377                    intentFilters.toArray(array);
6378                    listCut.add(array);
6379                }
6380            }
6381            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6382        }
6383
6384        public final void addProvider(PackageParser.Provider p) {
6385            if (mProviders.containsKey(p.getComponentName())) {
6386                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6387                return;
6388            }
6389
6390            mProviders.put(p.getComponentName(), p);
6391            if (DEBUG_SHOW_INFO) {
6392                Log.v(TAG, "  "
6393                        + (p.info.nonLocalizedLabel != null
6394                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6395                Log.v(TAG, "    Class=" + p.info.name);
6396            }
6397            final int NI = p.intents.size();
6398            int j;
6399            for (j = 0; j < NI; j++) {
6400                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6401                if (DEBUG_SHOW_INFO) {
6402                    Log.v(TAG, "    IntentFilter:");
6403                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6404                }
6405                if (!intent.debugCheck()) {
6406                    Log.w(TAG, "==> For Provider " + p.info.name);
6407                }
6408                addFilter(intent);
6409            }
6410        }
6411
6412        public final void removeProvider(PackageParser.Provider p) {
6413            mProviders.remove(p.getComponentName());
6414            if (DEBUG_SHOW_INFO) {
6415                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6416                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6417                Log.v(TAG, "    Class=" + p.info.name);
6418            }
6419            final int NI = p.intents.size();
6420            int j;
6421            for (j = 0; j < NI; j++) {
6422                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6423                if (DEBUG_SHOW_INFO) {
6424                    Log.v(TAG, "    IntentFilter:");
6425                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6426                }
6427                removeFilter(intent);
6428            }
6429        }
6430
6431        @Override
6432        protected boolean allowFilterResult(
6433                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6434            ProviderInfo filterPi = filter.provider.info;
6435            for (int i = dest.size() - 1; i >= 0; i--) {
6436                ProviderInfo destPi = dest.get(i).providerInfo;
6437                if (destPi.name == filterPi.name
6438                        && destPi.packageName == filterPi.packageName) {
6439                    return false;
6440                }
6441            }
6442            return true;
6443        }
6444
6445        @Override
6446        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6447            return new PackageParser.ProviderIntentInfo[size];
6448        }
6449
6450        @Override
6451        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6452            if (!sUserManager.exists(userId))
6453                return true;
6454            PackageParser.Package p = filter.provider.owner;
6455            if (p != null) {
6456                PackageSetting ps = (PackageSetting) p.mExtras;
6457                if (ps != null) {
6458                    // System apps are never considered stopped for purposes of
6459                    // filtering, because there may be no way for the user to
6460                    // actually re-launch them.
6461                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6462                            && ps.getStopped(userId);
6463                }
6464            }
6465            return false;
6466        }
6467
6468        @Override
6469        protected boolean isPackageForFilter(String packageName,
6470                PackageParser.ProviderIntentInfo info) {
6471            return packageName.equals(info.provider.owner.packageName);
6472        }
6473
6474        @Override
6475        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6476                int match, int userId) {
6477            if (!sUserManager.exists(userId))
6478                return null;
6479            final PackageParser.ProviderIntentInfo info = filter;
6480            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6481                return null;
6482            }
6483            final PackageParser.Provider provider = info.provider;
6484            if (mSafeMode && (provider.info.applicationInfo.flags
6485                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6486                return null;
6487            }
6488            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6489            if (ps == null) {
6490                return null;
6491            }
6492            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6493                    ps.readUserState(userId), userId);
6494            if (pi == null) {
6495                return null;
6496            }
6497            final ResolveInfo res = new ResolveInfo();
6498            res.providerInfo = pi;
6499            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6500                res.filter = filter;
6501            }
6502            res.priority = info.getPriority();
6503            res.preferredOrder = provider.owner.mPreferredOrder;
6504            res.match = match;
6505            res.isDefault = info.hasDefault;
6506            res.labelRes = info.labelRes;
6507            res.nonLocalizedLabel = info.nonLocalizedLabel;
6508            res.icon = info.icon;
6509            res.system = isSystemApp(res.providerInfo.applicationInfo);
6510            return res;
6511        }
6512
6513        @Override
6514        protected void sortResults(List<ResolveInfo> results) {
6515            Collections.sort(results, mResolvePrioritySorter);
6516        }
6517
6518        @Override
6519        protected void dumpFilter(PrintWriter out, String prefix,
6520                PackageParser.ProviderIntentInfo filter) {
6521            out.print(prefix);
6522            out.print(
6523                    Integer.toHexString(System.identityHashCode(filter.provider)));
6524            out.print(' ');
6525            filter.provider.printComponentShortName(out);
6526            out.print(" filter ");
6527            out.println(Integer.toHexString(System.identityHashCode(filter)));
6528        }
6529
6530        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6531                = new HashMap<ComponentName, PackageParser.Provider>();
6532        private int mFlags;
6533    };
6534
6535    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6536            new Comparator<ResolveInfo>() {
6537        public int compare(ResolveInfo r1, ResolveInfo r2) {
6538            int v1 = r1.priority;
6539            int v2 = r2.priority;
6540            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6541            if (v1 != v2) {
6542                return (v1 > v2) ? -1 : 1;
6543            }
6544            v1 = r1.preferredOrder;
6545            v2 = r2.preferredOrder;
6546            if (v1 != v2) {
6547                return (v1 > v2) ? -1 : 1;
6548            }
6549            if (r1.isDefault != r2.isDefault) {
6550                return r1.isDefault ? -1 : 1;
6551            }
6552            v1 = r1.match;
6553            v2 = r2.match;
6554            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6555            if (v1 != v2) {
6556                return (v1 > v2) ? -1 : 1;
6557            }
6558            if (r1.system != r2.system) {
6559                return r1.system ? -1 : 1;
6560            }
6561            return 0;
6562        }
6563    };
6564
6565    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6566            new Comparator<ProviderInfo>() {
6567        public int compare(ProviderInfo p1, ProviderInfo p2) {
6568            final int v1 = p1.initOrder;
6569            final int v2 = p2.initOrder;
6570            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6571        }
6572    };
6573
6574    static final void sendPackageBroadcast(String action, String pkg,
6575            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6576            int[] userIds) {
6577        IActivityManager am = ActivityManagerNative.getDefault();
6578        if (am != null) {
6579            try {
6580                if (userIds == null) {
6581                    userIds = am.getRunningUserIds();
6582                }
6583                for (int id : userIds) {
6584                    final Intent intent = new Intent(action,
6585                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6586                    if (extras != null) {
6587                        intent.putExtras(extras);
6588                    }
6589                    if (targetPkg != null) {
6590                        intent.setPackage(targetPkg);
6591                    }
6592                    // Modify the UID when posting to other users
6593                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6594                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6595                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6596                        intent.putExtra(Intent.EXTRA_UID, uid);
6597                    }
6598                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6599                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6600                    if (DEBUG_BROADCASTS) {
6601                        RuntimeException here = new RuntimeException("here");
6602                        here.fillInStackTrace();
6603                        Slog.d(TAG, "Sending to user " + id + ": "
6604                                + intent.toShortString(false, true, false, false)
6605                                + " " + intent.getExtras(), here);
6606                    }
6607                    am.broadcastIntent(null, intent, null, finishedReceiver,
6608                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6609                            finishedReceiver != null, false, id);
6610                }
6611            } catch (RemoteException ex) {
6612            }
6613        }
6614    }
6615
6616    /**
6617     * Check if the external storage media is available. This is true if there
6618     * is a mounted external storage medium or if the external storage is
6619     * emulated.
6620     */
6621    private boolean isExternalMediaAvailable() {
6622        return mMediaMounted || Environment.isExternalStorageEmulated();
6623    }
6624
6625    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6626        // writer
6627        synchronized (mPackages) {
6628            if (!isExternalMediaAvailable()) {
6629                // If the external storage is no longer mounted at this point,
6630                // the caller may not have been able to delete all of this
6631                // packages files and can not delete any more.  Bail.
6632                return null;
6633            }
6634            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6635            if (lastPackage != null) {
6636                pkgs.remove(lastPackage);
6637            }
6638            if (pkgs.size() > 0) {
6639                return pkgs.get(0);
6640            }
6641        }
6642        return null;
6643    }
6644
6645    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6646        if (false) {
6647            RuntimeException here = new RuntimeException("here");
6648            here.fillInStackTrace();
6649            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6650                    + " andCode=" + andCode, here);
6651        }
6652        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6653                userId, andCode ? 1 : 0, packageName));
6654    }
6655
6656    void startCleaningPackages() {
6657        // reader
6658        synchronized (mPackages) {
6659            if (!isExternalMediaAvailable()) {
6660                return;
6661            }
6662            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6663                return;
6664            }
6665        }
6666        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6667        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6668        IActivityManager am = ActivityManagerNative.getDefault();
6669        if (am != null) {
6670            try {
6671                am.startService(null, intent, null, UserHandle.USER_OWNER);
6672            } catch (RemoteException e) {
6673            }
6674        }
6675    }
6676
6677    private final class AppDirObserver extends FileObserver {
6678        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6679            super(path, mask);
6680            mRootDir = path;
6681            mIsRom = isrom;
6682            mIsPrivileged = isPrivileged;
6683        }
6684
6685        public void onEvent(int event, String path) {
6686            String removedPackage = null;
6687            int removedAppId = -1;
6688            int[] removedUsers = null;
6689            String addedPackage = null;
6690            int addedAppId = -1;
6691            int[] addedUsers = null;
6692
6693            // TODO post a message to the handler to obtain serial ordering
6694            synchronized (mInstallLock) {
6695                String fullPathStr = null;
6696                File fullPath = null;
6697                if (path != null) {
6698                    fullPath = new File(mRootDir, path);
6699                    fullPathStr = fullPath.getPath();
6700                }
6701
6702                if (DEBUG_APP_DIR_OBSERVER)
6703                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6704
6705                if (!isPackageFilename(path)) {
6706                    if (DEBUG_APP_DIR_OBSERVER)
6707                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6708                    return;
6709                }
6710
6711                // Ignore packages that are being installed or
6712                // have just been installed.
6713                if (ignoreCodePath(fullPathStr)) {
6714                    return;
6715                }
6716                PackageParser.Package p = null;
6717                PackageSetting ps = null;
6718                // reader
6719                synchronized (mPackages) {
6720                    p = mAppDirs.get(fullPathStr);
6721                    if (p != null) {
6722                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6723                        if (ps != null) {
6724                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6725                        } else {
6726                            removedUsers = sUserManager.getUserIds();
6727                        }
6728                    }
6729                    addedUsers = sUserManager.getUserIds();
6730                }
6731                if ((event&REMOVE_EVENTS) != 0) {
6732                    if (ps != null) {
6733                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6734                        removePackageLI(ps, true);
6735                        removedPackage = ps.name;
6736                        removedAppId = ps.appId;
6737                    }
6738                }
6739
6740                if ((event&ADD_EVENTS) != 0) {
6741                    if (p == null) {
6742                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6743                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6744                        if (mIsRom) {
6745                            flags |= PackageParser.PARSE_IS_SYSTEM
6746                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6747                            if (mIsPrivileged) {
6748                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6749                            }
6750                        }
6751                        p = scanPackageLI(fullPath, flags,
6752                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6753                                System.currentTimeMillis(), UserHandle.ALL);
6754                        if (p != null) {
6755                            /*
6756                             * TODO this seems dangerous as the package may have
6757                             * changed since we last acquired the mPackages
6758                             * lock.
6759                             */
6760                            // writer
6761                            synchronized (mPackages) {
6762                                updatePermissionsLPw(p.packageName, p,
6763                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6764                            }
6765                            addedPackage = p.applicationInfo.packageName;
6766                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6767                        }
6768                    }
6769                }
6770
6771                // reader
6772                synchronized (mPackages) {
6773                    mSettings.writeLPr();
6774                }
6775            }
6776
6777            if (removedPackage != null) {
6778                Bundle extras = new Bundle(1);
6779                extras.putInt(Intent.EXTRA_UID, removedAppId);
6780                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6781                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6782                        extras, null, null, removedUsers);
6783            }
6784            if (addedPackage != null) {
6785                Bundle extras = new Bundle(1);
6786                extras.putInt(Intent.EXTRA_UID, addedAppId);
6787                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6788                        extras, null, null, addedUsers);
6789            }
6790        }
6791
6792        private final String mRootDir;
6793        private final boolean mIsRom;
6794        private final boolean mIsPrivileged;
6795    }
6796
6797    /*
6798     * The old-style observer methods all just trampoline to the newer signature with
6799     * expanded install observer API.  The older API continues to work but does not
6800     * supply the additional details of the Observer2 API.
6801     */
6802
6803    /* Called when a downloaded package installation has been confirmed by the user */
6804    public void installPackage(
6805            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6806        installPackageEtc(packageURI, observer, null, flags, null);
6807    }
6808
6809    /* Called when a downloaded package installation has been confirmed by the user */
6810    public void installPackage(
6811            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6812            final String installerPackageName) {
6813        installPackageWithVerificationEtc(packageURI, observer, null, flags,
6814                installerPackageName, null, null, null);
6815    }
6816
6817    @Override
6818    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6819            int flags, String installerPackageName, Uri verificationURI,
6820            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6821        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6822                VerificationParams.NO_UID, manifestDigest);
6823        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6824                installerPackageName, verificationParams, encryptionParams);
6825    }
6826
6827    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6828            IPackageInstallObserver observer, int flags, String installerPackageName,
6829            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6830        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6831                installerPackageName, verificationParams, encryptionParams);
6832    }
6833
6834    /*
6835     * And here are the "live" versions that take both observer arguments
6836     */
6837    public void installPackageEtc(
6838            final Uri packageURI, final IPackageInstallObserver observer,
6839            IPackageInstallObserver2 observer2, final int flags) {
6840        installPackageEtc(packageURI, observer, observer2, flags, null);
6841    }
6842
6843    public void installPackageEtc(
6844            final Uri packageURI, final IPackageInstallObserver observer,
6845            final IPackageInstallObserver2 observer2, final int flags,
6846            final String installerPackageName) {
6847        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
6848                installerPackageName, null, null, null);
6849    }
6850
6851    @Override
6852    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
6853            IPackageInstallObserver2 observer2,
6854            int flags, String installerPackageName, Uri verificationURI,
6855            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6856        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6857                VerificationParams.NO_UID, manifestDigest);
6858        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
6859                installerPackageName, verificationParams, encryptionParams);
6860    }
6861
6862    /*
6863     * All of the installPackage...*() methods redirect to this one for the master implementation
6864     */
6865    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
6866            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
6867            int flags, String installerPackageName,
6868            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6869        if (observer == null && observer2 == null) {
6870            throw new IllegalArgumentException("No install observer supplied");
6871        }
6872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6873                null);
6874
6875        final int uid = Binder.getCallingUid();
6876        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
6877            try {
6878                if (observer != null) {
6879                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6880                }
6881                if (observer2 != null) {
6882                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6883                }
6884            } catch (RemoteException re) {
6885            }
6886            return;
6887        }
6888
6889        UserHandle user;
6890        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6891            user = UserHandle.ALL;
6892        } else {
6893            user = new UserHandle(UserHandle.getUserId(uid));
6894        }
6895
6896        final int filteredFlags;
6897
6898        if (uid == Process.SHELL_UID || uid == 0) {
6899            if (DEBUG_INSTALL) {
6900                Slog.v(TAG, "Install from ADB");
6901            }
6902            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6903        } else {
6904            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6905        }
6906
6907        verificationParams.setInstallerUid(uid);
6908
6909        final Message msg = mHandler.obtainMessage(INIT_COPY);
6910        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
6911                installerPackageName, verificationParams, encryptionParams, user);
6912        mHandler.sendMessage(msg);
6913    }
6914
6915    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
6916        Bundle extras = new Bundle(1);
6917        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6918
6919        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6920                packageName, extras, null, null, new int[] {userId});
6921        try {
6922            IActivityManager am = ActivityManagerNative.getDefault();
6923            final boolean isSystem =
6924                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6925            if (isSystem && am.isUserRunning(userId, false)) {
6926                // The just-installed/enabled app is bundled on the system, so presumed
6927                // to be able to run automatically without needing an explicit launch.
6928                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6929                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6930                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6931                        .setPackage(packageName);
6932                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6933                        android.app.AppOpsManager.OP_NONE, false, false, userId);
6934            }
6935        } catch (RemoteException e) {
6936            // shouldn't happen
6937            Slog.w(TAG, "Unable to bootstrap installed package", e);
6938        }
6939    }
6940
6941    @Override
6942    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
6943            int userId) {
6944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6945        PackageSetting pkgSetting;
6946        final int uid = Binder.getCallingUid();
6947        if (UserHandle.getUserId(uid) != userId) {
6948            mContext.enforceCallingOrSelfPermission(
6949                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6950                    "setApplicationBlockedSetting for user " + userId);
6951        }
6952
6953        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
6954            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
6955            return false;
6956        }
6957
6958        long callingId = Binder.clearCallingIdentity();
6959        try {
6960            boolean sendAdded = false;
6961            boolean sendRemoved = false;
6962            // writer
6963            synchronized (mPackages) {
6964                pkgSetting = mSettings.mPackages.get(packageName);
6965                if (pkgSetting == null) {
6966                    return false;
6967                }
6968                if (pkgSetting.getBlocked(userId) != blocked) {
6969                    pkgSetting.setBlocked(blocked, userId);
6970                    mSettings.writePackageRestrictionsLPr(userId);
6971                    if (blocked) {
6972                        sendRemoved = true;
6973                    } else {
6974                        sendAdded = true;
6975                    }
6976                }
6977            }
6978            if (sendAdded) {
6979                sendPackageAddedForUser(packageName, pkgSetting, userId);
6980                return true;
6981            }
6982            if (sendRemoved) {
6983                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
6984                        "blocking pkg");
6985                sendPackageBlockedForUser(packageName, pkgSetting, userId);
6986            }
6987        } finally {
6988            Binder.restoreCallingIdentity(callingId);
6989        }
6990        return false;
6991    }
6992
6993    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
6994            int userId) {
6995        final PackageRemovedInfo info = new PackageRemovedInfo();
6996        info.removedPackage = packageName;
6997        info.removedUsers = new int[] {userId};
6998        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
6999        info.sendBroadcast(false, false, false);
7000    }
7001
7002    /**
7003     * Returns true if application is not found or there was an error. Otherwise it returns
7004     * the blocked state of the package for the given user.
7005     */
7006    @Override
7007    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7008        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7009        PackageSetting pkgSetting;
7010        final int uid = Binder.getCallingUid();
7011        if (UserHandle.getUserId(uid) != userId) {
7012            mContext.enforceCallingPermission(
7013                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7014                    "getApplicationBlocked for user " + userId);
7015        }
7016        long callingId = Binder.clearCallingIdentity();
7017        try {
7018            // writer
7019            synchronized (mPackages) {
7020                pkgSetting = mSettings.mPackages.get(packageName);
7021                if (pkgSetting == null) {
7022                    return true;
7023                }
7024                return pkgSetting.getBlocked(userId);
7025            }
7026        } finally {
7027            Binder.restoreCallingIdentity(callingId);
7028        }
7029    }
7030
7031    /**
7032     * @hide
7033     */
7034    @Override
7035    public int installExistingPackageAsUser(String packageName, int userId) {
7036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7037                null);
7038        PackageSetting pkgSetting;
7039        final int uid = Binder.getCallingUid();
7040        if (UserHandle.getUserId(uid) != userId) {
7041            mContext.enforceCallingPermission(
7042                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7043                    "installExistingPackage for user " + userId);
7044        }
7045        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7046            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7047        }
7048
7049        long callingId = Binder.clearCallingIdentity();
7050        try {
7051            boolean sendAdded = false;
7052            Bundle extras = new Bundle(1);
7053
7054            // writer
7055            synchronized (mPackages) {
7056                pkgSetting = mSettings.mPackages.get(packageName);
7057                if (pkgSetting == null) {
7058                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7059                }
7060                if (!pkgSetting.getInstalled(userId)) {
7061                    pkgSetting.setInstalled(true, userId);
7062                    pkgSetting.setBlocked(false, userId);
7063                    mSettings.writePackageRestrictionsLPr(userId);
7064                    sendAdded = true;
7065                }
7066            }
7067
7068            if (sendAdded) {
7069                sendPackageAddedForUser(packageName, pkgSetting, userId);
7070            }
7071        } finally {
7072            Binder.restoreCallingIdentity(callingId);
7073        }
7074
7075        return PackageManager.INSTALL_SUCCEEDED;
7076    }
7077
7078    private boolean isUserRestricted(int userId, String restrictionKey) {
7079        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7080        if (restrictions.getBoolean(restrictionKey, false)) {
7081            Log.w(TAG, "User is restricted: " + restrictionKey);
7082            return true;
7083        }
7084        return false;
7085    }
7086
7087    @Override
7088    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7089        mContext.enforceCallingOrSelfPermission(
7090                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7091                "Only package verification agents can verify applications");
7092
7093        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7094        final PackageVerificationResponse response = new PackageVerificationResponse(
7095                verificationCode, Binder.getCallingUid());
7096        msg.arg1 = id;
7097        msg.obj = response;
7098        mHandler.sendMessage(msg);
7099    }
7100
7101    @Override
7102    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7103            long millisecondsToDelay) {
7104        mContext.enforceCallingOrSelfPermission(
7105                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7106                "Only package verification agents can extend verification timeouts");
7107
7108        final PackageVerificationState state = mPendingVerification.get(id);
7109        final PackageVerificationResponse response = new PackageVerificationResponse(
7110                verificationCodeAtTimeout, Binder.getCallingUid());
7111
7112        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7113            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7114        }
7115        if (millisecondsToDelay < 0) {
7116            millisecondsToDelay = 0;
7117        }
7118        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7119                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7120            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7121        }
7122
7123        if ((state != null) && !state.timeoutExtended()) {
7124            state.extendTimeout();
7125
7126            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7127            msg.arg1 = id;
7128            msg.obj = response;
7129            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7130        }
7131    }
7132
7133    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7134            int verificationCode, UserHandle user) {
7135        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7136        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7137        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7138        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7139        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7140
7141        mContext.sendBroadcastAsUser(intent, user,
7142                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7143    }
7144
7145    private ComponentName matchComponentForVerifier(String packageName,
7146            List<ResolveInfo> receivers) {
7147        ActivityInfo targetReceiver = null;
7148
7149        final int NR = receivers.size();
7150        for (int i = 0; i < NR; i++) {
7151            final ResolveInfo info = receivers.get(i);
7152            if (info.activityInfo == null) {
7153                continue;
7154            }
7155
7156            if (packageName.equals(info.activityInfo.packageName)) {
7157                targetReceiver = info.activityInfo;
7158                break;
7159            }
7160        }
7161
7162        if (targetReceiver == null) {
7163            return null;
7164        }
7165
7166        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7167    }
7168
7169    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7170            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7171        if (pkgInfo.verifiers.length == 0) {
7172            return null;
7173        }
7174
7175        final int N = pkgInfo.verifiers.length;
7176        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7177        for (int i = 0; i < N; i++) {
7178            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7179
7180            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7181                    receivers);
7182            if (comp == null) {
7183                continue;
7184            }
7185
7186            final int verifierUid = getUidForVerifier(verifierInfo);
7187            if (verifierUid == -1) {
7188                continue;
7189            }
7190
7191            if (DEBUG_VERIFY) {
7192                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7193                        + " with the correct signature");
7194            }
7195            sufficientVerifiers.add(comp);
7196            verificationState.addSufficientVerifier(verifierUid);
7197        }
7198
7199        return sufficientVerifiers;
7200    }
7201
7202    private int getUidForVerifier(VerifierInfo verifierInfo) {
7203        synchronized (mPackages) {
7204            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7205            if (pkg == null) {
7206                return -1;
7207            } else if (pkg.mSignatures.length != 1) {
7208                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7209                        + " has more than one signature; ignoring");
7210                return -1;
7211            }
7212
7213            /*
7214             * If the public key of the package's signature does not match
7215             * our expected public key, then this is a different package and
7216             * we should skip.
7217             */
7218
7219            final byte[] expectedPublicKey;
7220            try {
7221                final Signature verifierSig = pkg.mSignatures[0];
7222                final PublicKey publicKey = verifierSig.getPublicKey();
7223                expectedPublicKey = publicKey.getEncoded();
7224            } catch (CertificateException e) {
7225                return -1;
7226            }
7227
7228            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7229
7230            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7231                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7232                        + " does not have the expected public key; ignoring");
7233                return -1;
7234            }
7235
7236            return pkg.applicationInfo.uid;
7237        }
7238    }
7239
7240    public void finishPackageInstall(int token) {
7241        enforceSystemOrRoot("Only the system is allowed to finish installs");
7242
7243        if (DEBUG_INSTALL) {
7244            Slog.v(TAG, "BM finishing package install for " + token);
7245        }
7246
7247        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7248        mHandler.sendMessage(msg);
7249    }
7250
7251    /**
7252     * Get the verification agent timeout.
7253     *
7254     * @return verification timeout in milliseconds
7255     */
7256    private long getVerificationTimeout() {
7257        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7258                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7259                DEFAULT_VERIFICATION_TIMEOUT);
7260    }
7261
7262    /**
7263     * Get the default verification agent response code.
7264     *
7265     * @return default verification response code
7266     */
7267    private int getDefaultVerificationResponse() {
7268        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7269                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7270                DEFAULT_VERIFICATION_RESPONSE);
7271    }
7272
7273    /**
7274     * Check whether or not package verification has been enabled.
7275     *
7276     * @return true if verification should be performed
7277     */
7278    private boolean isVerificationEnabled(int flags) {
7279        if (!DEFAULT_VERIFY_ENABLE) {
7280            return false;
7281        }
7282
7283        // Check if installing from ADB
7284        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7285            // Do not run verification in a test harness environment
7286            if (ActivityManager.isRunningInTestHarness()) {
7287                return false;
7288            }
7289            // Check if the developer does not want package verification for ADB installs
7290            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7291                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7292                return false;
7293            }
7294        }
7295
7296        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7297                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7298    }
7299
7300    /**
7301     * Get the "allow unknown sources" setting.
7302     *
7303     * @return the current "allow unknown sources" setting
7304     */
7305    private int getUnknownSourcesSettings() {
7306        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7307                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7308                -1);
7309    }
7310
7311    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7312        final int uid = Binder.getCallingUid();
7313        // writer
7314        synchronized (mPackages) {
7315            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7316            if (targetPackageSetting == null) {
7317                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7318            }
7319
7320            PackageSetting installerPackageSetting;
7321            if (installerPackageName != null) {
7322                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7323                if (installerPackageSetting == null) {
7324                    throw new IllegalArgumentException("Unknown installer package: "
7325                            + installerPackageName);
7326                }
7327            } else {
7328                installerPackageSetting = null;
7329            }
7330
7331            Signature[] callerSignature;
7332            Object obj = mSettings.getUserIdLPr(uid);
7333            if (obj != null) {
7334                if (obj instanceof SharedUserSetting) {
7335                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7336                } else if (obj instanceof PackageSetting) {
7337                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7338                } else {
7339                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7340                }
7341            } else {
7342                throw new SecurityException("Unknown calling uid " + uid);
7343            }
7344
7345            // Verify: can't set installerPackageName to a package that is
7346            // not signed with the same cert as the caller.
7347            if (installerPackageSetting != null) {
7348                if (compareSignatures(callerSignature,
7349                        installerPackageSetting.signatures.mSignatures)
7350                        != PackageManager.SIGNATURE_MATCH) {
7351                    throw new SecurityException(
7352                            "Caller does not have same cert as new installer package "
7353                            + installerPackageName);
7354                }
7355            }
7356
7357            // Verify: if target already has an installer package, it must
7358            // be signed with the same cert as the caller.
7359            if (targetPackageSetting.installerPackageName != null) {
7360                PackageSetting setting = mSettings.mPackages.get(
7361                        targetPackageSetting.installerPackageName);
7362                // If the currently set package isn't valid, then it's always
7363                // okay to change it.
7364                if (setting != null) {
7365                    if (compareSignatures(callerSignature,
7366                            setting.signatures.mSignatures)
7367                            != PackageManager.SIGNATURE_MATCH) {
7368                        throw new SecurityException(
7369                                "Caller does not have same cert as old installer package "
7370                                + targetPackageSetting.installerPackageName);
7371                    }
7372                }
7373            }
7374
7375            // Okay!
7376            targetPackageSetting.installerPackageName = installerPackageName;
7377            scheduleWriteSettingsLocked();
7378        }
7379    }
7380
7381    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7382        // Queue up an async operation since the package installation may take a little while.
7383        mHandler.post(new Runnable() {
7384            public void run() {
7385                mHandler.removeCallbacks(this);
7386                 // Result object to be returned
7387                PackageInstalledInfo res = new PackageInstalledInfo();
7388                res.returnCode = currentStatus;
7389                res.uid = -1;
7390                res.pkg = null;
7391                res.removedInfo = new PackageRemovedInfo();
7392                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7393                    args.doPreInstall(res.returnCode);
7394                    synchronized (mInstallLock) {
7395                        installPackageLI(args, true, res);
7396                    }
7397                    args.doPostInstall(res.returnCode, res.uid);
7398                }
7399
7400                // A restore should be performed at this point if (a) the install
7401                // succeeded, (b) the operation is not an update, and (c) the new
7402                // package has a backupAgent defined.
7403                final boolean update = res.removedInfo.removedPackage != null;
7404                boolean doRestore = (!update
7405                        && res.pkg != null
7406                        && res.pkg.applicationInfo.backupAgentName != null);
7407
7408                // Set up the post-install work request bookkeeping.  This will be used
7409                // and cleaned up by the post-install event handling regardless of whether
7410                // there's a restore pass performed.  Token values are >= 1.
7411                int token;
7412                if (mNextInstallToken < 0) mNextInstallToken = 1;
7413                token = mNextInstallToken++;
7414
7415                PostInstallData data = new PostInstallData(args, res);
7416                mRunningInstalls.put(token, data);
7417                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7418
7419                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7420                    // Pass responsibility to the Backup Manager.  It will perform a
7421                    // restore if appropriate, then pass responsibility back to the
7422                    // Package Manager to run the post-install observer callbacks
7423                    // and broadcasts.
7424                    IBackupManager bm = IBackupManager.Stub.asInterface(
7425                            ServiceManager.getService(Context.BACKUP_SERVICE));
7426                    if (bm != null) {
7427                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7428                                + " to BM for possible restore");
7429                        try {
7430                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7431                        } catch (RemoteException e) {
7432                            // can't happen; the backup manager is local
7433                        } catch (Exception e) {
7434                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7435                            doRestore = false;
7436                        }
7437                    } else {
7438                        Slog.e(TAG, "Backup Manager not found!");
7439                        doRestore = false;
7440                    }
7441                }
7442
7443                if (!doRestore) {
7444                    // No restore possible, or the Backup Manager was mysteriously not
7445                    // available -- just fire the post-install work request directly.
7446                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7447                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7448                    mHandler.sendMessage(msg);
7449                }
7450            }
7451        });
7452    }
7453
7454    private abstract class HandlerParams {
7455        private static final int MAX_RETRIES = 4;
7456
7457        /**
7458         * Number of times startCopy() has been attempted and had a non-fatal
7459         * error.
7460         */
7461        private int mRetries = 0;
7462
7463        /** User handle for the user requesting the information or installation. */
7464        private final UserHandle mUser;
7465
7466        HandlerParams(UserHandle user) {
7467            mUser = user;
7468        }
7469
7470        UserHandle getUser() {
7471            return mUser;
7472        }
7473
7474        final boolean startCopy() {
7475            boolean res;
7476            try {
7477                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7478
7479                if (++mRetries > MAX_RETRIES) {
7480                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7481                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7482                    handleServiceError();
7483                    return false;
7484                } else {
7485                    handleStartCopy();
7486                    res = true;
7487                }
7488            } catch (RemoteException e) {
7489                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7490                mHandler.sendEmptyMessage(MCS_RECONNECT);
7491                res = false;
7492            }
7493            handleReturnCode();
7494            return res;
7495        }
7496
7497        final void serviceError() {
7498            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7499            handleServiceError();
7500            handleReturnCode();
7501        }
7502
7503        abstract void handleStartCopy() throws RemoteException;
7504        abstract void handleServiceError();
7505        abstract void handleReturnCode();
7506    }
7507
7508    class MeasureParams extends HandlerParams {
7509        private final PackageStats mStats;
7510        private boolean mSuccess;
7511
7512        private final IPackageStatsObserver mObserver;
7513
7514        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7515            super(new UserHandle(stats.userHandle));
7516            mObserver = observer;
7517            mStats = stats;
7518        }
7519
7520        @Override
7521        public String toString() {
7522            return "MeasureParams{"
7523                + Integer.toHexString(System.identityHashCode(this))
7524                + " " + mStats.packageName + "}";
7525        }
7526
7527        @Override
7528        void handleStartCopy() throws RemoteException {
7529            synchronized (mInstallLock) {
7530                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7531            }
7532
7533            final boolean mounted;
7534            if (Environment.isExternalStorageEmulated()) {
7535                mounted = true;
7536            } else {
7537                final String status = Environment.getExternalStorageState();
7538                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7539                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7540            }
7541
7542            if (mounted) {
7543                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7544
7545                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7546                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7547
7548                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7549                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7550
7551                // Always subtract cache size, since it's a subdirectory
7552                mStats.externalDataSize -= mStats.externalCacheSize;
7553
7554                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7555                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7556
7557                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7558                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7559            }
7560        }
7561
7562        @Override
7563        void handleReturnCode() {
7564            if (mObserver != null) {
7565                try {
7566                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7567                } catch (RemoteException e) {
7568                    Slog.i(TAG, "Observer no longer exists.");
7569                }
7570            }
7571        }
7572
7573        @Override
7574        void handleServiceError() {
7575            Slog.e(TAG, "Could not measure application " + mStats.packageName
7576                            + " external storage");
7577        }
7578    }
7579
7580    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7581            throws RemoteException {
7582        long result = 0;
7583        for (File path : paths) {
7584            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7585        }
7586        return result;
7587    }
7588
7589    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7590        for (File path : paths) {
7591            try {
7592                mcs.clearDirectory(path.getAbsolutePath());
7593            } catch (RemoteException e) {
7594            }
7595        }
7596    }
7597
7598    class InstallParams extends HandlerParams {
7599        final IPackageInstallObserver observer;
7600        final IPackageInstallObserver2 observer2;
7601        int flags;
7602
7603        private final Uri mPackageURI;
7604        final String installerPackageName;
7605        final VerificationParams verificationParams;
7606        private InstallArgs mArgs;
7607        private int mRet;
7608        private File mTempPackage;
7609        final ContainerEncryptionParams encryptionParams;
7610
7611        InstallParams(Uri packageURI,
7612                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7613                int flags, String installerPackageName, VerificationParams verificationParams,
7614                ContainerEncryptionParams encryptionParams, UserHandle user) {
7615            super(user);
7616            this.mPackageURI = packageURI;
7617            this.flags = flags;
7618            this.observer = observer;
7619            this.observer2 = observer2;
7620            this.installerPackageName = installerPackageName;
7621            this.verificationParams = verificationParams;
7622            this.encryptionParams = encryptionParams;
7623        }
7624
7625        @Override
7626        public String toString() {
7627            return "InstallParams{"
7628                + Integer.toHexString(System.identityHashCode(this))
7629                + " " + mPackageURI + "}";
7630        }
7631
7632        public ManifestDigest getManifestDigest() {
7633            if (verificationParams == null) {
7634                return null;
7635            }
7636            return verificationParams.getManifestDigest();
7637        }
7638
7639        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7640            String packageName = pkgLite.packageName;
7641            int installLocation = pkgLite.installLocation;
7642            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7643            // reader
7644            synchronized (mPackages) {
7645                PackageParser.Package pkg = mPackages.get(packageName);
7646                if (pkg != null) {
7647                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7648                        // Check for downgrading.
7649                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7650                            if (pkgLite.versionCode < pkg.mVersionCode) {
7651                                Slog.w(TAG, "Can't install update of " + packageName
7652                                        + " update version " + pkgLite.versionCode
7653                                        + " is older than installed version "
7654                                        + pkg.mVersionCode);
7655                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7656                            }
7657                        }
7658                        // Check for updated system application.
7659                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7660                            if (onSd) {
7661                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7662                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7663                            }
7664                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7665                        } else {
7666                            if (onSd) {
7667                                // Install flag overrides everything.
7668                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7669                            }
7670                            // If current upgrade specifies particular preference
7671                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7672                                // Application explicitly specified internal.
7673                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7674                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7675                                // App explictly prefers external. Let policy decide
7676                            } else {
7677                                // Prefer previous location
7678                                if (isExternal(pkg)) {
7679                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7680                                }
7681                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7682                            }
7683                        }
7684                    } else {
7685                        // Invalid install. Return error code
7686                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7687                    }
7688                }
7689            }
7690            // All the special cases have been taken care of.
7691            // Return result based on recommended install location.
7692            if (onSd) {
7693                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7694            }
7695            return pkgLite.recommendedInstallLocation;
7696        }
7697
7698        private long getMemoryLowThreshold() {
7699            final DeviceStorageMonitorInternal
7700                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7701            if (dsm == null) {
7702                return 0L;
7703            }
7704            return dsm.getMemoryLowThreshold();
7705        }
7706
7707        /*
7708         * Invoke remote method to get package information and install
7709         * location values. Override install location based on default
7710         * policy if needed and then create install arguments based
7711         * on the install location.
7712         */
7713        public void handleStartCopy() throws RemoteException {
7714            int ret = PackageManager.INSTALL_SUCCEEDED;
7715            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7716            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7717            PackageInfoLite pkgLite = null;
7718
7719            if (onInt && onSd) {
7720                // Check if both bits are set.
7721                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7722                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7723            } else {
7724                final long lowThreshold = getMemoryLowThreshold();
7725                if (lowThreshold == 0L) {
7726                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7727                }
7728
7729                try {
7730                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7731                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7732
7733                    final File packageFile;
7734                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7735                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7736                        if (mTempPackage != null) {
7737                            ParcelFileDescriptor out;
7738                            try {
7739                                out = ParcelFileDescriptor.open(mTempPackage,
7740                                        ParcelFileDescriptor.MODE_READ_WRITE);
7741                            } catch (FileNotFoundException e) {
7742                                out = null;
7743                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7744                            }
7745
7746                            // Make a temporary file for decryption.
7747                            ret = mContainerService
7748                                    .copyResource(mPackageURI, encryptionParams, out);
7749                            IoUtils.closeQuietly(out);
7750
7751                            packageFile = mTempPackage;
7752
7753                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7754                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7755                                            | FileUtils.S_IROTH,
7756                                    -1, -1);
7757                        } else {
7758                            packageFile = null;
7759                        }
7760                    } else {
7761                        packageFile = new File(mPackageURI.getPath());
7762                    }
7763
7764                    if (packageFile != null) {
7765                        // Remote call to find out default install location
7766                        final String packageFilePath = packageFile.getAbsolutePath();
7767                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7768                                lowThreshold);
7769
7770                        /*
7771                         * If we have too little free space, try to free cache
7772                         * before giving up.
7773                         */
7774                        if (pkgLite.recommendedInstallLocation
7775                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7776                            final long size = mContainerService.calculateInstalledSize(
7777                                    packageFilePath, isForwardLocked());
7778                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7779                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7780                                        flags, lowThreshold);
7781                            }
7782                            /*
7783                             * The cache free must have deleted the file we
7784                             * downloaded to install.
7785                             *
7786                             * TODO: fix the "freeCache" call to not delete
7787                             *       the file we care about.
7788                             */
7789                            if (pkgLite.recommendedInstallLocation
7790                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7791                                pkgLite.recommendedInstallLocation
7792                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7793                            }
7794                        }
7795                    }
7796                } finally {
7797                    mContext.revokeUriPermission(mPackageURI,
7798                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7799                }
7800            }
7801
7802            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7803                int loc = pkgLite.recommendedInstallLocation;
7804                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7805                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7806                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7807                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7808                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7809                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7810                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7811                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7812                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7813                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7814                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7815                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7816                } else {
7817                    // Override with defaults if needed.
7818                    loc = installLocationPolicy(pkgLite, flags);
7819                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7820                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7821                    } else if (!onSd && !onInt) {
7822                        // Override install location with flags
7823                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7824                            // Set the flag to install on external media.
7825                            flags |= PackageManager.INSTALL_EXTERNAL;
7826                            flags &= ~PackageManager.INSTALL_INTERNAL;
7827                        } else {
7828                            // Make sure the flag for installing on external
7829                            // media is unset
7830                            flags |= PackageManager.INSTALL_INTERNAL;
7831                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7832                        }
7833                    }
7834                }
7835            }
7836
7837            final InstallArgs args = createInstallArgs(this);
7838            mArgs = args;
7839
7840            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7841                 /*
7842                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
7843                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
7844                 */
7845                int userIdentifier = getUser().getIdentifier();
7846                if (userIdentifier == UserHandle.USER_ALL
7847                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
7848                    userIdentifier = UserHandle.USER_OWNER;
7849                }
7850
7851                /*
7852                 * Determine if we have any installed package verifiers. If we
7853                 * do, then we'll defer to them to verify the packages.
7854                 */
7855                final int requiredUid = mRequiredVerifierPackage == null ? -1
7856                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
7857                if (requiredUid != -1 && isVerificationEnabled(flags)) {
7858                    final Intent verification = new Intent(
7859                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
7860                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
7861                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7862
7863                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
7864                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
7865                            0 /* TODO: Which userId? */);
7866
7867                    if (DEBUG_VERIFY) {
7868                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
7869                                + verification.toString() + " with " + pkgLite.verifiers.length
7870                                + " optional verifiers");
7871                    }
7872
7873                    final int verificationId = mPendingVerificationToken++;
7874
7875                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7876
7877                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
7878                            installerPackageName);
7879
7880                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
7881
7882                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
7883                            pkgLite.packageName);
7884
7885                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
7886                            pkgLite.versionCode);
7887
7888                    if (verificationParams != null) {
7889                        if (verificationParams.getVerificationURI() != null) {
7890                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
7891                                 verificationParams.getVerificationURI());
7892                        }
7893                        if (verificationParams.getOriginatingURI() != null) {
7894                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
7895                                  verificationParams.getOriginatingURI());
7896                        }
7897                        if (verificationParams.getReferrer() != null) {
7898                            verification.putExtra(Intent.EXTRA_REFERRER,
7899                                  verificationParams.getReferrer());
7900                        }
7901                        if (verificationParams.getOriginatingUid() >= 0) {
7902                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
7903                                  verificationParams.getOriginatingUid());
7904                        }
7905                        if (verificationParams.getInstallerUid() >= 0) {
7906                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
7907                                  verificationParams.getInstallerUid());
7908                        }
7909                    }
7910
7911                    final PackageVerificationState verificationState = new PackageVerificationState(
7912                            requiredUid, args);
7913
7914                    mPendingVerification.append(verificationId, verificationState);
7915
7916                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7917                            receivers, verificationState);
7918
7919                    /*
7920                     * If any sufficient verifiers were listed in the package
7921                     * manifest, attempt to ask them.
7922                     */
7923                    if (sufficientVerifiers != null) {
7924                        final int N = sufficientVerifiers.size();
7925                        if (N == 0) {
7926                            Slog.i(TAG, "Additional verifiers required, but none installed.");
7927                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7928                        } else {
7929                            for (int i = 0; i < N; i++) {
7930                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
7931
7932                                final Intent sufficientIntent = new Intent(verification);
7933                                sufficientIntent.setComponent(verifierComponent);
7934
7935                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
7936                            }
7937                        }
7938                    }
7939
7940                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7941                            mRequiredVerifierPackage, receivers);
7942                    if (ret == PackageManager.INSTALL_SUCCEEDED
7943                            && mRequiredVerifierPackage != null) {
7944                        /*
7945                         * Send the intent to the required verification agent,
7946                         * but only start the verification timeout after the
7947                         * target BroadcastReceivers have run.
7948                         */
7949                        verification.setComponent(requiredVerifierComponent);
7950                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
7951                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7952                                new BroadcastReceiver() {
7953                                    @Override
7954                                    public void onReceive(Context context, Intent intent) {
7955                                        final Message msg = mHandler
7956                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
7957                                        msg.arg1 = verificationId;
7958                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7959                                    }
7960                                }, null, 0, null, null);
7961
7962                        /*
7963                         * We don't want the copy to proceed until verification
7964                         * succeeds, so null out this field.
7965                         */
7966                        mArgs = null;
7967                    }
7968                } else {
7969                    /*
7970                     * No package verification is enabled, so immediately start
7971                     * the remote call to initiate copy using temporary file.
7972                     */
7973                    ret = args.copyApk(mContainerService, true);
7974                }
7975            }
7976
7977            mRet = ret;
7978        }
7979
7980        @Override
7981        void handleReturnCode() {
7982            // If mArgs is null, then MCS couldn't be reached. When it
7983            // reconnects, it will try again to install. At that point, this
7984            // will succeed.
7985            if (mArgs != null) {
7986                processPendingInstall(mArgs, mRet);
7987
7988                if (mTempPackage != null) {
7989                    if (!mTempPackage.delete()) {
7990                        Slog.w(TAG, "Couldn't delete temporary file: " +
7991                                mTempPackage.getAbsolutePath());
7992                    }
7993                }
7994            }
7995        }
7996
7997        @Override
7998        void handleServiceError() {
7999            mArgs = createInstallArgs(this);
8000            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8001        }
8002
8003        public boolean isForwardLocked() {
8004            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8005        }
8006
8007        public Uri getPackageUri() {
8008            if (mTempPackage != null) {
8009                return Uri.fromFile(mTempPackage);
8010            } else {
8011                return mPackageURI;
8012            }
8013        }
8014    }
8015
8016    /*
8017     * Utility class used in movePackage api.
8018     * srcArgs and targetArgs are not set for invalid flags and make
8019     * sure to do null checks when invoking methods on them.
8020     * We probably want to return ErrorPrams for both failed installs
8021     * and moves.
8022     */
8023    class MoveParams extends HandlerParams {
8024        final IPackageMoveObserver observer;
8025        final int flags;
8026        final String packageName;
8027        final InstallArgs srcArgs;
8028        final InstallArgs targetArgs;
8029        int uid;
8030        int mRet;
8031
8032        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8033                String packageName, String dataDir, int uid, UserHandle user) {
8034            super(user);
8035            this.srcArgs = srcArgs;
8036            this.observer = observer;
8037            this.flags = flags;
8038            this.packageName = packageName;
8039            this.uid = uid;
8040            if (srcArgs != null) {
8041                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8042                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
8043            } else {
8044                targetArgs = null;
8045            }
8046        }
8047
8048        @Override
8049        public String toString() {
8050            return "MoveParams{"
8051                + Integer.toHexString(System.identityHashCode(this))
8052                + " " + packageName + "}";
8053        }
8054
8055        public void handleStartCopy() throws RemoteException {
8056            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8057            // Check for storage space on target medium
8058            if (!targetArgs.checkFreeStorage(mContainerService)) {
8059                Log.w(TAG, "Insufficient storage to install");
8060                return;
8061            }
8062
8063            mRet = srcArgs.doPreCopy();
8064            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8065                return;
8066            }
8067
8068            mRet = targetArgs.copyApk(mContainerService, false);
8069            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8070                srcArgs.doPostCopy(uid);
8071                return;
8072            }
8073
8074            mRet = srcArgs.doPostCopy(uid);
8075            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8076                return;
8077            }
8078
8079            mRet = targetArgs.doPreInstall(mRet);
8080            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8081                return;
8082            }
8083
8084            if (DEBUG_SD_INSTALL) {
8085                StringBuilder builder = new StringBuilder();
8086                if (srcArgs != null) {
8087                    builder.append("src: ");
8088                    builder.append(srcArgs.getCodePath());
8089                }
8090                if (targetArgs != null) {
8091                    builder.append(" target : ");
8092                    builder.append(targetArgs.getCodePath());
8093                }
8094                Log.i(TAG, builder.toString());
8095            }
8096        }
8097
8098        @Override
8099        void handleReturnCode() {
8100            targetArgs.doPostInstall(mRet, uid);
8101            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8102            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8103                currentStatus = PackageManager.MOVE_SUCCEEDED;
8104            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8105                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8106            }
8107            processPendingMove(this, currentStatus);
8108        }
8109
8110        @Override
8111        void handleServiceError() {
8112            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8113        }
8114    }
8115
8116    /**
8117     * Used during creation of InstallArgs
8118     *
8119     * @param flags package installation flags
8120     * @return true if should be installed on external storage
8121     */
8122    private static boolean installOnSd(int flags) {
8123        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8124            return false;
8125        }
8126        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8127            return true;
8128        }
8129        return false;
8130    }
8131
8132    /**
8133     * Used during creation of InstallArgs
8134     *
8135     * @param flags package installation flags
8136     * @return true if should be installed as forward locked
8137     */
8138    private static boolean installForwardLocked(int flags) {
8139        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8140    }
8141
8142    private InstallArgs createInstallArgs(InstallParams params) {
8143        if (installOnSd(params.flags) || params.isForwardLocked()) {
8144            return new AsecInstallArgs(params);
8145        } else {
8146            return new FileInstallArgs(params);
8147        }
8148    }
8149
8150    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8151            String nativeLibraryPath) {
8152        final boolean isInAsec;
8153        if (installOnSd(flags)) {
8154            /* Apps on SD card are always in ASEC containers. */
8155            isInAsec = true;
8156        } else if (installForwardLocked(flags)
8157                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8158            /*
8159             * Forward-locked apps are only in ASEC containers if they're the
8160             * new style
8161             */
8162            isInAsec = true;
8163        } else {
8164            isInAsec = false;
8165        }
8166
8167        if (isInAsec) {
8168            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8169                    installOnSd(flags), installForwardLocked(flags));
8170        } else {
8171            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
8172        }
8173    }
8174
8175    // Used by package mover
8176    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
8177        if (installOnSd(flags) || installForwardLocked(flags)) {
8178            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8179                    + AsecInstallArgs.RES_FILE_NAME);
8180            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
8181                    installForwardLocked(flags));
8182        } else {
8183            return new FileInstallArgs(packageURI, pkgName, dataDir);
8184        }
8185    }
8186
8187    static abstract class InstallArgs {
8188        final IPackageInstallObserver observer;
8189        final IPackageInstallObserver2 observer2;
8190        // Always refers to PackageManager flags only
8191        final int flags;
8192        final Uri packageURI;
8193        final String installerPackageName;
8194        final ManifestDigest manifestDigest;
8195        final UserHandle user;
8196
8197        InstallArgs(Uri packageURI,
8198                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8199                int flags, String installerPackageName, ManifestDigest manifestDigest,
8200                UserHandle user) {
8201            this.packageURI = packageURI;
8202            this.flags = flags;
8203            this.observer = observer;
8204            this.observer2 = observer2;
8205            this.installerPackageName = installerPackageName;
8206            this.manifestDigest = manifestDigest;
8207            this.user = user;
8208        }
8209
8210        abstract void createCopyFile();
8211        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8212        abstract int doPreInstall(int status);
8213        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8214
8215        abstract int doPostInstall(int status, int uid);
8216        abstract String getCodePath();
8217        abstract String getResourcePath();
8218        abstract String getNativeLibraryPath();
8219        // Need installer lock especially for dex file removal.
8220        abstract void cleanUpResourcesLI();
8221        abstract boolean doPostDeleteLI(boolean delete);
8222        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8223
8224        /**
8225         * Called before the source arguments are copied. This is used mostly
8226         * for MoveParams when it needs to read the source file to put it in the
8227         * destination.
8228         */
8229        int doPreCopy() {
8230            return PackageManager.INSTALL_SUCCEEDED;
8231        }
8232
8233        /**
8234         * Called after the source arguments are copied. This is used mostly for
8235         * MoveParams when it needs to read the source file to put it in the
8236         * destination.
8237         *
8238         * @return
8239         */
8240        int doPostCopy(int uid) {
8241            return PackageManager.INSTALL_SUCCEEDED;
8242        }
8243
8244        protected boolean isFwdLocked() {
8245            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8246        }
8247
8248        UserHandle getUser() {
8249            return user;
8250        }
8251    }
8252
8253    class FileInstallArgs extends InstallArgs {
8254        File installDir;
8255        String codeFileName;
8256        String resourceFileName;
8257        String libraryPath;
8258        boolean created = false;
8259
8260        FileInstallArgs(InstallParams params) {
8261            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8262                    params.installerPackageName, params.getManifestDigest(),
8263                    params.getUser());
8264        }
8265
8266        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
8267            super(null, null, null, 0, null, null, null);
8268            File codeFile = new File(fullCodePath);
8269            installDir = codeFile.getParentFile();
8270            codeFileName = fullCodePath;
8271            resourceFileName = fullResourcePath;
8272            libraryPath = nativeLibraryPath;
8273        }
8274
8275        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
8276            super(packageURI, null, null, 0, null, null, null);
8277            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8278            String apkName = getNextCodePath(null, pkgName, ".apk");
8279            codeFileName = new File(installDir, apkName + ".apk").getPath();
8280            resourceFileName = getResourcePathFromCodePath();
8281            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8282        }
8283
8284        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8285            final long lowThreshold;
8286
8287            final DeviceStorageMonitorInternal
8288                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8289            if (dsm == null) {
8290                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8291                lowThreshold = 0L;
8292            } else {
8293                if (dsm.isMemoryLow()) {
8294                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8295                    return false;
8296                }
8297
8298                lowThreshold = dsm.getMemoryLowThreshold();
8299            }
8300
8301            try {
8302                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8303                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8304                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8305            } finally {
8306                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8307            }
8308        }
8309
8310        String getCodePath() {
8311            return codeFileName;
8312        }
8313
8314        void createCopyFile() {
8315            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8316            codeFileName = createTempPackageFile(installDir).getPath();
8317            resourceFileName = getResourcePathFromCodePath();
8318            libraryPath = getLibraryPathFromCodePath();
8319            created = true;
8320        }
8321
8322        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8323            if (temp) {
8324                // Generate temp file name
8325                createCopyFile();
8326            }
8327            // Get a ParcelFileDescriptor to write to the output file
8328            File codeFile = new File(codeFileName);
8329            if (!created) {
8330                try {
8331                    codeFile.createNewFile();
8332                    // Set permissions
8333                    if (!setPermissions()) {
8334                        // Failed setting permissions.
8335                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8336                    }
8337                } catch (IOException e) {
8338                   Slog.w(TAG, "Failed to create file " + codeFile);
8339                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8340                }
8341            }
8342            ParcelFileDescriptor out = null;
8343            try {
8344                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8345            } catch (FileNotFoundException e) {
8346                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8347                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8348            }
8349            // Copy the resource now
8350            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8351            try {
8352                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8353                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8354                ret = imcs.copyResource(packageURI, null, out);
8355            } finally {
8356                IoUtils.closeQuietly(out);
8357                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8358            }
8359
8360            if (isFwdLocked()) {
8361                final File destResourceFile = new File(getResourcePath());
8362
8363                // Copy the public files
8364                try {
8365                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8366                } catch (IOException e) {
8367                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8368                            + " forward-locked app.");
8369                    destResourceFile.delete();
8370                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8371                }
8372            }
8373
8374            final File nativeLibraryFile = new File(getNativeLibraryPath());
8375            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8376            if (nativeLibraryFile.exists()) {
8377                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8378                nativeLibraryFile.delete();
8379            }
8380            try {
8381                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8382                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
8383                    return copyRet;
8384                }
8385            } catch (IOException e) {
8386                Slog.e(TAG, "Copying native libraries failed", e);
8387                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8388            }
8389
8390            return ret;
8391        }
8392
8393        int doPreInstall(int status) {
8394            if (status != PackageManager.INSTALL_SUCCEEDED) {
8395                cleanUp();
8396            }
8397            return status;
8398        }
8399
8400        boolean doRename(int status, final String pkgName, String oldCodePath) {
8401            if (status != PackageManager.INSTALL_SUCCEEDED) {
8402                cleanUp();
8403                return false;
8404            } else {
8405                final File oldCodeFile = new File(getCodePath());
8406                final File oldResourceFile = new File(getResourcePath());
8407                final File oldLibraryFile = new File(getNativeLibraryPath());
8408
8409                // Rename APK file based on packageName
8410                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8411                final File newCodeFile = new File(installDir, apkName + ".apk");
8412                if (!oldCodeFile.renameTo(newCodeFile)) {
8413                    return false;
8414                }
8415                codeFileName = newCodeFile.getPath();
8416
8417                // Rename public resource file if it's forward-locked.
8418                final File newResFile = new File(getResourcePathFromCodePath());
8419                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8420                    return false;
8421                }
8422                resourceFileName = newResFile.getPath();
8423
8424                // Rename library path
8425                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8426                if (newLibraryFile.exists()) {
8427                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8428                    newLibraryFile.delete();
8429                }
8430                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8431                    Slog.e(TAG, "Cannot rename native library directory "
8432                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8433                    return false;
8434                }
8435                libraryPath = newLibraryFile.getPath();
8436
8437                // Attempt to set permissions
8438                if (!setPermissions()) {
8439                    return false;
8440                }
8441
8442                if (!SELinux.restorecon(newCodeFile)) {
8443                    return false;
8444                }
8445
8446                return true;
8447            }
8448        }
8449
8450        int doPostInstall(int status, int uid) {
8451            if (status != PackageManager.INSTALL_SUCCEEDED) {
8452                cleanUp();
8453            }
8454            return status;
8455        }
8456
8457        String getResourcePath() {
8458            return resourceFileName;
8459        }
8460
8461        private String getResourcePathFromCodePath() {
8462            final String codePath = getCodePath();
8463            if (isFwdLocked()) {
8464                final StringBuilder sb = new StringBuilder();
8465
8466                sb.append(mAppInstallDir.getPath());
8467                sb.append('/');
8468                sb.append(getApkName(codePath));
8469                sb.append(".zip");
8470
8471                /*
8472                 * If our APK is a temporary file, mark the resource as a
8473                 * temporary file as well so it can be cleaned up after
8474                 * catastrophic failure.
8475                 */
8476                if (codePath.endsWith(".tmp")) {
8477                    sb.append(".tmp");
8478                }
8479
8480                return sb.toString();
8481            } else {
8482                return codePath;
8483            }
8484        }
8485
8486        private String getLibraryPathFromCodePath() {
8487            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8488        }
8489
8490        @Override
8491        String getNativeLibraryPath() {
8492            if (libraryPath == null) {
8493                libraryPath = getLibraryPathFromCodePath();
8494            }
8495            return libraryPath;
8496        }
8497
8498        private boolean cleanUp() {
8499            boolean ret = true;
8500            String sourceDir = getCodePath();
8501            String publicSourceDir = getResourcePath();
8502            if (sourceDir != null) {
8503                File sourceFile = new File(sourceDir);
8504                if (!sourceFile.exists()) {
8505                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8506                    ret = false;
8507                }
8508                // Delete application's code and resources
8509                sourceFile.delete();
8510            }
8511            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8512                final File publicSourceFile = new File(publicSourceDir);
8513                if (!publicSourceFile.exists()) {
8514                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8515                }
8516                if (publicSourceFile.exists()) {
8517                    publicSourceFile.delete();
8518                }
8519            }
8520
8521            if (libraryPath != null) {
8522                File nativeLibraryFile = new File(libraryPath);
8523                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8524                if (!nativeLibraryFile.delete()) {
8525                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8526                }
8527            }
8528
8529            return ret;
8530        }
8531
8532        void cleanUpResourcesLI() {
8533            String sourceDir = getCodePath();
8534            if (cleanUp()) {
8535                int retCode = mInstaller.rmdex(sourceDir);
8536                if (retCode < 0) {
8537                    Slog.w(TAG, "Couldn't remove dex file for package: "
8538                            +  " at location "
8539                            + sourceDir + ", retcode=" + retCode);
8540                    // we don't consider this to be a failure of the core package deletion
8541                }
8542            }
8543        }
8544
8545        private boolean setPermissions() {
8546            // TODO Do this in a more elegant way later on. for now just a hack
8547            if (!isFwdLocked()) {
8548                final int filePermissions =
8549                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8550                    |FileUtils.S_IROTH;
8551                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8552                if (retCode != 0) {
8553                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8554                            getCodePath()
8555                            + ". The return code was: " + retCode);
8556                    // TODO Define new internal error
8557                    return false;
8558                }
8559                return true;
8560            }
8561            return true;
8562        }
8563
8564        boolean doPostDeleteLI(boolean delete) {
8565            // XXX err, shouldn't we respect the delete flag?
8566            cleanUpResourcesLI();
8567            return true;
8568        }
8569    }
8570
8571    private boolean isAsecExternal(String cid) {
8572        final String asecPath = PackageHelper.getSdFilesystem(cid);
8573        return !asecPath.startsWith(mAsecInternalPath);
8574    }
8575
8576    /**
8577     * Extract the MountService "container ID" from the full code path of an
8578     * .apk.
8579     */
8580    static String cidFromCodePath(String fullCodePath) {
8581        int eidx = fullCodePath.lastIndexOf("/");
8582        String subStr1 = fullCodePath.substring(0, eidx);
8583        int sidx = subStr1.lastIndexOf("/");
8584        return subStr1.substring(sidx+1, eidx);
8585    }
8586
8587    class AsecInstallArgs extends InstallArgs {
8588        static final String RES_FILE_NAME = "pkg.apk";
8589        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8590
8591        String cid;
8592        String packagePath;
8593        String resourcePath;
8594        String libraryPath;
8595
8596        AsecInstallArgs(InstallParams params) {
8597            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8598                    params.installerPackageName, params.getManifestDigest(),
8599                    params.getUser());
8600        }
8601
8602        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8603                boolean isExternal, boolean isForwardLocked) {
8604            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8605                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8606                    null, null, null);
8607            // Extract cid from fullCodePath
8608            int eidx = fullCodePath.lastIndexOf("/");
8609            String subStr1 = fullCodePath.substring(0, eidx);
8610            int sidx = subStr1.lastIndexOf("/");
8611            cid = subStr1.substring(sidx+1, eidx);
8612            setCachePath(subStr1);
8613        }
8614
8615        AsecInstallArgs(String cid, boolean isForwardLocked) {
8616            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8617                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8618                    null, null, null);
8619            this.cid = cid;
8620            setCachePath(PackageHelper.getSdDir(cid));
8621        }
8622
8623        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
8624            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8625                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8626                    null, null, null);
8627            this.cid = cid;
8628        }
8629
8630        void createCopyFile() {
8631            cid = getTempContainerId();
8632        }
8633
8634        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8635            try {
8636                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8637                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8638                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8639            } finally {
8640                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8641            }
8642        }
8643
8644        private final boolean isExternal() {
8645            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8646        }
8647
8648        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8649            if (temp) {
8650                createCopyFile();
8651            } else {
8652                /*
8653                 * Pre-emptively destroy the container since it's destroyed if
8654                 * copying fails due to it existing anyway.
8655                 */
8656                PackageHelper.destroySdDir(cid);
8657            }
8658
8659            final String newCachePath;
8660            try {
8661                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8662                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8663                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8664                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8665            } finally {
8666                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8667            }
8668
8669            if (newCachePath != null) {
8670                setCachePath(newCachePath);
8671                return PackageManager.INSTALL_SUCCEEDED;
8672            } else {
8673                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8674            }
8675        }
8676
8677        @Override
8678        String getCodePath() {
8679            return packagePath;
8680        }
8681
8682        @Override
8683        String getResourcePath() {
8684            return resourcePath;
8685        }
8686
8687        @Override
8688        String getNativeLibraryPath() {
8689            return libraryPath;
8690        }
8691
8692        int doPreInstall(int status) {
8693            if (status != PackageManager.INSTALL_SUCCEEDED) {
8694                // Destroy container
8695                PackageHelper.destroySdDir(cid);
8696            } else {
8697                boolean mounted = PackageHelper.isContainerMounted(cid);
8698                if (!mounted) {
8699                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8700                            Process.SYSTEM_UID);
8701                    if (newCachePath != null) {
8702                        setCachePath(newCachePath);
8703                    } else {
8704                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8705                    }
8706                }
8707            }
8708            return status;
8709        }
8710
8711        boolean doRename(int status, final String pkgName,
8712                String oldCodePath) {
8713            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8714            String newCachePath = null;
8715            if (PackageHelper.isContainerMounted(cid)) {
8716                // Unmount the container
8717                if (!PackageHelper.unMountSdDir(cid)) {
8718                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8719                    return false;
8720                }
8721            }
8722            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8723                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8724                        " which might be stale. Will try to clean up.");
8725                // Clean up the stale container and proceed to recreate.
8726                if (!PackageHelper.destroySdDir(newCacheId)) {
8727                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8728                    return false;
8729                }
8730                // Successfully cleaned up stale container. Try to rename again.
8731                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8732                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8733                            + " inspite of cleaning it up.");
8734                    return false;
8735                }
8736            }
8737            if (!PackageHelper.isContainerMounted(newCacheId)) {
8738                Slog.w(TAG, "Mounting container " + newCacheId);
8739                newCachePath = PackageHelper.mountSdDir(newCacheId,
8740                        getEncryptKey(), Process.SYSTEM_UID);
8741            } else {
8742                newCachePath = PackageHelper.getSdDir(newCacheId);
8743            }
8744            if (newCachePath == null) {
8745                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8746                return false;
8747            }
8748            Log.i(TAG, "Succesfully renamed " + cid +
8749                    " to " + newCacheId +
8750                    " at new path: " + newCachePath);
8751            cid = newCacheId;
8752            setCachePath(newCachePath);
8753            return true;
8754        }
8755
8756        private void setCachePath(String newCachePath) {
8757            File cachePath = new File(newCachePath);
8758            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8759            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8760
8761            if (isFwdLocked()) {
8762                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8763            } else {
8764                resourcePath = packagePath;
8765            }
8766        }
8767
8768        int doPostInstall(int status, int uid) {
8769            if (status != PackageManager.INSTALL_SUCCEEDED) {
8770                cleanUp();
8771            } else {
8772                final int groupOwner;
8773                final String protectedFile;
8774                if (isFwdLocked()) {
8775                    groupOwner = UserHandle.getSharedAppGid(uid);
8776                    protectedFile = RES_FILE_NAME;
8777                } else {
8778                    groupOwner = -1;
8779                    protectedFile = null;
8780                }
8781
8782                if (uid < Process.FIRST_APPLICATION_UID
8783                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8784                    Slog.e(TAG, "Failed to finalize " + cid);
8785                    PackageHelper.destroySdDir(cid);
8786                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8787                }
8788
8789                boolean mounted = PackageHelper.isContainerMounted(cid);
8790                if (!mounted) {
8791                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8792                }
8793            }
8794            return status;
8795        }
8796
8797        private void cleanUp() {
8798            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8799
8800            // Destroy secure container
8801            PackageHelper.destroySdDir(cid);
8802        }
8803
8804        void cleanUpResourcesLI() {
8805            String sourceFile = getCodePath();
8806            // Remove dex file
8807            int retCode = mInstaller.rmdex(sourceFile);
8808            if (retCode < 0) {
8809                Slog.w(TAG, "Couldn't remove dex file for package: "
8810                        + " at location "
8811                        + sourceFile.toString() + ", retcode=" + retCode);
8812                // we don't consider this to be a failure of the core package deletion
8813            }
8814            cleanUp();
8815        }
8816
8817        boolean matchContainer(String app) {
8818            if (cid.startsWith(app)) {
8819                return true;
8820            }
8821            return false;
8822        }
8823
8824        String getPackageName() {
8825            return getAsecPackageName(cid);
8826        }
8827
8828        boolean doPostDeleteLI(boolean delete) {
8829            boolean ret = false;
8830            boolean mounted = PackageHelper.isContainerMounted(cid);
8831            if (mounted) {
8832                // Unmount first
8833                ret = PackageHelper.unMountSdDir(cid);
8834            }
8835            if (ret && delete) {
8836                cleanUpResourcesLI();
8837            }
8838            return ret;
8839        }
8840
8841        @Override
8842        int doPreCopy() {
8843            if (isFwdLocked()) {
8844                if (!PackageHelper.fixSdPermissions(cid,
8845                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
8846                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8847                }
8848            }
8849
8850            return PackageManager.INSTALL_SUCCEEDED;
8851        }
8852
8853        @Override
8854        int doPostCopy(int uid) {
8855            if (isFwdLocked()) {
8856                if (uid < Process.FIRST_APPLICATION_UID
8857                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
8858                                RES_FILE_NAME)) {
8859                    Slog.e(TAG, "Failed to finalize " + cid);
8860                    PackageHelper.destroySdDir(cid);
8861                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8862                }
8863            }
8864
8865            return PackageManager.INSTALL_SUCCEEDED;
8866        }
8867    };
8868
8869    static String getAsecPackageName(String packageCid) {
8870        int idx = packageCid.lastIndexOf("-");
8871        if (idx == -1) {
8872            return packageCid;
8873        }
8874        return packageCid.substring(0, idx);
8875    }
8876
8877    // Utility method used to create code paths based on package name and available index.
8878    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
8879        String idxStr = "";
8880        int idx = 1;
8881        // Fall back to default value of idx=1 if prefix is not
8882        // part of oldCodePath
8883        if (oldCodePath != null) {
8884            String subStr = oldCodePath;
8885            // Drop the suffix right away
8886            if (subStr.endsWith(suffix)) {
8887                subStr = subStr.substring(0, subStr.length() - suffix.length());
8888            }
8889            // If oldCodePath already contains prefix find out the
8890            // ending index to either increment or decrement.
8891            int sidx = subStr.lastIndexOf(prefix);
8892            if (sidx != -1) {
8893                subStr = subStr.substring(sidx + prefix.length());
8894                if (subStr != null) {
8895                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
8896                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
8897                    }
8898                    try {
8899                        idx = Integer.parseInt(subStr);
8900                        if (idx <= 1) {
8901                            idx++;
8902                        } else {
8903                            idx--;
8904                        }
8905                    } catch(NumberFormatException e) {
8906                    }
8907                }
8908            }
8909        }
8910        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
8911        return prefix + idxStr;
8912    }
8913
8914    // Utility method used to ignore ADD/REMOVE events
8915    // by directory observer.
8916    private static boolean ignoreCodePath(String fullPathStr) {
8917        String apkName = getApkName(fullPathStr);
8918        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8919        if (idx != -1 && ((idx+1) < apkName.length())) {
8920            // Make sure the package ends with a numeral
8921            String version = apkName.substring(idx+1);
8922            try {
8923                Integer.parseInt(version);
8924                return true;
8925            } catch (NumberFormatException e) {}
8926        }
8927        return false;
8928    }
8929
8930    // Utility method that returns the relative package path with respect
8931    // to the installation directory. Like say for /data/data/com.test-1.apk
8932    // string com.test-1 is returned.
8933    static String getApkName(String codePath) {
8934        if (codePath == null) {
8935            return null;
8936        }
8937        int sidx = codePath.lastIndexOf("/");
8938        int eidx = codePath.lastIndexOf(".");
8939        if (eidx == -1) {
8940            eidx = codePath.length();
8941        } else if (eidx == 0) {
8942            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
8943            return null;
8944        }
8945        return codePath.substring(sidx+1, eidx);
8946    }
8947
8948    class PackageInstalledInfo {
8949        String name;
8950        int uid;
8951        // The set of users that originally had this package installed.
8952        int[] origUsers;
8953        // The set of users that now have this package installed.
8954        int[] newUsers;
8955        PackageParser.Package pkg;
8956        int returnCode;
8957        PackageRemovedInfo removedInfo;
8958
8959        // In some error cases we want to convey more info back to the observer
8960        String origPackage;
8961        String origPermission;
8962    }
8963
8964    /*
8965     * Install a non-existing package.
8966     */
8967    private void installNewPackageLI(PackageParser.Package pkg,
8968            int parseFlags, int scanMode, UserHandle user,
8969            String installerPackageName, PackageInstalledInfo res) {
8970        // Remember this for later, in case we need to rollback this install
8971        String pkgName = pkg.packageName;
8972
8973        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
8974        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
8975        synchronized(mPackages) {
8976            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8977                // A package with the same name is already installed, though
8978                // it has been renamed to an older name.  The package we
8979                // are trying to install should be installed as an update to
8980                // the existing one, but that has not been requested, so bail.
8981                Slog.w(TAG, "Attempt to re-install " + pkgName
8982                        + " without first uninstalling package running as "
8983                        + mSettings.mRenamedPackages.get(pkgName));
8984                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8985                return;
8986            }
8987            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
8988                // Don't allow installation over an existing package with the same name.
8989                Slog.w(TAG, "Attempt to re-install " + pkgName
8990                        + " without first uninstalling.");
8991                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8992                return;
8993            }
8994        }
8995        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8996        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
8997                System.currentTimeMillis(), user);
8998        if (newPackage == null) {
8999            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9000            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9001                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9002            }
9003        } else {
9004            updateSettingsLI(newPackage,
9005                    installerPackageName,
9006                    null, null,
9007                    res);
9008            // delete the partially installed application. the data directory will have to be
9009            // restored if it was already existing
9010            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9011                // remove package from internal structures.  Note that we want deletePackageX to
9012                // delete the package data and cache directories that it created in
9013                // scanPackageLocked, unless those directories existed before we even tried to
9014                // install.
9015                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9016                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9017                                res.removedInfo, true);
9018            }
9019        }
9020    }
9021
9022    private void replacePackageLI(PackageParser.Package pkg,
9023            int parseFlags, int scanMode, UserHandle user,
9024            String installerPackageName, PackageInstalledInfo res) {
9025
9026        PackageParser.Package oldPackage;
9027        String pkgName = pkg.packageName;
9028        int[] allUsers;
9029        boolean[] perUserInstalled;
9030
9031        // First find the old package info and check signatures
9032        synchronized(mPackages) {
9033            oldPackage = mPackages.get(pkgName);
9034            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9035            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9036                    != PackageManager.SIGNATURE_MATCH) {
9037                Slog.w(TAG, "New package has a different signature: " + pkgName);
9038                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9039                return;
9040            }
9041
9042            // In case of rollback, remember per-user/profile install state
9043            PackageSetting ps = mSettings.mPackages.get(pkgName);
9044            allUsers = sUserManager.getUserIds();
9045            perUserInstalled = new boolean[allUsers.length];
9046            for (int i = 0; i < allUsers.length; i++) {
9047                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9048            }
9049        }
9050        boolean sysPkg = (isSystemApp(oldPackage));
9051        if (sysPkg) {
9052            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9053                    user, allUsers, perUserInstalled, installerPackageName, res);
9054        } else {
9055            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9056                    user, allUsers, perUserInstalled, installerPackageName, res);
9057        }
9058    }
9059
9060    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9061            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9062            int[] allUsers, boolean[] perUserInstalled,
9063            String installerPackageName, PackageInstalledInfo res) {
9064        PackageParser.Package newPackage = null;
9065        String pkgName = deletedPackage.packageName;
9066        boolean deletedPkg = true;
9067        boolean updatedSettings = false;
9068
9069        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9070                + deletedPackage);
9071        long origUpdateTime;
9072        if (pkg.mExtras != null) {
9073            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9074        } else {
9075            origUpdateTime = 0;
9076        }
9077
9078        // First delete the existing package while retaining the data directory
9079        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9080                res.removedInfo, true)) {
9081            // If the existing package wasn't successfully deleted
9082            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9083            deletedPkg = false;
9084        } else {
9085            // Successfully deleted the old package. Now proceed with re-installation
9086            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9087            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9088                    System.currentTimeMillis(), user);
9089            if (newPackage == null) {
9090                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9091                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9092                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9093                }
9094            } else {
9095                updateSettingsLI(newPackage,
9096                        installerPackageName,
9097                        allUsers, perUserInstalled,
9098                        res);
9099                updatedSettings = true;
9100            }
9101        }
9102
9103        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9104            // remove package from internal structures.  Note that we want deletePackageX to
9105            // delete the package data and cache directories that it created in
9106            // scanPackageLocked, unless those directories existed before we even tried to
9107            // install.
9108            if(updatedSettings) {
9109                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9110                deletePackageLI(
9111                        pkgName, null, true, allUsers, perUserInstalled,
9112                        PackageManager.DELETE_KEEP_DATA,
9113                                res.removedInfo, true);
9114            }
9115            // Since we failed to install the new package we need to restore the old
9116            // package that we deleted.
9117            if(deletedPkg) {
9118                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9119                File restoreFile = new File(deletedPackage.mPath);
9120                // Parse old package
9121                boolean oldOnSd = isExternal(deletedPackage);
9122                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9123                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9124                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9125                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9126                        | SCAN_UPDATE_TIME;
9127                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9128                        origUpdateTime, null) == null) {
9129                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9130                    return;
9131                }
9132                // Restore of old package succeeded. Update permissions.
9133                // writer
9134                synchronized (mPackages) {
9135                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9136                            UPDATE_PERMISSIONS_ALL);
9137                    // can downgrade to reader
9138                    mSettings.writeLPr();
9139                }
9140                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9141            }
9142        }
9143    }
9144
9145    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9146            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9147            int[] allUsers, boolean[] perUserInstalled,
9148            String installerPackageName, PackageInstalledInfo res) {
9149        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9150                + ", old=" + deletedPackage);
9151        PackageParser.Package newPackage = null;
9152        boolean updatedSettings = false;
9153        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9154                PackageParser.PARSE_IS_SYSTEM;
9155        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9156            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9157        }
9158        String packageName = deletedPackage.packageName;
9159        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9160        if (packageName == null) {
9161            Slog.w(TAG, "Attempt to delete null packageName.");
9162            return;
9163        }
9164        PackageParser.Package oldPkg;
9165        PackageSetting oldPkgSetting;
9166        // reader
9167        synchronized (mPackages) {
9168            oldPkg = mPackages.get(packageName);
9169            oldPkgSetting = mSettings.mPackages.get(packageName);
9170            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9171                    (oldPkgSetting == null)) {
9172                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9173                return;
9174            }
9175        }
9176
9177        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9178
9179        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9180        res.removedInfo.removedPackage = packageName;
9181        // Remove existing system package
9182        removePackageLI(oldPkgSetting, true);
9183        // writer
9184        synchronized (mPackages) {
9185            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9186                // We didn't need to disable the .apk as a current system package,
9187                // which means we are replacing another update that is already
9188                // installed.  We need to make sure to delete the older one's .apk.
9189                res.removedInfo.args = createInstallArgs(0,
9190                        deletedPackage.applicationInfo.sourceDir,
9191                        deletedPackage.applicationInfo.publicSourceDir,
9192                        deletedPackage.applicationInfo.nativeLibraryDir);
9193            } else {
9194                res.removedInfo.args = null;
9195            }
9196        }
9197
9198        // Successfully disabled the old package. Now proceed with re-installation
9199        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9200        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9201        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9202        if (newPackage == null) {
9203            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9204            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9205                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9206            }
9207        } else {
9208            if (newPackage.mExtras != null) {
9209                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9210                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9211                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9212            }
9213            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9214            updatedSettings = true;
9215        }
9216
9217        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9218            // Re installation failed. Restore old information
9219            // Remove new pkg information
9220            if (newPackage != null) {
9221                removeInstalledPackageLI(newPackage, true);
9222            }
9223            // Add back the old system package
9224            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9225            // Restore the old system information in Settings
9226            synchronized(mPackages) {
9227                if (updatedSettings) {
9228                    mSettings.enableSystemPackageLPw(packageName);
9229                    mSettings.setInstallerPackageName(packageName,
9230                            oldPkgSetting.installerPackageName);
9231                }
9232                mSettings.writeLPr();
9233            }
9234        }
9235    }
9236
9237    // Utility method used to move dex files during install.
9238    private int moveDexFilesLI(PackageParser.Package newPackage) {
9239        int retCode;
9240        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9241            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
9242            if (retCode != 0) {
9243                if (mNoDexOpt) {
9244                    /*
9245                     * If we're in an engineering build, programs are lazily run
9246                     * through dexopt. If the .dex file doesn't exist yet, it
9247                     * will be created when the program is run next.
9248                     */
9249                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9250                } else {
9251                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9252                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9253                }
9254            }
9255        }
9256        return PackageManager.INSTALL_SUCCEEDED;
9257    }
9258
9259    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9260            int[] allUsers, boolean[] perUserInstalled,
9261            PackageInstalledInfo res) {
9262        String pkgName = newPackage.packageName;
9263        synchronized (mPackages) {
9264            //write settings. the installStatus will be incomplete at this stage.
9265            //note that the new package setting would have already been
9266            //added to mPackages. It hasn't been persisted yet.
9267            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9268            mSettings.writeLPr();
9269        }
9270
9271        if ((res.returnCode = moveDexFilesLI(newPackage))
9272                != PackageManager.INSTALL_SUCCEEDED) {
9273            // Discontinue if moving dex files failed.
9274            return;
9275        }
9276
9277        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9278
9279        synchronized (mPackages) {
9280            updatePermissionsLPw(newPackage.packageName, newPackage,
9281                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9282                            ? UPDATE_PERMISSIONS_ALL : 0));
9283            // For system-bundled packages, we assume that installing an upgraded version
9284            // of the package implies that the user actually wants to run that new code,
9285            // so we enable the package.
9286            if (isSystemApp(newPackage)) {
9287                // NB: implicit assumption that system package upgrades apply to all users
9288                if (DEBUG_INSTALL) {
9289                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9290                }
9291                PackageSetting ps = mSettings.mPackages.get(pkgName);
9292                if (ps != null) {
9293                    if (res.origUsers != null) {
9294                        for (int userHandle : res.origUsers) {
9295                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9296                                    userHandle, installerPackageName);
9297                        }
9298                    }
9299                    // Also convey the prior install/uninstall state
9300                    if (allUsers != null && perUserInstalled != null) {
9301                        for (int i = 0; i < allUsers.length; i++) {
9302                            if (DEBUG_INSTALL) {
9303                                Slog.d(TAG, "    user " + allUsers[i]
9304                                        + " => " + perUserInstalled[i]);
9305                            }
9306                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9307                        }
9308                        // these install state changes will be persisted in the
9309                        // upcoming call to mSettings.writeLPr().
9310                    }
9311                }
9312            }
9313            res.name = pkgName;
9314            res.uid = newPackage.applicationInfo.uid;
9315            res.pkg = newPackage;
9316            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9317            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9318            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9319            //to update install status
9320            mSettings.writeLPr();
9321        }
9322    }
9323
9324    private void installPackageLI(InstallArgs args,
9325            boolean newInstall, PackageInstalledInfo res) {
9326        int pFlags = args.flags;
9327        String installerPackageName = args.installerPackageName;
9328        File tmpPackageFile = new File(args.getCodePath());
9329        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9330        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9331        boolean replace = false;
9332        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9333                | (newInstall ? SCAN_NEW_INSTALL : 0);
9334        // Result object to be returned
9335        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9336
9337        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9338        // Retrieve PackageSettings and parse package
9339        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9340                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9341                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9342        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9343        pp.setSeparateProcesses(mSeparateProcesses);
9344        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9345                null, mMetrics, parseFlags);
9346        if (pkg == null) {
9347            res.returnCode = pp.getParseError();
9348            return;
9349        }
9350        String pkgName = res.name = pkg.packageName;
9351        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9352            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9353                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9354                return;
9355            }
9356        }
9357        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9358            res.returnCode = pp.getParseError();
9359            return;
9360        }
9361
9362        /* If the installer passed in a manifest digest, compare it now. */
9363        if (args.manifestDigest != null) {
9364            if (DEBUG_INSTALL) {
9365                final String parsedManifest = pkg.manifestDigest == null ? "null"
9366                        : pkg.manifestDigest.toString();
9367                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9368                        + parsedManifest);
9369            }
9370
9371            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9372                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9373                return;
9374            }
9375        } else if (DEBUG_INSTALL) {
9376            final String parsedManifest = pkg.manifestDigest == null
9377                    ? "null" : pkg.manifestDigest.toString();
9378            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9379        }
9380
9381        // Get rid of all references to package scan path via parser.
9382        pp = null;
9383        String oldCodePath = null;
9384        boolean systemApp = false;
9385        synchronized (mPackages) {
9386            // Check whether the newly-scanned package wants to define an already-defined perm
9387            int N = pkg.permissions.size();
9388            for (int i = 0; i < N; i++) {
9389                PackageParser.Permission perm = pkg.permissions.get(i);
9390                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
9391                if (bp != null) {
9392                    Slog.w(TAG, "Package " + pkg.packageName
9393                            + " attempting to redeclare permission " + perm.info.name
9394                            + " already owned by " + bp.sourcePackage);
9395                    res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
9396                    res.origPermission = perm.info.name;
9397                    res.origPackage = bp.sourcePackage;
9398                    return;
9399                }
9400            }
9401
9402            // Check if installing already existing package
9403            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9404                String oldName = mSettings.mRenamedPackages.get(pkgName);
9405                if (pkg.mOriginalPackages != null
9406                        && pkg.mOriginalPackages.contains(oldName)
9407                        && mPackages.containsKey(oldName)) {
9408                    // This package is derived from an original package,
9409                    // and this device has been updating from that original
9410                    // name.  We must continue using the original name, so
9411                    // rename the new package here.
9412                    pkg.setPackageName(oldName);
9413                    pkgName = pkg.packageName;
9414                    replace = true;
9415                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9416                            + oldName + " pkgName=" + pkgName);
9417                } else if (mPackages.containsKey(pkgName)) {
9418                    // This package, under its official name, already exists
9419                    // on the device; we should replace it.
9420                    replace = true;
9421                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9422                }
9423            }
9424            PackageSetting ps = mSettings.mPackages.get(pkgName);
9425            if (ps != null) {
9426                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9427                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9428                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9429                    systemApp = (ps.pkg.applicationInfo.flags &
9430                            ApplicationInfo.FLAG_SYSTEM) != 0;
9431                }
9432                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9433            }
9434        }
9435
9436        if (systemApp && onSd) {
9437            // Disable updates to system apps on sdcard
9438            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9439            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9440            return;
9441        }
9442
9443        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9444            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9445            return;
9446        }
9447        // Set application objects path explicitly after the rename
9448        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9449        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9450        if (replace) {
9451            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9452                    installerPackageName, res);
9453        } else {
9454            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9455                    installerPackageName, res);
9456        }
9457        synchronized (mPackages) {
9458            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9459            if (ps != null) {
9460                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9461            }
9462        }
9463    }
9464
9465    private static boolean isForwardLocked(PackageParser.Package pkg) {
9466        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9467    }
9468
9469
9470    private boolean isForwardLocked(PackageSetting ps) {
9471        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9472    }
9473
9474    private static boolean isExternal(PackageParser.Package pkg) {
9475        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9476    }
9477
9478    private static boolean isExternal(PackageSetting ps) {
9479        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9480    }
9481
9482    private static boolean isSystemApp(PackageParser.Package pkg) {
9483        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9484    }
9485
9486    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9487        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9488    }
9489
9490    private static boolean isSystemApp(ApplicationInfo info) {
9491        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9492    }
9493
9494    private static boolean isSystemApp(PackageSetting ps) {
9495        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9496    }
9497
9498    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9499        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9500    }
9501
9502    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9503        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9504    }
9505
9506    private int packageFlagsToInstallFlags(PackageSetting ps) {
9507        int installFlags = 0;
9508        if (isExternal(ps)) {
9509            installFlags |= PackageManager.INSTALL_EXTERNAL;
9510        }
9511        if (isForwardLocked(ps)) {
9512            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9513        }
9514        return installFlags;
9515    }
9516
9517    private void deleteTempPackageFiles() {
9518        final FilenameFilter filter = new FilenameFilter() {
9519            public boolean accept(File dir, String name) {
9520                return name.startsWith("vmdl") && name.endsWith(".tmp");
9521            }
9522        };
9523        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9524        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9525    }
9526
9527    private static final void deleteTempPackageFilesInDirectory(File directory,
9528            FilenameFilter filter) {
9529        final String[] tmpFilesList = directory.list(filter);
9530        if (tmpFilesList == null) {
9531            return;
9532        }
9533        for (int i = 0; i < tmpFilesList.length; i++) {
9534            final File tmpFile = new File(directory, tmpFilesList[i]);
9535            tmpFile.delete();
9536        }
9537    }
9538
9539    private File createTempPackageFile(File installDir) {
9540        File tmpPackageFile;
9541        try {
9542            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9543        } catch (IOException e) {
9544            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9545            return null;
9546        }
9547        try {
9548            FileUtils.setPermissions(
9549                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9550                    -1, -1);
9551            if (!SELinux.restorecon(tmpPackageFile)) {
9552                return null;
9553            }
9554        } catch (IOException e) {
9555            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9556            return null;
9557        }
9558        return tmpPackageFile;
9559    }
9560
9561    @Override
9562    public void deletePackageAsUser(final String packageName,
9563                                    final IPackageDeleteObserver observer,
9564                                    final int userId, final int flags) {
9565        mContext.enforceCallingOrSelfPermission(
9566                android.Manifest.permission.DELETE_PACKAGES, null);
9567        final int uid = Binder.getCallingUid();
9568        if (UserHandle.getUserId(uid) != userId) {
9569            mContext.enforceCallingPermission(
9570                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9571                    "deletePackage for user " + userId);
9572        }
9573        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9574            try {
9575                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9576            } catch (RemoteException re) {
9577            }
9578            return;
9579        }
9580
9581        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9582        // Queue up an async operation since the package deletion may take a little while.
9583        mHandler.post(new Runnable() {
9584            public void run() {
9585                mHandler.removeCallbacks(this);
9586                final int returnCode = deletePackageX(packageName, userId, flags);
9587                if (observer != null) {
9588                    try {
9589                        observer.packageDeleted(packageName, returnCode);
9590                    } catch (RemoteException e) {
9591                        Log.i(TAG, "Observer no longer exists.");
9592                    } //end catch
9593                } //end if
9594            } //end run
9595        });
9596    }
9597
9598    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9599        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9600                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9601        try {
9602            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9603                    || dpm.isDeviceOwner(packageName))) {
9604                return true;
9605            }
9606        } catch (RemoteException e) {
9607        }
9608        return false;
9609    }
9610
9611    /**
9612     *  This method is an internal method that could be get invoked either
9613     *  to delete an installed package or to clean up a failed installation.
9614     *  After deleting an installed package, a broadcast is sent to notify any
9615     *  listeners that the package has been installed. For cleaning up a failed
9616     *  installation, the broadcast is not necessary since the package's
9617     *  installation wouldn't have sent the initial broadcast either
9618     *  The key steps in deleting a package are
9619     *  deleting the package information in internal structures like mPackages,
9620     *  deleting the packages base directories through installd
9621     *  updating mSettings to reflect current status
9622     *  persisting settings for later use
9623     *  sending a broadcast if necessary
9624     */
9625    private int deletePackageX(String packageName, int userId, int flags) {
9626        final PackageRemovedInfo info = new PackageRemovedInfo();
9627        final boolean res;
9628
9629        if (isPackageDeviceAdmin(packageName, userId)) {
9630            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9631            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9632        }
9633
9634        boolean removedForAllUsers = false;
9635        boolean systemUpdate = false;
9636
9637        // for the uninstall-updates case and restricted profiles, remember the per-
9638        // userhandle installed state
9639        int[] allUsers;
9640        boolean[] perUserInstalled;
9641        synchronized (mPackages) {
9642            PackageSetting ps = mSettings.mPackages.get(packageName);
9643            allUsers = sUserManager.getUserIds();
9644            perUserInstalled = new boolean[allUsers.length];
9645            for (int i = 0; i < allUsers.length; i++) {
9646                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9647            }
9648        }
9649
9650        synchronized (mInstallLock) {
9651            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9652            res = deletePackageLI(packageName,
9653                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9654                            ? UserHandle.ALL : new UserHandle(userId),
9655                    true, allUsers, perUserInstalled,
9656                    flags | REMOVE_CHATTY, info, true);
9657            systemUpdate = info.isRemovedPackageSystemUpdate;
9658            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9659                removedForAllUsers = true;
9660            }
9661            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9662                    + " removedForAllUsers=" + removedForAllUsers);
9663        }
9664
9665        if (res) {
9666            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9667
9668            // If the removed package was a system update, the old system package
9669            // was re-enabled; we need to broadcast this information
9670            if (systemUpdate) {
9671                Bundle extras = new Bundle(1);
9672                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9673                        ? info.removedAppId : info.uid);
9674                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9675
9676                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9677                        extras, null, null, null);
9678                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9679                        extras, null, null, null);
9680                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9681                        null, packageName, null, null);
9682            }
9683        }
9684        // Force a gc here.
9685        Runtime.getRuntime().gc();
9686        // Delete the resources here after sending the broadcast to let
9687        // other processes clean up before deleting resources.
9688        if (info.args != null) {
9689            synchronized (mInstallLock) {
9690                info.args.doPostDeleteLI(true);
9691            }
9692        }
9693
9694        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9695    }
9696
9697    static class PackageRemovedInfo {
9698        String removedPackage;
9699        int uid = -1;
9700        int removedAppId = -1;
9701        int[] removedUsers = null;
9702        boolean isRemovedPackageSystemUpdate = false;
9703        // Clean up resources deleted packages.
9704        InstallArgs args = null;
9705
9706        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9707            Bundle extras = new Bundle(1);
9708            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9709            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9710            if (replacing) {
9711                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9712            }
9713            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9714            if (removedPackage != null) {
9715                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9716                        extras, null, null, removedUsers);
9717                if (fullRemove && !replacing) {
9718                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9719                            extras, null, null, removedUsers);
9720                }
9721            }
9722            if (removedAppId >= 0) {
9723                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9724                        removedUsers);
9725            }
9726        }
9727    }
9728
9729    /*
9730     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9731     * flag is not set, the data directory is removed as well.
9732     * make sure this flag is set for partially installed apps. If not its meaningless to
9733     * delete a partially installed application.
9734     */
9735    private void removePackageDataLI(PackageSetting ps,
9736            int[] allUserHandles, boolean[] perUserInstalled,
9737            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9738        String packageName = ps.name;
9739        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9740        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9741        // Retrieve object to delete permissions for shared user later on
9742        final PackageSetting deletedPs;
9743        // reader
9744        synchronized (mPackages) {
9745            deletedPs = mSettings.mPackages.get(packageName);
9746            if (outInfo != null) {
9747                outInfo.removedPackage = packageName;
9748                outInfo.removedUsers = deletedPs != null
9749                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9750                        : null;
9751            }
9752        }
9753        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9754            removeDataDirsLI(packageName);
9755            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9756        }
9757        // writer
9758        synchronized (mPackages) {
9759            if (deletedPs != null) {
9760                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9761                    if (outInfo != null) {
9762                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9763                    }
9764                    if (deletedPs != null) {
9765                        updatePermissionsLPw(deletedPs.name, null, 0);
9766                        if (deletedPs.sharedUser != null) {
9767                            // remove permissions associated with package
9768                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9769                        }
9770                    }
9771                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9772                }
9773                // make sure to preserve per-user disabled state if this removal was just
9774                // a downgrade of a system app to the factory package
9775                if (allUserHandles != null && perUserInstalled != null) {
9776                    if (DEBUG_REMOVE) {
9777                        Slog.d(TAG, "Propagating install state across downgrade");
9778                    }
9779                    for (int i = 0; i < allUserHandles.length; i++) {
9780                        if (DEBUG_REMOVE) {
9781                            Slog.d(TAG, "    user " + allUserHandles[i]
9782                                    + " => " + perUserInstalled[i]);
9783                        }
9784                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9785                    }
9786                }
9787            }
9788            // can downgrade to reader
9789            if (writeSettings) {
9790                // Save settings now
9791                mSettings.writeLPr();
9792            }
9793        }
9794        if (outInfo != null) {
9795            // A user ID was deleted here. Go through all users and remove it
9796            // from KeyStore.
9797            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9798        }
9799    }
9800
9801    static boolean locationIsPrivileged(File path) {
9802        try {
9803            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9804                    .getCanonicalPath();
9805            return path.getCanonicalPath().startsWith(privilegedAppDir);
9806        } catch (IOException e) {
9807            Slog.e(TAG, "Unable to access code path " + path);
9808        }
9809        return false;
9810    }
9811
9812    /*
9813     * Tries to delete system package.
9814     */
9815    private boolean deleteSystemPackageLI(PackageSetting newPs,
9816            int[] allUserHandles, boolean[] perUserInstalled,
9817            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
9818        final boolean applyUserRestrictions
9819                = (allUserHandles != null) && (perUserInstalled != null);
9820        PackageSetting disabledPs = null;
9821        // Confirm if the system package has been updated
9822        // An updated system app can be deleted. This will also have to restore
9823        // the system pkg from system partition
9824        // reader
9825        synchronized (mPackages) {
9826            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
9827        }
9828        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
9829                + " disabledPs=" + disabledPs);
9830        if (disabledPs == null) {
9831            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
9832            return false;
9833        } else if (DEBUG_REMOVE) {
9834            Slog.d(TAG, "Deleting system pkg from data partition");
9835        }
9836        if (DEBUG_REMOVE) {
9837            if (applyUserRestrictions) {
9838                Slog.d(TAG, "Remembering install states:");
9839                for (int i = 0; i < allUserHandles.length; i++) {
9840                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
9841                }
9842            }
9843        }
9844        // Delete the updated package
9845        outInfo.isRemovedPackageSystemUpdate = true;
9846        if (disabledPs.versionCode < newPs.versionCode) {
9847            // Delete data for downgrades
9848            flags &= ~PackageManager.DELETE_KEEP_DATA;
9849        } else {
9850            // Preserve data by setting flag
9851            flags |= PackageManager.DELETE_KEEP_DATA;
9852        }
9853        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
9854                allUserHandles, perUserInstalled, outInfo, writeSettings);
9855        if (!ret) {
9856            return false;
9857        }
9858        // writer
9859        synchronized (mPackages) {
9860            // Reinstate the old system package
9861            mSettings.enableSystemPackageLPw(newPs.name);
9862            // Remove any native libraries from the upgraded package.
9863            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
9864        }
9865        // Install the system package
9866        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
9867        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
9868        if (locationIsPrivileged(disabledPs.codePath)) {
9869            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9870        }
9871        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
9872                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
9873
9874        if (newPkg == null) {
9875            Slog.w(TAG, "Failed to restore system package:" + newPs.name
9876                    + " with error:" + mLastScanError);
9877            return false;
9878        }
9879        // writer
9880        synchronized (mPackages) {
9881            updatePermissionsLPw(newPkg.packageName, newPkg,
9882                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
9883            if (applyUserRestrictions) {
9884                if (DEBUG_REMOVE) {
9885                    Slog.d(TAG, "Propagating install state across reinstall");
9886                }
9887                PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
9888                for (int i = 0; i < allUserHandles.length; i++) {
9889                    if (DEBUG_REMOVE) {
9890                        Slog.d(TAG, "    user " + allUserHandles[i]
9891                                + " => " + perUserInstalled[i]);
9892                    }
9893                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9894                }
9895                // Regardless of writeSettings we need to ensure that this restriction
9896                // state propagation is persisted
9897                mSettings.writeAllUsersPackageRestrictionsLPr();
9898            }
9899            // can downgrade to reader here
9900            if (writeSettings) {
9901                mSettings.writeLPr();
9902            }
9903        }
9904        return true;
9905    }
9906
9907    private boolean deleteInstalledPackageLI(PackageSetting ps,
9908            boolean deleteCodeAndResources, int flags,
9909            int[] allUserHandles, boolean[] perUserInstalled,
9910            PackageRemovedInfo outInfo, boolean writeSettings) {
9911        if (outInfo != null) {
9912            outInfo.uid = ps.appId;
9913        }
9914
9915        // Delete package data from internal structures and also remove data if flag is set
9916        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
9917
9918        // Delete application code and resources
9919        if (deleteCodeAndResources && (outInfo != null)) {
9920            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
9921                    ps.resourcePathString, ps.nativeLibraryPathString);
9922        }
9923        return true;
9924    }
9925
9926    /*
9927     * This method handles package deletion in general
9928     */
9929    private boolean deletePackageLI(String packageName, UserHandle user,
9930            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
9931            int flags, PackageRemovedInfo outInfo,
9932            boolean writeSettings) {
9933        if (packageName == null) {
9934            Slog.w(TAG, "Attempt to delete null packageName.");
9935            return false;
9936        }
9937        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
9938        PackageSetting ps;
9939        boolean dataOnly = false;
9940        int removeUser = -1;
9941        int appId = -1;
9942        synchronized (mPackages) {
9943            ps = mSettings.mPackages.get(packageName);
9944            if (ps == null) {
9945                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9946                return false;
9947            }
9948            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
9949                    && user.getIdentifier() != UserHandle.USER_ALL) {
9950                // The caller is asking that the package only be deleted for a single
9951                // user.  To do this, we just mark its uninstalled state and delete
9952                // its data.  If this is a system app, we only allow this to happen if
9953                // they have set the special DELETE_SYSTEM_APP which requests different
9954                // semantics than normal for uninstalling system apps.
9955                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
9956                ps.setUserState(user.getIdentifier(),
9957                        COMPONENT_ENABLED_STATE_DEFAULT,
9958                        false, //installed
9959                        true,  //stopped
9960                        true,  //notLaunched
9961                        false, //blocked
9962                        null, null, null);
9963                if (!isSystemApp(ps)) {
9964                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
9965                        // Other user still have this package installed, so all
9966                        // we need to do is clear this user's data and save that
9967                        // it is uninstalled.
9968                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
9969                        removeUser = user.getIdentifier();
9970                        appId = ps.appId;
9971                        mSettings.writePackageRestrictionsLPr(removeUser);
9972                    } else {
9973                        // We need to set it back to 'installed' so the uninstall
9974                        // broadcasts will be sent correctly.
9975                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
9976                        ps.setInstalled(true, user.getIdentifier());
9977                    }
9978                } else {
9979                    // This is a system app, so we assume that the
9980                    // other users still have this package installed, so all
9981                    // we need to do is clear this user's data and save that
9982                    // it is uninstalled.
9983                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
9984                    removeUser = user.getIdentifier();
9985                    appId = ps.appId;
9986                    mSettings.writePackageRestrictionsLPr(removeUser);
9987                }
9988            }
9989        }
9990
9991        if (removeUser >= 0) {
9992            // From above, we determined that we are deleting this only
9993            // for a single user.  Continue the work here.
9994            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
9995            if (outInfo != null) {
9996                outInfo.removedPackage = packageName;
9997                outInfo.removedAppId = appId;
9998                outInfo.removedUsers = new int[] {removeUser};
9999            }
10000            mInstaller.clearUserData(packageName, removeUser);
10001            removeKeystoreDataIfNeeded(removeUser, appId);
10002            schedulePackageCleaning(packageName, removeUser, false);
10003            return true;
10004        }
10005
10006        if (dataOnly) {
10007            // Delete application data first
10008            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10009            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10010            return true;
10011        }
10012
10013        boolean ret = false;
10014        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10015        if (isSystemApp(ps)) {
10016            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10017            // When an updated system application is deleted we delete the existing resources as well and
10018            // fall back to existing code in system partition
10019            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10020                    flags, outInfo, writeSettings);
10021        } else {
10022            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10023            // Kill application pre-emptively especially for apps on sd.
10024            killApplication(packageName, ps.appId, "uninstall pkg");
10025            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10026                    allUserHandles, perUserInstalled,
10027                    outInfo, writeSettings);
10028        }
10029
10030        return ret;
10031    }
10032
10033    private final class ClearStorageConnection implements ServiceConnection {
10034        IMediaContainerService mContainerService;
10035
10036        @Override
10037        public void onServiceConnected(ComponentName name, IBinder service) {
10038            synchronized (this) {
10039                mContainerService = IMediaContainerService.Stub.asInterface(service);
10040                notifyAll();
10041            }
10042        }
10043
10044        @Override
10045        public void onServiceDisconnected(ComponentName name) {
10046        }
10047    }
10048
10049    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10050        final boolean mounted;
10051        if (Environment.isExternalStorageEmulated()) {
10052            mounted = true;
10053        } else {
10054            final String status = Environment.getExternalStorageState();
10055
10056            mounted = status.equals(Environment.MEDIA_MOUNTED)
10057                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10058        }
10059
10060        if (!mounted) {
10061            return;
10062        }
10063
10064        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10065        int[] users;
10066        if (userId == UserHandle.USER_ALL) {
10067            users = sUserManager.getUserIds();
10068        } else {
10069            users = new int[] { userId };
10070        }
10071        final ClearStorageConnection conn = new ClearStorageConnection();
10072        if (mContext.bindServiceAsUser(
10073                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10074            try {
10075                for (int curUser : users) {
10076                    long timeout = SystemClock.uptimeMillis() + 5000;
10077                    synchronized (conn) {
10078                        long now = SystemClock.uptimeMillis();
10079                        while (conn.mContainerService == null && now < timeout) {
10080                            try {
10081                                conn.wait(timeout - now);
10082                            } catch (InterruptedException e) {
10083                            }
10084                        }
10085                    }
10086                    if (conn.mContainerService == null) {
10087                        return;
10088                    }
10089
10090                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10091                    clearDirectory(conn.mContainerService,
10092                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10093                    if (allData) {
10094                        clearDirectory(conn.mContainerService,
10095                                userEnv.buildExternalStorageAppDataDirs(packageName));
10096                        clearDirectory(conn.mContainerService,
10097                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10098                    }
10099                }
10100            } finally {
10101                mContext.unbindService(conn);
10102            }
10103        }
10104    }
10105
10106    @Override
10107    public void clearApplicationUserData(final String packageName,
10108            final IPackageDataObserver observer, final int userId) {
10109        mContext.enforceCallingOrSelfPermission(
10110                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10111        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10112        // Queue up an async operation since the package deletion may take a little while.
10113        mHandler.post(new Runnable() {
10114            public void run() {
10115                mHandler.removeCallbacks(this);
10116                final boolean succeeded;
10117                synchronized (mInstallLock) {
10118                    succeeded = clearApplicationUserDataLI(packageName, userId);
10119                }
10120                clearExternalStorageDataSync(packageName, userId, true);
10121                if (succeeded) {
10122                    // invoke DeviceStorageMonitor's update method to clear any notifications
10123                    DeviceStorageMonitorInternal
10124                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10125                    if (dsm != null) {
10126                        dsm.checkMemory();
10127                    }
10128                }
10129                if(observer != null) {
10130                    try {
10131                        observer.onRemoveCompleted(packageName, succeeded);
10132                    } catch (RemoteException e) {
10133                        Log.i(TAG, "Observer no longer exists.");
10134                    }
10135                } //end if observer
10136            } //end run
10137        });
10138    }
10139
10140    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10141        if (packageName == null) {
10142            Slog.w(TAG, "Attempt to delete null packageName.");
10143            return false;
10144        }
10145        PackageParser.Package p;
10146        boolean dataOnly = false;
10147        final int appId;
10148        synchronized (mPackages) {
10149            p = mPackages.get(packageName);
10150            if (p == null) {
10151                dataOnly = true;
10152                PackageSetting ps = mSettings.mPackages.get(packageName);
10153                if ((ps == null) || (ps.pkg == null)) {
10154                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10155                    return false;
10156                }
10157                p = ps.pkg;
10158            }
10159            if (!dataOnly) {
10160                // need to check this only for fully installed applications
10161                if (p == null) {
10162                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10163                    return false;
10164                }
10165                final ApplicationInfo applicationInfo = p.applicationInfo;
10166                if (applicationInfo == null) {
10167                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10168                    return false;
10169                }
10170            }
10171            if (p != null && p.applicationInfo != null) {
10172                appId = p.applicationInfo.uid;
10173            } else {
10174                appId = -1;
10175            }
10176        }
10177        int retCode = mInstaller.clearUserData(packageName, userId);
10178        if (retCode < 0) {
10179            Slog.w(TAG, "Couldn't remove cache files for package: "
10180                    + packageName);
10181            return false;
10182        }
10183        removeKeystoreDataIfNeeded(userId, appId);
10184        return true;
10185    }
10186
10187    /**
10188     * Remove entries from the keystore daemon. Will only remove it if the
10189     * {@code appId} is valid.
10190     */
10191    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10192        if (appId < 0) {
10193            return;
10194        }
10195
10196        final KeyStore keyStore = KeyStore.getInstance();
10197        if (keyStore != null) {
10198            if (userId == UserHandle.USER_ALL) {
10199                for (final int individual : sUserManager.getUserIds()) {
10200                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10201                }
10202            } else {
10203                keyStore.clearUid(UserHandle.getUid(userId, appId));
10204            }
10205        } else {
10206            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10207        }
10208    }
10209
10210    public void deleteApplicationCacheFiles(final String packageName,
10211            final IPackageDataObserver observer) {
10212        mContext.enforceCallingOrSelfPermission(
10213                android.Manifest.permission.DELETE_CACHE_FILES, null);
10214        // Queue up an async operation since the package deletion may take a little while.
10215        final int userId = UserHandle.getCallingUserId();
10216        mHandler.post(new Runnable() {
10217            public void run() {
10218                mHandler.removeCallbacks(this);
10219                final boolean succeded;
10220                synchronized (mInstallLock) {
10221                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10222                }
10223                clearExternalStorageDataSync(packageName, userId, false);
10224                if(observer != null) {
10225                    try {
10226                        observer.onRemoveCompleted(packageName, succeded);
10227                    } catch (RemoteException e) {
10228                        Log.i(TAG, "Observer no longer exists.");
10229                    }
10230                } //end if observer
10231            } //end run
10232        });
10233    }
10234
10235    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10236        if (packageName == null) {
10237            Slog.w(TAG, "Attempt to delete null packageName.");
10238            return false;
10239        }
10240        PackageParser.Package p;
10241        synchronized (mPackages) {
10242            p = mPackages.get(packageName);
10243        }
10244        if (p == null) {
10245            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10246            return false;
10247        }
10248        final ApplicationInfo applicationInfo = p.applicationInfo;
10249        if (applicationInfo == null) {
10250            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10251            return false;
10252        }
10253        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10254        if (retCode < 0) {
10255            Slog.w(TAG, "Couldn't remove cache files for package: "
10256                       + packageName + " u" + userId);
10257            return false;
10258        }
10259        return true;
10260    }
10261
10262    public void getPackageSizeInfo(final String packageName, int userHandle,
10263            final IPackageStatsObserver observer) {
10264        mContext.enforceCallingOrSelfPermission(
10265                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10266
10267        PackageStats stats = new PackageStats(packageName, userHandle);
10268
10269        /*
10270         * Queue up an async operation since the package measurement may take a
10271         * little while.
10272         */
10273        Message msg = mHandler.obtainMessage(INIT_COPY);
10274        msg.obj = new MeasureParams(stats, observer);
10275        mHandler.sendMessage(msg);
10276    }
10277
10278    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10279            PackageStats pStats) {
10280        if (packageName == null) {
10281            Slog.w(TAG, "Attempt to get size of null packageName.");
10282            return false;
10283        }
10284        PackageParser.Package p;
10285        boolean dataOnly = false;
10286        String libDirPath = null;
10287        String asecPath = null;
10288        synchronized (mPackages) {
10289            p = mPackages.get(packageName);
10290            PackageSetting ps = mSettings.mPackages.get(packageName);
10291            if(p == null) {
10292                dataOnly = true;
10293                if((ps == null) || (ps.pkg == null)) {
10294                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10295                    return false;
10296                }
10297                p = ps.pkg;
10298            }
10299            if (ps != null) {
10300                libDirPath = ps.nativeLibraryPathString;
10301            }
10302            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10303                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10304                if (secureContainerId != null) {
10305                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10306                }
10307            }
10308        }
10309        String publicSrcDir = null;
10310        if(!dataOnly) {
10311            final ApplicationInfo applicationInfo = p.applicationInfo;
10312            if (applicationInfo == null) {
10313                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10314                return false;
10315            }
10316            if (isForwardLocked(p)) {
10317                publicSrcDir = applicationInfo.publicSourceDir;
10318            }
10319        }
10320        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10321                publicSrcDir, asecPath, pStats);
10322        if (res < 0) {
10323            return false;
10324        }
10325
10326        // Fix-up for forward-locked applications in ASEC containers.
10327        if (!isExternal(p)) {
10328            pStats.codeSize += pStats.externalCodeSize;
10329            pStats.externalCodeSize = 0L;
10330        }
10331
10332        return true;
10333    }
10334
10335
10336    public void addPackageToPreferred(String packageName) {
10337        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10338    }
10339
10340    public void removePackageFromPreferred(String packageName) {
10341        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10342    }
10343
10344    public List<PackageInfo> getPreferredPackages(int flags) {
10345        return new ArrayList<PackageInfo>();
10346    }
10347
10348    private int getUidTargetSdkVersionLockedLPr(int uid) {
10349        Object obj = mSettings.getUserIdLPr(uid);
10350        if (obj instanceof SharedUserSetting) {
10351            final SharedUserSetting sus = (SharedUserSetting) obj;
10352            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10353            final Iterator<PackageSetting> it = sus.packages.iterator();
10354            while (it.hasNext()) {
10355                final PackageSetting ps = it.next();
10356                if (ps.pkg != null) {
10357                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10358                    if (v < vers) vers = v;
10359                }
10360            }
10361            return vers;
10362        } else if (obj instanceof PackageSetting) {
10363            final PackageSetting ps = (PackageSetting) obj;
10364            if (ps.pkg != null) {
10365                return ps.pkg.applicationInfo.targetSdkVersion;
10366            }
10367        }
10368        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10369    }
10370
10371    public void addPreferredActivity(IntentFilter filter, int match,
10372            ComponentName[] set, ComponentName activity, int userId) {
10373        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10374    }
10375
10376    private void addPreferredActivityInternal(IntentFilter filter, int match,
10377            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10378        // writer
10379        int callingUid = Binder.getCallingUid();
10380        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10381        if (filter.countActions() == 0) {
10382            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10383            return;
10384        }
10385        synchronized (mPackages) {
10386            if (mContext.checkCallingOrSelfPermission(
10387                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10388                    != PackageManager.PERMISSION_GRANTED) {
10389                if (getUidTargetSdkVersionLockedLPr(callingUid)
10390                        < Build.VERSION_CODES.FROYO) {
10391                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10392                            + callingUid);
10393                    return;
10394                }
10395                mContext.enforceCallingOrSelfPermission(
10396                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10397            }
10398
10399            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10400            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10401            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10402                    new PreferredActivity(filter, match, set, activity, always));
10403            mSettings.writePackageRestrictionsLPr(userId);
10404        }
10405    }
10406
10407    public void replacePreferredActivity(IntentFilter filter, int match,
10408            ComponentName[] set, ComponentName activity) {
10409        if (filter.countActions() != 1) {
10410            throw new IllegalArgumentException(
10411                    "replacePreferredActivity expects filter to have only 1 action.");
10412        }
10413        if (filter.countDataAuthorities() != 0
10414                || filter.countDataPaths() != 0
10415                || filter.countDataSchemes() > 1
10416                || filter.countDataTypes() != 0) {
10417            throw new IllegalArgumentException(
10418                    "replacePreferredActivity expects filter to have no data authorities, " +
10419                    "paths, or types; and at most one scheme.");
10420        }
10421        synchronized (mPackages) {
10422            if (mContext.checkCallingOrSelfPermission(
10423                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10424                    != PackageManager.PERMISSION_GRANTED) {
10425                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10426                        < Build.VERSION_CODES.FROYO) {
10427                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10428                            + Binder.getCallingUid());
10429                    return;
10430                }
10431                mContext.enforceCallingOrSelfPermission(
10432                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10433            }
10434
10435            final int callingUserId = UserHandle.getCallingUserId();
10436            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10437            if (pir != null) {
10438                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10439                if (filter.countDataSchemes() == 1) {
10440                    Uri.Builder builder = new Uri.Builder();
10441                    builder.scheme(filter.getDataScheme(0));
10442                    intent.setData(builder.build());
10443                }
10444                List<PreferredActivity> matches = pir.queryIntent(
10445                        intent, null, true, callingUserId);
10446                if (DEBUG_PREFERRED) {
10447                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10448                }
10449                for (int i = 0; i < matches.size(); i++) {
10450                    PreferredActivity pa = matches.get(i);
10451                    if (DEBUG_PREFERRED) {
10452                        Slog.i(TAG, "Removing preferred activity "
10453                                + pa.mPref.mComponent + ":");
10454                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10455                    }
10456                    pir.removeFilter(pa);
10457                }
10458            }
10459            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10460        }
10461    }
10462
10463    public void clearPackagePreferredActivities(String packageName) {
10464        final int uid = Binder.getCallingUid();
10465        // writer
10466        synchronized (mPackages) {
10467            PackageParser.Package pkg = mPackages.get(packageName);
10468            if (pkg == null || pkg.applicationInfo.uid != uid) {
10469                if (mContext.checkCallingOrSelfPermission(
10470                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10471                        != PackageManager.PERMISSION_GRANTED) {
10472                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10473                            < Build.VERSION_CODES.FROYO) {
10474                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10475                                + Binder.getCallingUid());
10476                        return;
10477                    }
10478                    mContext.enforceCallingOrSelfPermission(
10479                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10480                }
10481            }
10482
10483            int user = UserHandle.getCallingUserId();
10484            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10485                mSettings.writePackageRestrictionsLPr(user);
10486                scheduleWriteSettingsLocked();
10487            }
10488        }
10489    }
10490
10491    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10492    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10493        ArrayList<PreferredActivity> removed = null;
10494        boolean changed = false;
10495        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10496            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10497            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10498            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10499                continue;
10500            }
10501            Iterator<PreferredActivity> it = pir.filterIterator();
10502            while (it.hasNext()) {
10503                PreferredActivity pa = it.next();
10504                // Mark entry for removal only if it matches the package name
10505                // and the entry is of type "always".
10506                if (packageName == null ||
10507                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10508                                && pa.mPref.mAlways)) {
10509                    if (removed == null) {
10510                        removed = new ArrayList<PreferredActivity>();
10511                    }
10512                    removed.add(pa);
10513                }
10514            }
10515            if (removed != null) {
10516                for (int j=0; j<removed.size(); j++) {
10517                    PreferredActivity pa = removed.get(j);
10518                    pir.removeFilter(pa);
10519                }
10520                changed = true;
10521            }
10522        }
10523        return changed;
10524    }
10525
10526    public void resetPreferredActivities(int userId) {
10527        mContext.enforceCallingOrSelfPermission(
10528                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10529        // writer
10530        synchronized (mPackages) {
10531            int user = UserHandle.getCallingUserId();
10532            clearPackagePreferredActivitiesLPw(null, user);
10533            mSettings.readDefaultPreferredAppsLPw(this, user);
10534            mSettings.writePackageRestrictionsLPr(user);
10535            scheduleWriteSettingsLocked();
10536        }
10537    }
10538
10539    public int getPreferredActivities(List<IntentFilter> outFilters,
10540            List<ComponentName> outActivities, String packageName) {
10541
10542        int num = 0;
10543        final int userId = UserHandle.getCallingUserId();
10544        // reader
10545        synchronized (mPackages) {
10546            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10547            if (pir != null) {
10548                final Iterator<PreferredActivity> it = pir.filterIterator();
10549                while (it.hasNext()) {
10550                    final PreferredActivity pa = it.next();
10551                    if (packageName == null
10552                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10553                                    && pa.mPref.mAlways)) {
10554                        if (outFilters != null) {
10555                            outFilters.add(new IntentFilter(pa));
10556                        }
10557                        if (outActivities != null) {
10558                            outActivities.add(pa.mPref.mComponent);
10559                        }
10560                    }
10561                }
10562            }
10563        }
10564
10565        return num;
10566    }
10567
10568    @Override
10569    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
10570            int userId) {
10571        int callingUid = Binder.getCallingUid();
10572        if (callingUid != Process.SYSTEM_UID) {
10573            throw new SecurityException(
10574                    "addPersistentPreferredActivity can only be run by the system");
10575        }
10576        if (filter.countActions() == 0) {
10577            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10578            return;
10579        }
10580        synchronized (mPackages) {
10581            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
10582                    " :");
10583            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10584            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
10585                    new PersistentPreferredActivity(filter, activity));
10586            mSettings.writePackageRestrictionsLPr(userId);
10587        }
10588    }
10589
10590    @Override
10591    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
10592        int callingUid = Binder.getCallingUid();
10593        if (callingUid != Process.SYSTEM_UID) {
10594            throw new SecurityException(
10595                    "clearPackagePersistentPreferredActivities can only be run by the system");
10596        }
10597        ArrayList<PersistentPreferredActivity> removed = null;
10598        boolean changed = false;
10599        synchronized (mPackages) {
10600            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
10601                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
10602                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
10603                        .valueAt(i);
10604                if (userId != thisUserId) {
10605                    continue;
10606                }
10607                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
10608                while (it.hasNext()) {
10609                    PersistentPreferredActivity ppa = it.next();
10610                    // Mark entry for removal only if it matches the package name.
10611                    if (ppa.mComponent.getPackageName().equals(packageName)) {
10612                        if (removed == null) {
10613                            removed = new ArrayList<PersistentPreferredActivity>();
10614                        }
10615                        removed.add(ppa);
10616                    }
10617                }
10618                if (removed != null) {
10619                    for (int j=0; j<removed.size(); j++) {
10620                        PersistentPreferredActivity ppa = removed.get(j);
10621                        ppir.removeFilter(ppa);
10622                    }
10623                    changed = true;
10624                }
10625            }
10626
10627            if (changed) {
10628                mSettings.writePackageRestrictionsLPr(userId);
10629            }
10630        }
10631    }
10632
10633    @Override
10634    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10635        Intent intent = new Intent(Intent.ACTION_MAIN);
10636        intent.addCategory(Intent.CATEGORY_HOME);
10637
10638        final int callingUserId = UserHandle.getCallingUserId();
10639        List<ResolveInfo> list = queryIntentActivities(intent, null,
10640                PackageManager.GET_META_DATA, callingUserId);
10641        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10642                true, false, false, callingUserId);
10643
10644        allHomeCandidates.clear();
10645        if (list != null) {
10646            for (ResolveInfo ri : list) {
10647                allHomeCandidates.add(ri);
10648            }
10649        }
10650        return (preferred == null || preferred.activityInfo == null)
10651                ? null
10652                : new ComponentName(preferred.activityInfo.packageName,
10653                        preferred.activityInfo.name);
10654    }
10655
10656    @Override
10657    public void setApplicationEnabledSetting(String appPackageName,
10658            int newState, int flags, int userId, String callingPackage) {
10659        if (!sUserManager.exists(userId)) return;
10660        if (callingPackage == null) {
10661            callingPackage = Integer.toString(Binder.getCallingUid());
10662        }
10663        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10664    }
10665
10666    @Override
10667    public void setComponentEnabledSetting(ComponentName componentName,
10668            int newState, int flags, int userId) {
10669        if (!sUserManager.exists(userId)) return;
10670        setEnabledSetting(componentName.getPackageName(),
10671                componentName.getClassName(), newState, flags, userId, null);
10672    }
10673
10674    private void setEnabledSetting(final String packageName, String className, int newState,
10675            final int flags, int userId, String callingPackage) {
10676        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10677              || newState == COMPONENT_ENABLED_STATE_ENABLED
10678              || newState == COMPONENT_ENABLED_STATE_DISABLED
10679              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10680              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10681            throw new IllegalArgumentException("Invalid new component state: "
10682                    + newState);
10683        }
10684        PackageSetting pkgSetting;
10685        final int uid = Binder.getCallingUid();
10686        final int permission = mContext.checkCallingOrSelfPermission(
10687                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10688        enforceCrossUserPermission(uid, userId, false, "set enabled");
10689        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10690        boolean sendNow = false;
10691        boolean isApp = (className == null);
10692        String componentName = isApp ? packageName : className;
10693        int packageUid = -1;
10694        ArrayList<String> components;
10695
10696        // writer
10697        synchronized (mPackages) {
10698            pkgSetting = mSettings.mPackages.get(packageName);
10699            if (pkgSetting == null) {
10700                if (className == null) {
10701                    throw new IllegalArgumentException(
10702                            "Unknown package: " + packageName);
10703                }
10704                throw new IllegalArgumentException(
10705                        "Unknown component: " + packageName
10706                        + "/" + className);
10707            }
10708            // Allow root and verify that userId is not being specified by a different user
10709            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10710                throw new SecurityException(
10711                        "Permission Denial: attempt to change component state from pid="
10712                        + Binder.getCallingPid()
10713                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10714            }
10715            if (className == null) {
10716                // We're dealing with an application/package level state change
10717                if (pkgSetting.getEnabled(userId) == newState) {
10718                    // Nothing to do
10719                    return;
10720                }
10721                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10722                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10723                    // Don't care about who enables an app.
10724                    callingPackage = null;
10725                }
10726                pkgSetting.setEnabled(newState, userId, callingPackage);
10727                // pkgSetting.pkg.mSetEnabled = newState;
10728            } else {
10729                // We're dealing with a component level state change
10730                // First, verify that this is a valid class name.
10731                PackageParser.Package pkg = pkgSetting.pkg;
10732                if (pkg == null || !pkg.hasComponentClassName(className)) {
10733                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10734                        throw new IllegalArgumentException("Component class " + className
10735                                + " does not exist in " + packageName);
10736                    } else {
10737                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10738                                + className + " does not exist in " + packageName);
10739                    }
10740                }
10741                switch (newState) {
10742                case COMPONENT_ENABLED_STATE_ENABLED:
10743                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10744                        return;
10745                    }
10746                    break;
10747                case COMPONENT_ENABLED_STATE_DISABLED:
10748                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10749                        return;
10750                    }
10751                    break;
10752                case COMPONENT_ENABLED_STATE_DEFAULT:
10753                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10754                        return;
10755                    }
10756                    break;
10757                default:
10758                    Slog.e(TAG, "Invalid new component state: " + newState);
10759                    return;
10760                }
10761            }
10762            mSettings.writePackageRestrictionsLPr(userId);
10763            components = mPendingBroadcasts.get(userId, packageName);
10764            final boolean newPackage = components == null;
10765            if (newPackage) {
10766                components = new ArrayList<String>();
10767            }
10768            if (!components.contains(componentName)) {
10769                components.add(componentName);
10770            }
10771            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10772                sendNow = true;
10773                // Purge entry from pending broadcast list if another one exists already
10774                // since we are sending one right away.
10775                mPendingBroadcasts.remove(userId, packageName);
10776            } else {
10777                if (newPackage) {
10778                    mPendingBroadcasts.put(userId, packageName, components);
10779                }
10780                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10781                    // Schedule a message
10782                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10783                }
10784            }
10785        }
10786
10787        long callingId = Binder.clearCallingIdentity();
10788        try {
10789            if (sendNow) {
10790                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10791                sendPackageChangedBroadcast(packageName,
10792                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10793            }
10794        } finally {
10795            Binder.restoreCallingIdentity(callingId);
10796        }
10797    }
10798
10799    private void sendPackageChangedBroadcast(String packageName,
10800            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10801        if (DEBUG_INSTALL)
10802            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10803                    + componentNames);
10804        Bundle extras = new Bundle(4);
10805        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10806        String nameList[] = new String[componentNames.size()];
10807        componentNames.toArray(nameList);
10808        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10809        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10810        extras.putInt(Intent.EXTRA_UID, packageUid);
10811        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10812                new int[] {UserHandle.getUserId(packageUid)});
10813    }
10814
10815    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
10816        if (!sUserManager.exists(userId)) return;
10817        final int uid = Binder.getCallingUid();
10818        final int permission = mContext.checkCallingOrSelfPermission(
10819                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10820        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10821        enforceCrossUserPermission(uid, userId, true, "stop package");
10822        // writer
10823        synchronized (mPackages) {
10824            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
10825                    uid, userId)) {
10826                scheduleWritePackageRestrictionsLocked(userId);
10827            }
10828        }
10829    }
10830
10831    public String getInstallerPackageName(String packageName) {
10832        // reader
10833        synchronized (mPackages) {
10834            return mSettings.getInstallerPackageNameLPr(packageName);
10835        }
10836    }
10837
10838    @Override
10839    public int getApplicationEnabledSetting(String packageName, int userId) {
10840        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10841        int uid = Binder.getCallingUid();
10842        enforceCrossUserPermission(uid, userId, false, "get enabled");
10843        // reader
10844        synchronized (mPackages) {
10845            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
10846        }
10847    }
10848
10849    @Override
10850    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
10851        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10852        int uid = Binder.getCallingUid();
10853        enforceCrossUserPermission(uid, userId, false, "get component enabled");
10854        // reader
10855        synchronized (mPackages) {
10856            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
10857        }
10858    }
10859
10860    public void enterSafeMode() {
10861        enforceSystemOrRoot("Only the system can request entering safe mode");
10862
10863        if (!mSystemReady) {
10864            mSafeMode = true;
10865        }
10866    }
10867
10868    public void systemReady() {
10869        mSystemReady = true;
10870
10871        // Read the compatibilty setting when the system is ready.
10872        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
10873                mContext.getContentResolver(),
10874                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
10875        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
10876        if (DEBUG_SETTINGS) {
10877            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
10878        }
10879
10880        synchronized (mPackages) {
10881            // Verify that all of the preferred activity components actually
10882            // exist.  It is possible for applications to be updated and at
10883            // that point remove a previously declared activity component that
10884            // had been set as a preferred activity.  We try to clean this up
10885            // the next time we encounter that preferred activity, but it is
10886            // possible for the user flow to never be able to return to that
10887            // situation so here we do a sanity check to make sure we haven't
10888            // left any junk around.
10889            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
10890            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10891                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10892                removed.clear();
10893                for (PreferredActivity pa : pir.filterSet()) {
10894                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
10895                        removed.add(pa);
10896                    }
10897                }
10898                if (removed.size() > 0) {
10899                    for (int j=0; j<removed.size(); j++) {
10900                        PreferredActivity pa = removed.get(i);
10901                        Slog.w(TAG, "Removing dangling preferred activity: "
10902                                + pa.mPref.mComponent);
10903                        pir.removeFilter(pa);
10904                    }
10905                    mSettings.writePackageRestrictionsLPr(
10906                            mSettings.mPreferredActivities.keyAt(i));
10907                }
10908            }
10909        }
10910        sUserManager.systemReady();
10911    }
10912
10913    public boolean isSafeMode() {
10914        return mSafeMode;
10915    }
10916
10917    public boolean hasSystemUidErrors() {
10918        return mHasSystemUidErrors;
10919    }
10920
10921    static String arrayToString(int[] array) {
10922        StringBuffer buf = new StringBuffer(128);
10923        buf.append('[');
10924        if (array != null) {
10925            for (int i=0; i<array.length; i++) {
10926                if (i > 0) buf.append(", ");
10927                buf.append(array[i]);
10928            }
10929        }
10930        buf.append(']');
10931        return buf.toString();
10932    }
10933
10934    static class DumpState {
10935        public static final int DUMP_LIBS = 1 << 0;
10936
10937        public static final int DUMP_FEATURES = 1 << 1;
10938
10939        public static final int DUMP_RESOLVERS = 1 << 2;
10940
10941        public static final int DUMP_PERMISSIONS = 1 << 3;
10942
10943        public static final int DUMP_PACKAGES = 1 << 4;
10944
10945        public static final int DUMP_SHARED_USERS = 1 << 5;
10946
10947        public static final int DUMP_MESSAGES = 1 << 6;
10948
10949        public static final int DUMP_PROVIDERS = 1 << 7;
10950
10951        public static final int DUMP_VERIFIERS = 1 << 8;
10952
10953        public static final int DUMP_PREFERRED = 1 << 9;
10954
10955        public static final int DUMP_PREFERRED_XML = 1 << 10;
10956
10957        public static final int DUMP_KEYSETS = 1 << 11;
10958
10959        public static final int OPTION_SHOW_FILTERS = 1 << 0;
10960
10961        private int mTypes;
10962
10963        private int mOptions;
10964
10965        private boolean mTitlePrinted;
10966
10967        private SharedUserSetting mSharedUser;
10968
10969        public boolean isDumping(int type) {
10970            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
10971                return true;
10972            }
10973
10974            return (mTypes & type) != 0;
10975        }
10976
10977        public void setDump(int type) {
10978            mTypes |= type;
10979        }
10980
10981        public boolean isOptionEnabled(int option) {
10982            return (mOptions & option) != 0;
10983        }
10984
10985        public void setOptionEnabled(int option) {
10986            mOptions |= option;
10987        }
10988
10989        public boolean onTitlePrinted() {
10990            final boolean printed = mTitlePrinted;
10991            mTitlePrinted = true;
10992            return printed;
10993        }
10994
10995        public boolean getTitlePrinted() {
10996            return mTitlePrinted;
10997        }
10998
10999        public void setTitlePrinted(boolean enabled) {
11000            mTitlePrinted = enabled;
11001        }
11002
11003        public SharedUserSetting getSharedUser() {
11004            return mSharedUser;
11005        }
11006
11007        public void setSharedUser(SharedUserSetting user) {
11008            mSharedUser = user;
11009        }
11010    }
11011
11012    @Override
11013    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11014        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11015                != PackageManager.PERMISSION_GRANTED) {
11016            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11017                    + Binder.getCallingPid()
11018                    + ", uid=" + Binder.getCallingUid()
11019                    + " without permission "
11020                    + android.Manifest.permission.DUMP);
11021            return;
11022        }
11023
11024        DumpState dumpState = new DumpState();
11025        boolean fullPreferred = false;
11026        boolean checkin = false;
11027
11028        String packageName = null;
11029
11030        int opti = 0;
11031        while (opti < args.length) {
11032            String opt = args[opti];
11033            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11034                break;
11035            }
11036            opti++;
11037            if ("-a".equals(opt)) {
11038                // Right now we only know how to print all.
11039            } else if ("-h".equals(opt)) {
11040                pw.println("Package manager dump options:");
11041                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11042                pw.println("    --checkin: dump for a checkin");
11043                pw.println("    -f: print details of intent filters");
11044                pw.println("    -h: print this help");
11045                pw.println("  cmd may be one of:");
11046                pw.println("    l[ibraries]: list known shared libraries");
11047                pw.println("    f[ibraries]: list device features");
11048                pw.println("    r[esolvers]: dump intent resolvers");
11049                pw.println("    perm[issions]: dump permissions");
11050                pw.println("    pref[erred]: print preferred package settings");
11051                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11052                pw.println("    prov[iders]: dump content providers");
11053                pw.println("    p[ackages]: dump installed packages");
11054                pw.println("    s[hared-users]: dump shared user IDs");
11055                pw.println("    m[essages]: print collected runtime messages");
11056                pw.println("    v[erifiers]: print package verifier info");
11057                pw.println("    <package.name>: info about given package");
11058                pw.println("    k[eysets]: print known keysets");
11059                return;
11060            } else if ("--checkin".equals(opt)) {
11061                checkin = true;
11062            } else if ("-f".equals(opt)) {
11063                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11064            } else {
11065                pw.println("Unknown argument: " + opt + "; use -h for help");
11066            }
11067        }
11068
11069        // Is the caller requesting to dump a particular piece of data?
11070        if (opti < args.length) {
11071            String cmd = args[opti];
11072            opti++;
11073            // Is this a package name?
11074            if ("android".equals(cmd) || cmd.contains(".")) {
11075                packageName = cmd;
11076                // When dumping a single package, we always dump all of its
11077                // filter information since the amount of data will be reasonable.
11078                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11079            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11080                dumpState.setDump(DumpState.DUMP_LIBS);
11081            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11082                dumpState.setDump(DumpState.DUMP_FEATURES);
11083            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11084                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11085            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11086                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11087            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11088                dumpState.setDump(DumpState.DUMP_PREFERRED);
11089            } else if ("preferred-xml".equals(cmd)) {
11090                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11091                if (opti < args.length && "--full".equals(args[opti])) {
11092                    fullPreferred = true;
11093                    opti++;
11094                }
11095            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11096                dumpState.setDump(DumpState.DUMP_PACKAGES);
11097            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11098                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11099            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11100                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11101            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11102                dumpState.setDump(DumpState.DUMP_MESSAGES);
11103            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11104                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11105            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11106                dumpState.setDump(DumpState.DUMP_KEYSETS);
11107            }
11108        }
11109
11110        if (checkin) {
11111            pw.println("vers,1");
11112        }
11113
11114        // reader
11115        synchronized (mPackages) {
11116            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11117                if (!checkin) {
11118                    if (dumpState.onTitlePrinted())
11119                        pw.println();
11120                    pw.println("Verifiers:");
11121                    pw.print("  Required: ");
11122                    pw.print(mRequiredVerifierPackage);
11123                    pw.print(" (uid=");
11124                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11125                    pw.println(")");
11126                } else if (mRequiredVerifierPackage != null) {
11127                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11128                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11129                }
11130            }
11131
11132            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11133                boolean printedHeader = false;
11134                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11135                while (it.hasNext()) {
11136                    String name = it.next();
11137                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11138                    if (!checkin) {
11139                        if (!printedHeader) {
11140                            if (dumpState.onTitlePrinted())
11141                                pw.println();
11142                            pw.println("Libraries:");
11143                            printedHeader = true;
11144                        }
11145                        pw.print("  ");
11146                    } else {
11147                        pw.print("lib,");
11148                    }
11149                    pw.print(name);
11150                    if (!checkin) {
11151                        pw.print(" -> ");
11152                    }
11153                    if (ent.path != null) {
11154                        if (!checkin) {
11155                            pw.print("(jar) ");
11156                            pw.print(ent.path);
11157                        } else {
11158                            pw.print(",jar,");
11159                            pw.print(ent.path);
11160                        }
11161                    } else {
11162                        if (!checkin) {
11163                            pw.print("(apk) ");
11164                            pw.print(ent.apk);
11165                        } else {
11166                            pw.print(",apk,");
11167                            pw.print(ent.apk);
11168                        }
11169                    }
11170                    pw.println();
11171                }
11172            }
11173
11174            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11175                if (dumpState.onTitlePrinted())
11176                    pw.println();
11177                if (!checkin) {
11178                    pw.println("Features:");
11179                }
11180                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11181                while (it.hasNext()) {
11182                    String name = it.next();
11183                    if (!checkin) {
11184                        pw.print("  ");
11185                    } else {
11186                        pw.print("feat,");
11187                    }
11188                    pw.println(name);
11189                }
11190            }
11191
11192            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11193                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11194                        : "Activity Resolver Table:", "  ", packageName,
11195                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11196                    dumpState.setTitlePrinted(true);
11197                }
11198                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11199                        : "Receiver Resolver Table:", "  ", packageName,
11200                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11201                    dumpState.setTitlePrinted(true);
11202                }
11203                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11204                        : "Service Resolver Table:", "  ", packageName,
11205                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11206                    dumpState.setTitlePrinted(true);
11207                }
11208                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11209                        : "Provider Resolver Table:", "  ", packageName,
11210                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11211                    dumpState.setTitlePrinted(true);
11212                }
11213            }
11214
11215            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11216                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11217                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11218                    int user = mSettings.mPreferredActivities.keyAt(i);
11219                    if (pir.dump(pw,
11220                            dumpState.getTitlePrinted()
11221                                ? "\nPreferred Activities User " + user + ":"
11222                                : "Preferred Activities User " + user + ":", "  ",
11223                            packageName, true)) {
11224                        dumpState.setTitlePrinted(true);
11225                    }
11226                }
11227            }
11228
11229            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11230                pw.flush();
11231                FileOutputStream fout = new FileOutputStream(fd);
11232                BufferedOutputStream str = new BufferedOutputStream(fout);
11233                XmlSerializer serializer = new FastXmlSerializer();
11234                try {
11235                    serializer.setOutput(str, "utf-8");
11236                    serializer.startDocument(null, true);
11237                    serializer.setFeature(
11238                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11239                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11240                    serializer.endDocument();
11241                    serializer.flush();
11242                } catch (IllegalArgumentException e) {
11243                    pw.println("Failed writing: " + e);
11244                } catch (IllegalStateException e) {
11245                    pw.println("Failed writing: " + e);
11246                } catch (IOException e) {
11247                    pw.println("Failed writing: " + e);
11248                }
11249            }
11250
11251            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11252                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11253            }
11254
11255            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11256                boolean printedSomething = false;
11257                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11258                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11259                        continue;
11260                    }
11261                    if (!printedSomething) {
11262                        if (dumpState.onTitlePrinted())
11263                            pw.println();
11264                        pw.println("Registered ContentProviders:");
11265                        printedSomething = true;
11266                    }
11267                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11268                    pw.print("    "); pw.println(p.toString());
11269                }
11270                printedSomething = false;
11271                for (Map.Entry<String, PackageParser.Provider> entry :
11272                        mProvidersByAuthority.entrySet()) {
11273                    PackageParser.Provider p = entry.getValue();
11274                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11275                        continue;
11276                    }
11277                    if (!printedSomething) {
11278                        if (dumpState.onTitlePrinted())
11279                            pw.println();
11280                        pw.println("ContentProvider Authorities:");
11281                        printedSomething = true;
11282                    }
11283                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11284                    pw.print("    "); pw.println(p.toString());
11285                    if (p.info != null && p.info.applicationInfo != null) {
11286                        final String appInfo = p.info.applicationInfo.toString();
11287                        pw.print("      applicationInfo="); pw.println(appInfo);
11288                    }
11289                }
11290            }
11291
11292            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11293                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11294            }
11295
11296            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11297                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11298            }
11299
11300            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11301                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11302            }
11303
11304            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11305                if (dumpState.onTitlePrinted())
11306                    pw.println();
11307                mSettings.dumpReadMessagesLPr(pw, dumpState);
11308
11309                pw.println();
11310                pw.println("Package warning messages:");
11311                final File fname = getSettingsProblemFile();
11312                FileInputStream in = null;
11313                try {
11314                    in = new FileInputStream(fname);
11315                    final int avail = in.available();
11316                    final byte[] data = new byte[avail];
11317                    in.read(data);
11318                    pw.print(new String(data));
11319                } catch (FileNotFoundException e) {
11320                } catch (IOException e) {
11321                } finally {
11322                    if (in != null) {
11323                        try {
11324                            in.close();
11325                        } catch (IOException e) {
11326                        }
11327                    }
11328                }
11329            }
11330        }
11331    }
11332
11333    // ------- apps on sdcard specific code -------
11334    static final boolean DEBUG_SD_INSTALL = false;
11335
11336    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11337
11338    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11339
11340    private boolean mMediaMounted = false;
11341
11342    private String getEncryptKey() {
11343        try {
11344            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11345                    SD_ENCRYPTION_KEYSTORE_NAME);
11346            if (sdEncKey == null) {
11347                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11348                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11349                if (sdEncKey == null) {
11350                    Slog.e(TAG, "Failed to create encryption keys");
11351                    return null;
11352                }
11353            }
11354            return sdEncKey;
11355        } catch (NoSuchAlgorithmException nsae) {
11356            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11357            return null;
11358        } catch (IOException ioe) {
11359            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11360            return null;
11361        }
11362
11363    }
11364
11365    /* package */static String getTempContainerId() {
11366        int tmpIdx = 1;
11367        String list[] = PackageHelper.getSecureContainerList();
11368        if (list != null) {
11369            for (final String name : list) {
11370                // Ignore null and non-temporary container entries
11371                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11372                    continue;
11373                }
11374
11375                String subStr = name.substring(mTempContainerPrefix.length());
11376                try {
11377                    int cid = Integer.parseInt(subStr);
11378                    if (cid >= tmpIdx) {
11379                        tmpIdx = cid + 1;
11380                    }
11381                } catch (NumberFormatException e) {
11382                }
11383            }
11384        }
11385        return mTempContainerPrefix + tmpIdx;
11386    }
11387
11388    /*
11389     * Update media status on PackageManager.
11390     */
11391    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11392        int callingUid = Binder.getCallingUid();
11393        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11394            throw new SecurityException("Media status can only be updated by the system");
11395        }
11396        // reader; this apparently protects mMediaMounted, but should probably
11397        // be a different lock in that case.
11398        synchronized (mPackages) {
11399            Log.i(TAG, "Updating external media status from "
11400                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11401                    + (mediaStatus ? "mounted" : "unmounted"));
11402            if (DEBUG_SD_INSTALL)
11403                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11404                        + ", mMediaMounted=" + mMediaMounted);
11405            if (mediaStatus == mMediaMounted) {
11406                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11407                        : 0, -1);
11408                mHandler.sendMessage(msg);
11409                return;
11410            }
11411            mMediaMounted = mediaStatus;
11412        }
11413        // Queue up an async operation since the package installation may take a
11414        // little while.
11415        mHandler.post(new Runnable() {
11416            public void run() {
11417                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11418            }
11419        });
11420    }
11421
11422    /**
11423     * Called by MountService when the initial ASECs to scan are available.
11424     * Should block until all the ASEC containers are finished being scanned.
11425     */
11426    public void scanAvailableAsecs() {
11427        updateExternalMediaStatusInner(true, false, false);
11428    }
11429
11430    /*
11431     * Collect information of applications on external media, map them against
11432     * existing containers and update information based on current mount status.
11433     * Please note that we always have to report status if reportStatus has been
11434     * set to true especially when unloading packages.
11435     */
11436    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11437            boolean externalStorage) {
11438        // Collection of uids
11439        int uidArr[] = null;
11440        // Collection of stale containers
11441        HashSet<String> removeCids = new HashSet<String>();
11442        // Collection of packages on external media with valid containers.
11443        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11444        // Get list of secure containers.
11445        final String list[] = PackageHelper.getSecureContainerList();
11446        if (list == null || list.length == 0) {
11447            Log.i(TAG, "No secure containers on sdcard");
11448        } else {
11449            // Process list of secure containers and categorize them
11450            // as active or stale based on their package internal state.
11451            int uidList[] = new int[list.length];
11452            int num = 0;
11453            // reader
11454            synchronized (mPackages) {
11455                for (String cid : list) {
11456                    if (DEBUG_SD_INSTALL)
11457                        Log.i(TAG, "Processing container " + cid);
11458                    String pkgName = getAsecPackageName(cid);
11459                    if (pkgName == null) {
11460                        if (DEBUG_SD_INSTALL)
11461                            Log.i(TAG, "Container : " + cid + " stale");
11462                        removeCids.add(cid);
11463                        continue;
11464                    }
11465                    if (DEBUG_SD_INSTALL)
11466                        Log.i(TAG, "Looking for pkg : " + pkgName);
11467
11468                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11469                    if (ps == null) {
11470                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11471                        removeCids.add(cid);
11472                        continue;
11473                    }
11474
11475                    /*
11476                     * Skip packages that are not external if we're unmounting
11477                     * external storage.
11478                     */
11479                    if (externalStorage && !isMounted && !isExternal(ps)) {
11480                        continue;
11481                    }
11482
11483                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
11484                    // The package status is changed only if the code path
11485                    // matches between settings and the container id.
11486                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11487                        if (DEBUG_SD_INSTALL) {
11488                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11489                                    + " at code path: " + ps.codePathString);
11490                        }
11491
11492                        // We do have a valid package installed on sdcard
11493                        processCids.put(args, ps.codePathString);
11494                        final int uid = ps.appId;
11495                        if (uid != -1) {
11496                            uidList[num++] = uid;
11497                        }
11498                    } else {
11499                        Log.i(TAG, "Deleting stale container for " + cid);
11500                        removeCids.add(cid);
11501                    }
11502                }
11503            }
11504
11505            if (num > 0) {
11506                // Sort uid list
11507                Arrays.sort(uidList, 0, num);
11508                // Throw away duplicates
11509                uidArr = new int[num];
11510                uidArr[0] = uidList[0];
11511                int di = 0;
11512                for (int i = 1; i < num; i++) {
11513                    if (uidList[i - 1] != uidList[i]) {
11514                        uidArr[di++] = uidList[i];
11515                    }
11516                }
11517            }
11518        }
11519        // Process packages with valid entries.
11520        if (isMounted) {
11521            if (DEBUG_SD_INSTALL)
11522                Log.i(TAG, "Loading packages");
11523            loadMediaPackages(processCids, uidArr, removeCids);
11524            startCleaningPackages();
11525        } else {
11526            if (DEBUG_SD_INSTALL)
11527                Log.i(TAG, "Unloading packages");
11528            unloadMediaPackages(processCids, uidArr, reportStatus);
11529        }
11530    }
11531
11532   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11533           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11534        int size = pkgList.size();
11535        if (size > 0) {
11536            // Send broadcasts here
11537            Bundle extras = new Bundle();
11538            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11539                    .toArray(new String[size]));
11540            if (uidArr != null) {
11541                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11542            }
11543            if (replacing) {
11544                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11545            }
11546            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11547                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11548            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11549        }
11550    }
11551
11552   /*
11553     * Look at potentially valid container ids from processCids If package
11554     * information doesn't match the one on record or package scanning fails,
11555     * the cid is added to list of removeCids. We currently don't delete stale
11556     * containers.
11557     */
11558   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11559            HashSet<String> removeCids) {
11560        ArrayList<String> pkgList = new ArrayList<String>();
11561        Set<AsecInstallArgs> keys = processCids.keySet();
11562        boolean doGc = false;
11563        for (AsecInstallArgs args : keys) {
11564            String codePath = processCids.get(args);
11565            if (DEBUG_SD_INSTALL)
11566                Log.i(TAG, "Loading container : " + args.cid);
11567            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11568            try {
11569                // Make sure there are no container errors first.
11570                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11571                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11572                            + " when installing from sdcard");
11573                    continue;
11574                }
11575                // Check code path here.
11576                if (codePath == null || !codePath.equals(args.getCodePath())) {
11577                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11578                            + " does not match one in settings " + codePath);
11579                    continue;
11580                }
11581                // Parse package
11582                int parseFlags = mDefParseFlags;
11583                if (args.isExternal()) {
11584                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11585                }
11586                if (args.isFwdLocked()) {
11587                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11588                }
11589
11590                doGc = true;
11591                synchronized (mInstallLock) {
11592                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11593                            0, 0, null);
11594                    // Scan the package
11595                    if (pkg != null) {
11596                        /*
11597                         * TODO why is the lock being held? doPostInstall is
11598                         * called in other places without the lock. This needs
11599                         * to be straightened out.
11600                         */
11601                        // writer
11602                        synchronized (mPackages) {
11603                            retCode = PackageManager.INSTALL_SUCCEEDED;
11604                            pkgList.add(pkg.packageName);
11605                            // Post process args
11606                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11607                                    pkg.applicationInfo.uid);
11608                        }
11609                    } else {
11610                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11611                    }
11612                }
11613
11614            } finally {
11615                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11616                    // Don't destroy container here. Wait till gc clears things
11617                    // up.
11618                    removeCids.add(args.cid);
11619                }
11620            }
11621        }
11622        // writer
11623        synchronized (mPackages) {
11624            // If the platform SDK has changed since the last time we booted,
11625            // we need to re-grant app permission to catch any new ones that
11626            // appear. This is really a hack, and means that apps can in some
11627            // cases get permissions that the user didn't initially explicitly
11628            // allow... it would be nice to have some better way to handle
11629            // this situation.
11630            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11631            if (regrantPermissions)
11632                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11633                        + mSdkVersion + "; regranting permissions for external storage");
11634            mSettings.mExternalSdkPlatform = mSdkVersion;
11635
11636            // Make sure group IDs have been assigned, and any permission
11637            // changes in other apps are accounted for
11638            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11639                    | (regrantPermissions
11640                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11641                            : 0));
11642            // can downgrade to reader
11643            // Persist settings
11644            mSettings.writeLPr();
11645        }
11646        // Send a broadcast to let everyone know we are done processing
11647        if (pkgList.size() > 0) {
11648            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11649        }
11650        // Force gc to avoid any stale parser references that we might have.
11651        if (doGc) {
11652            Runtime.getRuntime().gc();
11653        }
11654        // List stale containers and destroy stale temporary containers.
11655        if (removeCids != null) {
11656            for (String cid : removeCids) {
11657                if (cid.startsWith(mTempContainerPrefix)) {
11658                    Log.i(TAG, "Destroying stale temporary container " + cid);
11659                    PackageHelper.destroySdDir(cid);
11660                } else {
11661                    Log.w(TAG, "Container " + cid + " is stale");
11662               }
11663           }
11664        }
11665    }
11666
11667   /*
11668     * Utility method to unload a list of specified containers
11669     */
11670    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11671        // Just unmount all valid containers.
11672        for (AsecInstallArgs arg : cidArgs) {
11673            synchronized (mInstallLock) {
11674                arg.doPostDeleteLI(false);
11675           }
11676       }
11677   }
11678
11679    /*
11680     * Unload packages mounted on external media. This involves deleting package
11681     * data from internal structures, sending broadcasts about diabled packages,
11682     * gc'ing to free up references, unmounting all secure containers
11683     * corresponding to packages on external media, and posting a
11684     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11685     * that we always have to post this message if status has been requested no
11686     * matter what.
11687     */
11688    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11689            final boolean reportStatus) {
11690        if (DEBUG_SD_INSTALL)
11691            Log.i(TAG, "unloading media packages");
11692        ArrayList<String> pkgList = new ArrayList<String>();
11693        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11694        final Set<AsecInstallArgs> keys = processCids.keySet();
11695        for (AsecInstallArgs args : keys) {
11696            String pkgName = args.getPackageName();
11697            if (DEBUG_SD_INSTALL)
11698                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11699            // Delete package internally
11700            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11701            synchronized (mInstallLock) {
11702                boolean res = deletePackageLI(pkgName, null, false, null, null,
11703                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11704                if (res) {
11705                    pkgList.add(pkgName);
11706                } else {
11707                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11708                    failedList.add(args);
11709                }
11710            }
11711        }
11712
11713        // reader
11714        synchronized (mPackages) {
11715            // We didn't update the settings after removing each package;
11716            // write them now for all packages.
11717            mSettings.writeLPr();
11718        }
11719
11720        // We have to absolutely send UPDATED_MEDIA_STATUS only
11721        // after confirming that all the receivers processed the ordered
11722        // broadcast when packages get disabled, force a gc to clean things up.
11723        // and unload all the containers.
11724        if (pkgList.size() > 0) {
11725            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11726                    new IIntentReceiver.Stub() {
11727                public void performReceive(Intent intent, int resultCode, String data,
11728                        Bundle extras, boolean ordered, boolean sticky,
11729                        int sendingUser) throws RemoteException {
11730                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11731                            reportStatus ? 1 : 0, 1, keys);
11732                    mHandler.sendMessage(msg);
11733                }
11734            });
11735        } else {
11736            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11737                    keys);
11738            mHandler.sendMessage(msg);
11739        }
11740    }
11741
11742    /** Binder call */
11743    @Override
11744    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11745            final int flags) {
11746        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11747        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11748        int returnCode = PackageManager.MOVE_SUCCEEDED;
11749        int currFlags = 0;
11750        int newFlags = 0;
11751        // reader
11752        synchronized (mPackages) {
11753            PackageParser.Package pkg = mPackages.get(packageName);
11754            if (pkg == null) {
11755                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11756            } else {
11757                // Disable moving fwd locked apps and system packages
11758                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11759                    Slog.w(TAG, "Cannot move system application");
11760                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11761                } else if (pkg.mOperationPending) {
11762                    Slog.w(TAG, "Attempt to move package which has pending operations");
11763                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11764                } else {
11765                    // Find install location first
11766                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11767                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11768                        Slog.w(TAG, "Ambigous flags specified for move location.");
11769                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11770                    } else {
11771                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11772                                : PackageManager.INSTALL_INTERNAL;
11773                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11774                                : PackageManager.INSTALL_INTERNAL;
11775
11776                        if (newFlags == currFlags) {
11777                            Slog.w(TAG, "No move required. Trying to move to same location");
11778                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11779                        } else {
11780                            if (isForwardLocked(pkg)) {
11781                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11782                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11783                            }
11784                        }
11785                    }
11786                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11787                        pkg.mOperationPending = true;
11788                    }
11789                }
11790            }
11791
11792            /*
11793             * TODO this next block probably shouldn't be inside the lock. We
11794             * can't guarantee these won't change after this is fired off
11795             * anyway.
11796             */
11797            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11798                processPendingMove(new MoveParams(null, observer, 0, packageName,
11799                        null, -1, user),
11800                        returnCode);
11801            } else {
11802                Message msg = mHandler.obtainMessage(INIT_COPY);
11803                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
11804                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
11805                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
11806                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
11807                msg.obj = mp;
11808                mHandler.sendMessage(msg);
11809            }
11810        }
11811    }
11812
11813    private void processPendingMove(final MoveParams mp, final int currentStatus) {
11814        // Queue up an async operation since the package deletion may take a
11815        // little while.
11816        mHandler.post(new Runnable() {
11817            public void run() {
11818                // TODO fix this; this does nothing.
11819                mHandler.removeCallbacks(this);
11820                int returnCode = currentStatus;
11821                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
11822                    int uidArr[] = null;
11823                    ArrayList<String> pkgList = null;
11824                    synchronized (mPackages) {
11825                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11826                        if (pkg == null) {
11827                            Slog.w(TAG, " Package " + mp.packageName
11828                                    + " doesn't exist. Aborting move");
11829                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11830                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
11831                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
11832                                    + mp.srcArgs.getCodePath() + " to "
11833                                    + pkg.applicationInfo.sourceDir
11834                                    + " Aborting move and returning error");
11835                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11836                        } else {
11837                            uidArr = new int[] {
11838                                pkg.applicationInfo.uid
11839                            };
11840                            pkgList = new ArrayList<String>();
11841                            pkgList.add(mp.packageName);
11842                        }
11843                    }
11844                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11845                        // Send resources unavailable broadcast
11846                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
11847                        // Update package code and resource paths
11848                        synchronized (mInstallLock) {
11849                            synchronized (mPackages) {
11850                                PackageParser.Package pkg = mPackages.get(mp.packageName);
11851                                // Recheck for package again.
11852                                if (pkg == null) {
11853                                    Slog.w(TAG, " Package " + mp.packageName
11854                                            + " doesn't exist. Aborting move");
11855                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11856                                } else if (!mp.srcArgs.getCodePath().equals(
11857                                        pkg.applicationInfo.sourceDir)) {
11858                                    Slog.w(TAG, "Package " + mp.packageName
11859                                            + " code path changed from " + mp.srcArgs.getCodePath()
11860                                            + " to " + pkg.applicationInfo.sourceDir
11861                                            + " Aborting move and returning error");
11862                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11863                                } else {
11864                                    final String oldCodePath = pkg.mPath;
11865                                    final String newCodePath = mp.targetArgs.getCodePath();
11866                                    final String newResPath = mp.targetArgs.getResourcePath();
11867                                    final String newNativePath = mp.targetArgs
11868                                            .getNativeLibraryPath();
11869
11870                                    final File newNativeDir = new File(newNativePath);
11871
11872                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
11873                                        NativeLibraryHelper.copyNativeBinariesIfNeededLI(
11874                                                new File(newCodePath), newNativeDir);
11875                                    }
11876                                    final int[] users = sUserManager.getUserIds();
11877                                    for (int user : users) {
11878                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
11879                                                newNativePath, user) < 0) {
11880                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11881                                        }
11882                                    }
11883
11884                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11885                                        pkg.mPath = newCodePath;
11886                                        // Move dex files around
11887                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
11888                                            // Moving of dex files failed. Set
11889                                            // error code and abort move.
11890                                            pkg.mPath = pkg.mScanPath;
11891                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11892                                        }
11893                                    }
11894
11895                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11896                                        pkg.mScanPath = newCodePath;
11897                                        pkg.applicationInfo.sourceDir = newCodePath;
11898                                        pkg.applicationInfo.publicSourceDir = newResPath;
11899                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
11900                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
11901                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
11902                                        ps.codePathString = ps.codePath.getPath();
11903                                        ps.resourcePath = new File(
11904                                                pkg.applicationInfo.publicSourceDir);
11905                                        ps.resourcePathString = ps.resourcePath.getPath();
11906                                        ps.nativeLibraryPathString = newNativePath;
11907                                        // Set the application info flag
11908                                        // correctly.
11909                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
11910                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11911                                        } else {
11912                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11913                                        }
11914                                        ps.setFlags(pkg.applicationInfo.flags);
11915                                        mAppDirs.remove(oldCodePath);
11916                                        mAppDirs.put(newCodePath, pkg);
11917                                        // Persist settings
11918                                        mSettings.writeLPr();
11919                                    }
11920                                }
11921                            }
11922                        }
11923                        // Send resources available broadcast
11924                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11925                    }
11926                }
11927                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11928                    // Clean up failed installation
11929                    if (mp.targetArgs != null) {
11930                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
11931                                -1);
11932                    }
11933                } else {
11934                    // Force a gc to clear things up.
11935                    Runtime.getRuntime().gc();
11936                    // Delete older code
11937                    synchronized (mInstallLock) {
11938                        mp.srcArgs.doPostDeleteLI(true);
11939                    }
11940                }
11941
11942                // Allow more operations on this file if we didn't fail because
11943                // an operation was already pending for this package.
11944                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
11945                    synchronized (mPackages) {
11946                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11947                        if (pkg != null) {
11948                            pkg.mOperationPending = false;
11949                       }
11950                   }
11951                }
11952
11953                IPackageMoveObserver observer = mp.observer;
11954                if (observer != null) {
11955                    try {
11956                        observer.packageMoved(mp.packageName, returnCode);
11957                    } catch (RemoteException e) {
11958                        Log.i(TAG, "Observer no longer exists.");
11959                    }
11960                }
11961            }
11962        });
11963    }
11964
11965    public boolean setInstallLocation(int loc) {
11966        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
11967                null);
11968        if (getInstallLocation() == loc) {
11969            return true;
11970        }
11971        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
11972                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
11973            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
11974                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
11975            return true;
11976        }
11977        return false;
11978   }
11979
11980    public int getInstallLocation() {
11981        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11982                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
11983                PackageHelper.APP_INSTALL_AUTO);
11984    }
11985
11986    /** Called by UserManagerService */
11987    void cleanUpUserLILPw(int userHandle) {
11988        mDirtyUsers.remove(userHandle);
11989        mSettings.removeUserLPr(userHandle);
11990        mPendingBroadcasts.remove(userHandle);
11991        if (mInstaller != null) {
11992            // Technically, we shouldn't be doing this with the package lock
11993            // held.  However, this is very rare, and there is already so much
11994            // other disk I/O going on, that we'll let it slide for now.
11995            mInstaller.removeUserDataDirs(userHandle);
11996        }
11997    }
11998
11999    /** Called by UserManagerService */
12000    void createNewUserLILPw(int userHandle, File path) {
12001        if (mInstaller != null) {
12002            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12003        }
12004    }
12005
12006    @Override
12007    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12008        mContext.enforceCallingOrSelfPermission(
12009                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12010                "Only package verification agents can read the verifier device identity");
12011
12012        synchronized (mPackages) {
12013            return mSettings.getVerifierDeviceIdentityLPw();
12014        }
12015    }
12016
12017    @Override
12018    public void setPermissionEnforced(String permission, boolean enforced) {
12019        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12020        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12021            synchronized (mPackages) {
12022                if (mSettings.mReadExternalStorageEnforced == null
12023                        || mSettings.mReadExternalStorageEnforced != enforced) {
12024                    mSettings.mReadExternalStorageEnforced = enforced;
12025                    mSettings.writeLPr();
12026                }
12027            }
12028            // kill any non-foreground processes so we restart them and
12029            // grant/revoke the GID.
12030            final IActivityManager am = ActivityManagerNative.getDefault();
12031            if (am != null) {
12032                final long token = Binder.clearCallingIdentity();
12033                try {
12034                    am.killProcessesBelowForeground("setPermissionEnforcement");
12035                } catch (RemoteException e) {
12036                } finally {
12037                    Binder.restoreCallingIdentity(token);
12038                }
12039            }
12040        } else {
12041            throw new IllegalArgumentException("No selective enforcement for " + permission);
12042        }
12043    }
12044
12045    @Override
12046    @Deprecated
12047    public boolean isPermissionEnforced(String permission) {
12048        return true;
12049    }
12050
12051    @Override
12052    public boolean isStorageLow() {
12053        final long token = Binder.clearCallingIdentity();
12054        try {
12055            final DeviceStorageMonitorInternal
12056                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12057            if (dsm != null) {
12058                return dsm.isMemoryLow();
12059            } else {
12060                return false;
12061            }
12062        } finally {
12063            Binder.restoreCallingIdentity(token);
12064        }
12065    }
12066}
12067