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