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