PackageManagerService.java revision 98bab263500b258025c9c6ca64f8aaff7dc914f4
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.isDexOptNeeded(lib)) {
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.isDexOptNeeded(path)) {
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.isDexOptNeeded(path)) {
4092                    if (!forceDex && defer) {
4093                        if (mDeferredDexOpt == null) {
4094                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4095                        }
4096                        mDeferredDexOpt.add(pkg);
4097                        return DEX_OPT_DEFERRED;
4098                    } else {
4099                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4100                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4101                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
4102                        pkg.mDidDexOpt = true;
4103                        performed = true;
4104                    }
4105                }
4106            } catch (FileNotFoundException e) {
4107                Slog.w(TAG, "Apk not found for dexopt: " + path);
4108                ret = -1;
4109            } catch (IOException e) {
4110                Slog.w(TAG, "IOException reading apk: " + path, e);
4111                ret = -1;
4112            } catch (dalvik.system.StaleDexCacheError e) {
4113                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4114                ret = -1;
4115            } catch (Exception e) {
4116                Slog.w(TAG, "Exception when doing dexopt : ", e);
4117                ret = -1;
4118            }
4119            if (ret < 0) {
4120                //error from installer
4121                return DEX_OPT_FAILED;
4122            }
4123        }
4124
4125        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4126    }
4127
4128    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4129            boolean inclDependencies) {
4130        HashSet<String> done;
4131        boolean performed = false;
4132        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4133            done = new HashSet<String>();
4134            done.add(pkg.packageName);
4135        } else {
4136            done = null;
4137        }
4138        return performDexOptLI(pkg, forceDex, defer, done);
4139    }
4140
4141    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4142        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4143            Slog.w(TAG, "Unable to update from " + oldPkg.name
4144                    + " to " + newPkg.packageName
4145                    + ": old package not in system partition");
4146            return false;
4147        } else if (mPackages.get(oldPkg.name) != null) {
4148            Slog.w(TAG, "Unable to update from " + oldPkg.name
4149                    + " to " + newPkg.packageName
4150                    + ": old package still exists");
4151            return false;
4152        }
4153        return true;
4154    }
4155
4156    File getDataPathForUser(int userId) {
4157        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4158    }
4159
4160    private File getDataPathForPackage(String packageName, int userId) {
4161        /*
4162         * Until we fully support multiple users, return the directory we
4163         * previously would have. The PackageManagerTests will need to be
4164         * revised when this is changed back..
4165         */
4166        if (userId == 0) {
4167            return new File(mAppDataDir, packageName);
4168        } else {
4169            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4170                + File.separator + packageName);
4171        }
4172    }
4173
4174    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4175        int[] users = sUserManager.getUserIds();
4176        int res = mInstaller.install(packageName, uid, uid, seinfo);
4177        if (res < 0) {
4178            return res;
4179        }
4180        for (int user : users) {
4181            if (user != 0) {
4182                res = mInstaller.createUserData(packageName,
4183                        UserHandle.getUid(user, uid), user, seinfo);
4184                if (res < 0) {
4185                    return res;
4186                }
4187            }
4188        }
4189        return res;
4190    }
4191
4192    private int removeDataDirsLI(String packageName) {
4193        int[] users = sUserManager.getUserIds();
4194        int res = 0;
4195        for (int user : users) {
4196            int resInner = mInstaller.remove(packageName, user);
4197            if (resInner < 0) {
4198                res = resInner;
4199            }
4200        }
4201
4202        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4203        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4204        if (!nativeLibraryFile.delete()) {
4205            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4206        }
4207
4208        return res;
4209    }
4210
4211    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4212            PackageParser.Package changingLib) {
4213        if (file.path != null) {
4214            mTmpSharedLibraries[num] = file.path;
4215            return num+1;
4216        }
4217        PackageParser.Package p = mPackages.get(file.apk);
4218        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4219            // If we are doing this while in the middle of updating a library apk,
4220            // then we need to make sure to use that new apk for determining the
4221            // dependencies here.  (We haven't yet finished committing the new apk
4222            // to the package manager state.)
4223            if (p == null || p.packageName.equals(changingLib.packageName)) {
4224                p = changingLib;
4225            }
4226        }
4227        if (p != null) {
4228            String path = p.mPath;
4229            for (int i=0; i<num; i++) {
4230                if (mTmpSharedLibraries[i].equals(path)) {
4231                    return num;
4232                }
4233            }
4234            mTmpSharedLibraries[num] = p.mPath;
4235            return num+1;
4236        }
4237        return num;
4238    }
4239
4240    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4241            PackageParser.Package changingLib) {
4242        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4243            if (mTmpSharedLibraries == null ||
4244                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4245                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4246            }
4247            int num = 0;
4248            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4249            for (int i=0; i<N; i++) {
4250                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4251                if (file == null) {
4252                    Slog.e(TAG, "Package " + pkg.packageName
4253                            + " requires unavailable shared library "
4254                            + pkg.usesLibraries.get(i) + "; failing!");
4255                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4256                    return false;
4257                }
4258                num = addSharedLibraryLPw(file, num, changingLib);
4259            }
4260            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4261            for (int i=0; i<N; i++) {
4262                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4263                if (file == null) {
4264                    Slog.w(TAG, "Package " + pkg.packageName
4265                            + " desires unavailable shared library "
4266                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4267                } else {
4268                    num = addSharedLibraryLPw(file, num, changingLib);
4269                }
4270            }
4271            if (num > 0) {
4272                pkg.usesLibraryFiles = new String[num];
4273                System.arraycopy(mTmpSharedLibraries, 0,
4274                        pkg.usesLibraryFiles, 0, num);
4275            } else {
4276                pkg.usesLibraryFiles = null;
4277            }
4278        }
4279        return true;
4280    }
4281
4282    private static boolean hasString(List<String> list, List<String> which) {
4283        if (list == null) {
4284            return false;
4285        }
4286        for (int i=list.size()-1; i>=0; i--) {
4287            for (int j=which.size()-1; j>=0; j--) {
4288                if (which.get(j).equals(list.get(i))) {
4289                    return true;
4290                }
4291            }
4292        }
4293        return false;
4294    }
4295
4296    private void updateAllSharedLibrariesLPw() {
4297        for (PackageParser.Package pkg : mPackages.values()) {
4298            updateSharedLibrariesLPw(pkg, null);
4299        }
4300    }
4301
4302    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4303            PackageParser.Package changingPkg) {
4304        ArrayList<PackageParser.Package> res = null;
4305        for (PackageParser.Package pkg : mPackages.values()) {
4306            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4307                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4308                if (res == null) {
4309                    res = new ArrayList<PackageParser.Package>();
4310                }
4311                res.add(pkg);
4312                updateSharedLibrariesLPw(pkg, changingPkg);
4313            }
4314        }
4315        return res;
4316    }
4317
4318    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4319            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4320        File scanFile = new File(pkg.mScanPath);
4321        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4322                pkg.applicationInfo.publicSourceDir == null) {
4323            // Bail out. The resource and code paths haven't been set.
4324            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4325            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4326            return null;
4327        }
4328
4329        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4330            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4331        }
4332
4333        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4334            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4335        }
4336
4337        if (mCustomResolverComponentName != null &&
4338                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4339            setUpCustomResolverActivity(pkg);
4340        }
4341
4342        if (pkg.packageName.equals("android")) {
4343            synchronized (mPackages) {
4344                if (mAndroidApplication != null) {
4345                    Slog.w(TAG, "*************************************************");
4346                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4347                    Slog.w(TAG, " file=" + scanFile);
4348                    Slog.w(TAG, "*************************************************");
4349                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4350                    return null;
4351                }
4352
4353                // Set up information for our fall-back user intent resolution activity.
4354                mPlatformPackage = pkg;
4355                pkg.mVersionCode = mSdkVersion;
4356                mAndroidApplication = pkg.applicationInfo;
4357
4358                if (!mResolverReplaced) {
4359                    mResolveActivity.applicationInfo = mAndroidApplication;
4360                    mResolveActivity.name = ResolverActivity.class.getName();
4361                    mResolveActivity.packageName = mAndroidApplication.packageName;
4362                    mResolveActivity.processName = "system:ui";
4363                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4364                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4365                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4366                    mResolveActivity.exported = true;
4367                    mResolveActivity.enabled = true;
4368                    mResolveInfo.activityInfo = mResolveActivity;
4369                    mResolveInfo.priority = 0;
4370                    mResolveInfo.preferredOrder = 0;
4371                    mResolveInfo.match = 0;
4372                    mResolveComponentName = new ComponentName(
4373                            mAndroidApplication.packageName, mResolveActivity.name);
4374                }
4375            }
4376        }
4377
4378        if (DEBUG_PACKAGE_SCANNING) {
4379            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4380                Log.d(TAG, "Scanning package " + pkg.packageName);
4381        }
4382
4383        if (mPackages.containsKey(pkg.packageName)
4384                || mSharedLibraries.containsKey(pkg.packageName)) {
4385            Slog.w(TAG, "Application package " + pkg.packageName
4386                    + " already installed.  Skipping duplicate.");
4387            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4388            return null;
4389        }
4390
4391        // Initialize package source and resource directories
4392        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4393        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4394
4395        SharedUserSetting suid = null;
4396        PackageSetting pkgSetting = null;
4397
4398        if (!isSystemApp(pkg)) {
4399            // Only system apps can use these features.
4400            pkg.mOriginalPackages = null;
4401            pkg.mRealPackage = null;
4402            pkg.mAdoptPermissions = null;
4403        }
4404
4405        // writer
4406        synchronized (mPackages) {
4407            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4408                // Check all shared libraries and map to their actual file path.
4409                // We only do this here for apps not on a system dir, because those
4410                // are the only ones that can fail an install due to this.  We
4411                // will take care of the system apps by updating all of their
4412                // library paths after the scan is done.
4413                if (!updateSharedLibrariesLPw(pkg, null)) {
4414                    return null;
4415                }
4416            }
4417
4418            if (pkg.mSharedUserId != null) {
4419                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4420                if (suid == null) {
4421                    Slog.w(TAG, "Creating application package " + pkg.packageName
4422                            + " for shared user failed");
4423                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4424                    return null;
4425                }
4426                if (DEBUG_PACKAGE_SCANNING) {
4427                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4428                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4429                                + "): packages=" + suid.packages);
4430                }
4431            }
4432
4433            // Check if we are renaming from an original package name.
4434            PackageSetting origPackage = null;
4435            String realName = null;
4436            if (pkg.mOriginalPackages != null) {
4437                // This package may need to be renamed to a previously
4438                // installed name.  Let's check on that...
4439                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4440                if (pkg.mOriginalPackages.contains(renamed)) {
4441                    // This package had originally been installed as the
4442                    // original name, and we have already taken care of
4443                    // transitioning to the new one.  Just update the new
4444                    // one to continue using the old name.
4445                    realName = pkg.mRealPackage;
4446                    if (!pkg.packageName.equals(renamed)) {
4447                        // Callers into this function may have already taken
4448                        // care of renaming the package; only do it here if
4449                        // it is not already done.
4450                        pkg.setPackageName(renamed);
4451                    }
4452
4453                } else {
4454                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4455                        if ((origPackage = mSettings.peekPackageLPr(
4456                                pkg.mOriginalPackages.get(i))) != null) {
4457                            // We do have the package already installed under its
4458                            // original name...  should we use it?
4459                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4460                                // New package is not compatible with original.
4461                                origPackage = null;
4462                                continue;
4463                            } else if (origPackage.sharedUser != null) {
4464                                // Make sure uid is compatible between packages.
4465                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4466                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4467                                            + " to " + pkg.packageName + ": old uid "
4468                                            + origPackage.sharedUser.name
4469                                            + " differs from " + pkg.mSharedUserId);
4470                                    origPackage = null;
4471                                    continue;
4472                                }
4473                            } else {
4474                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4475                                        + pkg.packageName + " to old name " + origPackage.name);
4476                            }
4477                            break;
4478                        }
4479                    }
4480                }
4481            }
4482
4483            if (mTransferedPackages.contains(pkg.packageName)) {
4484                Slog.w(TAG, "Package " + pkg.packageName
4485                        + " was transferred to another, but its .apk remains");
4486            }
4487
4488            // Just create the setting, don't add it yet. For already existing packages
4489            // the PkgSetting exists already and doesn't have to be created.
4490            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4491                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4492                    pkg.applicationInfo.flags, user, false);
4493            if (pkgSetting == null) {
4494                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4495                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4496                return null;
4497            }
4498
4499            if (pkgSetting.origPackage != null) {
4500                // If we are first transitioning from an original package,
4501                // fix up the new package's name now.  We need to do this after
4502                // looking up the package under its new name, so getPackageLP
4503                // can take care of fiddling things correctly.
4504                pkg.setPackageName(origPackage.name);
4505
4506                // File a report about this.
4507                String msg = "New package " + pkgSetting.realName
4508                        + " renamed to replace old package " + pkgSetting.name;
4509                reportSettingsProblem(Log.WARN, msg);
4510
4511                // Make a note of it.
4512                mTransferedPackages.add(origPackage.name);
4513
4514                // No longer need to retain this.
4515                pkgSetting.origPackage = null;
4516            }
4517
4518            if (realName != null) {
4519                // Make a note of it.
4520                mTransferedPackages.add(pkg.packageName);
4521            }
4522
4523            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4524                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4525            }
4526
4527            if (mFoundPolicyFile) {
4528                SELinuxMMAC.assignSeinfoValue(pkg);
4529            }
4530
4531            pkg.applicationInfo.uid = pkgSetting.appId;
4532            pkg.mExtras = pkgSetting;
4533
4534            if (!verifySignaturesLP(pkgSetting, pkg)) {
4535                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4536                    return null;
4537                }
4538                // The signature has changed, but this package is in the system
4539                // image...  let's recover!
4540                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4541                // However...  if this package is part of a shared user, but it
4542                // doesn't match the signature of the shared user, let's fail.
4543                // What this means is that you can't change the signatures
4544                // associated with an overall shared user, which doesn't seem all
4545                // that unreasonable.
4546                if (pkgSetting.sharedUser != null) {
4547                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4548                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4549                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4550                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4551                        return null;
4552                    }
4553                }
4554                // File a report about this.
4555                String msg = "System package " + pkg.packageName
4556                        + " signature changed; retaining data.";
4557                reportSettingsProblem(Log.WARN, msg);
4558            }
4559
4560            // Verify that this new package doesn't have any content providers
4561            // that conflict with existing packages.  Only do this if the
4562            // package isn't already installed, since we don't want to break
4563            // things that are installed.
4564            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4565                final int N = pkg.providers.size();
4566                int i;
4567                for (i=0; i<N; i++) {
4568                    PackageParser.Provider p = pkg.providers.get(i);
4569                    if (p.info.authority != null) {
4570                        String names[] = p.info.authority.split(";");
4571                        for (int j = 0; j < names.length; j++) {
4572                            if (mProvidersByAuthority.containsKey(names[j])) {
4573                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4574                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4575                                        " (in package " + pkg.applicationInfo.packageName +
4576                                        ") is already used by "
4577                                        + ((other != null && other.getComponentName() != null)
4578                                                ? other.getComponentName().getPackageName() : "?"));
4579                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4580                                return null;
4581                            }
4582                        }
4583                    }
4584                }
4585            }
4586
4587            if (pkg.mAdoptPermissions != null) {
4588                // This package wants to adopt ownership of permissions from
4589                // another package.
4590                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4591                    final String origName = pkg.mAdoptPermissions.get(i);
4592                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4593                    if (orig != null) {
4594                        if (verifyPackageUpdateLPr(orig, pkg)) {
4595                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4596                                    + pkg.packageName);
4597                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4598                        }
4599                    }
4600                }
4601            }
4602        }
4603
4604        final String pkgName = pkg.packageName;
4605
4606        final long scanFileTime = scanFile.lastModified();
4607        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4608        pkg.applicationInfo.processName = fixProcessName(
4609                pkg.applicationInfo.packageName,
4610                pkg.applicationInfo.processName,
4611                pkg.applicationInfo.uid);
4612
4613        File dataPath;
4614        if (mPlatformPackage == pkg) {
4615            // The system package is special.
4616            dataPath = new File (Environment.getDataDirectory(), "system");
4617            pkg.applicationInfo.dataDir = dataPath.getPath();
4618        } else {
4619            // This is a normal package, need to make its data directory.
4620            dataPath = getDataPathForPackage(pkg.packageName, 0);
4621
4622            boolean uidError = false;
4623
4624            if (dataPath.exists()) {
4625                int currentUid = 0;
4626                try {
4627                    StructStat stat = Libcore.os.stat(dataPath.getPath());
4628                    currentUid = stat.st_uid;
4629                } catch (ErrnoException e) {
4630                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4631                }
4632
4633                // If we have mismatched owners for the data path, we have a problem.
4634                if (currentUid != pkg.applicationInfo.uid) {
4635                    boolean recovered = false;
4636                    if (currentUid == 0) {
4637                        // The directory somehow became owned by root.  Wow.
4638                        // This is probably because the system was stopped while
4639                        // installd was in the middle of messing with its libs
4640                        // directory.  Ask installd to fix that.
4641                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4642                                pkg.applicationInfo.uid);
4643                        if (ret >= 0) {
4644                            recovered = true;
4645                            String msg = "Package " + pkg.packageName
4646                                    + " unexpectedly changed to uid 0; recovered to " +
4647                                    + pkg.applicationInfo.uid;
4648                            reportSettingsProblem(Log.WARN, msg);
4649                        }
4650                    }
4651                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4652                            || (scanMode&SCAN_BOOTING) != 0)) {
4653                        // If this is a system app, we can at least delete its
4654                        // current data so the application will still work.
4655                        int ret = removeDataDirsLI(pkgName);
4656                        if (ret >= 0) {
4657                            // TODO: Kill the processes first
4658                            // Old data gone!
4659                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4660                                    ? "System package " : "Third party package ";
4661                            String msg = prefix + pkg.packageName
4662                                    + " has changed from uid: "
4663                                    + currentUid + " to "
4664                                    + pkg.applicationInfo.uid + "; old data erased";
4665                            reportSettingsProblem(Log.WARN, msg);
4666                            recovered = true;
4667
4668                            // And now re-install the app.
4669                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4670                                                   pkg.applicationInfo.seinfo);
4671                            if (ret == -1) {
4672                                // Ack should not happen!
4673                                msg = prefix + pkg.packageName
4674                                        + " could not have data directory re-created after delete.";
4675                                reportSettingsProblem(Log.WARN, msg);
4676                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4677                                return null;
4678                            }
4679                        }
4680                        if (!recovered) {
4681                            mHasSystemUidErrors = true;
4682                        }
4683                    } else if (!recovered) {
4684                        // If we allow this install to proceed, we will be broken.
4685                        // Abort, abort!
4686                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4687                        return null;
4688                    }
4689                    if (!recovered) {
4690                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4691                            + pkg.applicationInfo.uid + "/fs_"
4692                            + currentUid;
4693                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4694                        String msg = "Package " + pkg.packageName
4695                                + " has mismatched uid: "
4696                                + currentUid + " on disk, "
4697                                + pkg.applicationInfo.uid + " in settings";
4698                        // writer
4699                        synchronized (mPackages) {
4700                            mSettings.mReadMessages.append(msg);
4701                            mSettings.mReadMessages.append('\n');
4702                            uidError = true;
4703                            if (!pkgSetting.uidError) {
4704                                reportSettingsProblem(Log.ERROR, msg);
4705                            }
4706                        }
4707                    }
4708                }
4709                pkg.applicationInfo.dataDir = dataPath.getPath();
4710            } else {
4711                if (DEBUG_PACKAGE_SCANNING) {
4712                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4713                        Log.v(TAG, "Want this data dir: " + dataPath);
4714                }
4715                //invoke installer to do the actual installation
4716                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4717                                           pkg.applicationInfo.seinfo);
4718                if (ret < 0) {
4719                    // Error from installer
4720                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4721                    return null;
4722                }
4723
4724                if (dataPath.exists()) {
4725                    pkg.applicationInfo.dataDir = dataPath.getPath();
4726                } else {
4727                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4728                    pkg.applicationInfo.dataDir = null;
4729                }
4730            }
4731
4732            /*
4733             * Set the data dir to the default "/data/data/<package name>/lib"
4734             * if we got here without anyone telling us different (e.g., apps
4735             * stored on SD card have their native libraries stored in the ASEC
4736             * container with the APK).
4737             *
4738             * This happens during an upgrade from a package settings file that
4739             * doesn't have a native library path attribute at all.
4740             */
4741            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4742                if (pkgSetting.nativeLibraryPathString == null) {
4743                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4744                } else {
4745                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4746                }
4747            }
4748
4749            pkgSetting.uidError = uidError;
4750        }
4751
4752        String path = scanFile.getPath();
4753        /* Note: We don't want to unpack the native binaries for
4754         *        system applications, unless they have been updated
4755         *        (the binaries are already under /system/lib).
4756         *        Also, don't unpack libs for apps on the external card
4757         *        since they should have their libraries in the ASEC
4758         *        container already.
4759         *
4760         *        In other words, we're going to unpack the binaries
4761         *        only for non-system apps and system app upgrades.
4762         */
4763        if (pkg.applicationInfo.nativeLibraryDir != null) {
4764            try {
4765                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4766                final String dataPathString = dataPath.getCanonicalPath();
4767
4768                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4769                    /*
4770                     * Upgrading from a previous version of the OS sometimes
4771                     * leaves native libraries in the /data/data/<app>/lib
4772                     * directory for system apps even when they shouldn't be.
4773                     * Recent changes in the JNI library search path
4774                     * necessitates we remove those to match previous behavior.
4775                     */
4776                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4777                        Log.i(TAG, "removed obsolete native libraries for system package "
4778                                + path);
4779                    }
4780                } else {
4781                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4782                        /*
4783                         * Update native library dir if it starts with
4784                         * /data/data
4785                         */
4786                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4787                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
4788                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4789                        }
4790
4791                        try {
4792                            if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4793                                Slog.e(TAG, "Unable to copy native libraries");
4794                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4795                                return null;
4796                            }
4797                        } catch (IOException e) {
4798                            Slog.e(TAG, "Unable to copy native libraries", e);
4799                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4800                            return null;
4801                        }
4802                    }
4803
4804                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4805                    final int[] userIds = sUserManager.getUserIds();
4806                    synchronized (mInstallLock) {
4807                        for (int userId : userIds) {
4808                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4809                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4810                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4811                                        + ")");
4812                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4813                                return null;
4814                            }
4815                        }
4816                    }
4817                }
4818            } catch (IOException ioe) {
4819                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4820            }
4821        }
4822        pkg.mScanPath = path;
4823
4824        if ((scanMode&SCAN_NO_DEX) == 0) {
4825            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4826                    == DEX_OPT_FAILED) {
4827                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4828                    removeDataDirsLI(pkg.packageName);
4829                }
4830
4831                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4832                return null;
4833            }
4834        }
4835
4836        if (mFactoryTest && pkg.requestedPermissions.contains(
4837                android.Manifest.permission.FACTORY_TEST)) {
4838            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4839        }
4840
4841        ArrayList<PackageParser.Package> clientLibPkgs = null;
4842
4843        // writer
4844        synchronized (mPackages) {
4845            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4846                // Only system apps can add new shared libraries.
4847                if (pkg.libraryNames != null) {
4848                    for (int i=0; i<pkg.libraryNames.size(); i++) {
4849                        String name = pkg.libraryNames.get(i);
4850                        boolean allowed = false;
4851                        if (isUpdatedSystemApp(pkg)) {
4852                            // New library entries can only be added through the
4853                            // system image.  This is important to get rid of a lot
4854                            // of nasty edge cases: for example if we allowed a non-
4855                            // system update of the app to add a library, then uninstalling
4856                            // the update would make the library go away, and assumptions
4857                            // we made such as through app install filtering would now
4858                            // have allowed apps on the device which aren't compatible
4859                            // with it.  Better to just have the restriction here, be
4860                            // conservative, and create many fewer cases that can negatively
4861                            // impact the user experience.
4862                            final PackageSetting sysPs = mSettings
4863                                    .getDisabledSystemPkgLPr(pkg.packageName);
4864                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4865                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4866                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4867                                        allowed = true;
4868                                        allowed = true;
4869                                        break;
4870                                    }
4871                                }
4872                            }
4873                        } else {
4874                            allowed = true;
4875                        }
4876                        if (allowed) {
4877                            if (!mSharedLibraries.containsKey(name)) {
4878                                mSharedLibraries.put(name, new SharedLibraryEntry(null,
4879                                        pkg.packageName));
4880                            } else if (!name.equals(pkg.packageName)) {
4881                                Slog.w(TAG, "Package " + pkg.packageName + " library "
4882                                        + name + " already exists; skipping");
4883                            }
4884                        } else {
4885                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4886                                    + name + " that is not declared on system image; skipping");
4887                        }
4888                    }
4889                    if ((scanMode&SCAN_BOOTING) == 0) {
4890                        // If we are not booting, we need to update any applications
4891                        // that are clients of our shared library.  If we are booting,
4892                        // this will all be done once the scan is complete.
4893                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4894                    }
4895                }
4896            }
4897        }
4898
4899        // We also need to dexopt any apps that are dependent on this library.  Note that
4900        // if these fail, we should abort the install since installing the library will
4901        // result in some apps being broken.
4902        if (clientLibPkgs != null) {
4903            if ((scanMode&SCAN_NO_DEX) == 0) {
4904                for (int i=0; i<clientLibPkgs.size(); i++) {
4905                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
4906                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4907                            == DEX_OPT_FAILED) {
4908                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4909                            removeDataDirsLI(pkg.packageName);
4910                        }
4911
4912                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4913                        return null;
4914                    }
4915                }
4916            }
4917        }
4918
4919        // Request the ActivityManager to kill the process(only for existing packages)
4920        // so that we do not end up in a confused state while the user is still using the older
4921        // version of the application while the new one gets installed.
4922        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4923            // If the package lives in an asec, tell everyone that the container is going
4924            // away so they can clean up any references to its resources (which would prevent
4925            // vold from being able to unmount the asec)
4926            if (isForwardLocked(pkg) || isExternal(pkg)) {
4927                if (DEBUG_INSTALL) {
4928                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
4929                }
4930                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
4931                final ArrayList<String> pkgList = new ArrayList<String>(1);
4932                pkgList.add(pkg.applicationInfo.packageName);
4933                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
4934            }
4935
4936            // Post the request that it be killed now that the going-away broadcast is en route
4937            killApplication(pkg.applicationInfo.packageName,
4938                        pkg.applicationInfo.uid, "update pkg");
4939        }
4940
4941        // Also need to kill any apps that are dependent on the library.
4942        if (clientLibPkgs != null) {
4943            for (int i=0; i<clientLibPkgs.size(); i++) {
4944                PackageParser.Package clientPkg = clientLibPkgs.get(i);
4945                killApplication(clientPkg.applicationInfo.packageName,
4946                        clientPkg.applicationInfo.uid, "update lib");
4947            }
4948        }
4949
4950        // writer
4951        synchronized (mPackages) {
4952            // We don't expect installation to fail beyond this point,
4953            if ((scanMode&SCAN_MONITOR) != 0) {
4954                mAppDirs.put(pkg.mPath, pkg);
4955            }
4956            // Add the new setting to mSettings
4957            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
4958            // Add the new setting to mPackages
4959            mPackages.put(pkg.applicationInfo.packageName, pkg);
4960            // Make sure we don't accidentally delete its data.
4961            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4962            while (iter.hasNext()) {
4963                PackageCleanItem item = iter.next();
4964                if (pkgName.equals(item.packageName)) {
4965                    iter.remove();
4966                }
4967            }
4968
4969            // Take care of first install / last update times.
4970            if (currentTime != 0) {
4971                if (pkgSetting.firstInstallTime == 0) {
4972                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4973                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4974                    pkgSetting.lastUpdateTime = currentTime;
4975                }
4976            } else if (pkgSetting.firstInstallTime == 0) {
4977                // We need *something*.  Take time time stamp of the file.
4978                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4979            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4980                if (scanFileTime != pkgSetting.timeStamp) {
4981                    // A package on the system image has changed; consider this
4982                    // to be an update.
4983                    pkgSetting.lastUpdateTime = scanFileTime;
4984                }
4985            }
4986
4987            // Add the package's KeySets to the global KeySetManager
4988            KeySetManager ksm = mSettings.mKeySetManager;
4989            try {
4990                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
4991                if (pkg.mKeySetMapping != null) {
4992                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
4993                        if (entry.getValue() != null) {
4994                            ksm.addDefinedKeySetToPackage(pkg.packageName,
4995                                entry.getValue(), entry.getKey());
4996                        }
4997                    }
4998                }
4999            } catch (NullPointerException e) {
5000                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5001            } catch (IllegalArgumentException e) {
5002                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5003            }
5004
5005            int N = pkg.providers.size();
5006            StringBuilder r = null;
5007            int i;
5008            for (i=0; i<N; i++) {
5009                PackageParser.Provider p = pkg.providers.get(i);
5010                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5011                        p.info.processName, pkg.applicationInfo.uid);
5012                mProviders.addProvider(p);
5013                p.syncable = p.info.isSyncable;
5014                if (p.info.authority != null) {
5015                    String names[] = p.info.authority.split(";");
5016                    p.info.authority = null;
5017                    for (int j = 0; j < names.length; j++) {
5018                        if (j == 1 && p.syncable) {
5019                            // We only want the first authority for a provider to possibly be
5020                            // syncable, so if we already added this provider using a different
5021                            // authority clear the syncable flag. We copy the provider before
5022                            // changing it because the mProviders object contains a reference
5023                            // to a provider that we don't want to change.
5024                            // Only do this for the second authority since the resulting provider
5025                            // object can be the same for all future authorities for this provider.
5026                            p = new PackageParser.Provider(p);
5027                            p.syncable = false;
5028                        }
5029                        if (!mProvidersByAuthority.containsKey(names[j])) {
5030                            mProvidersByAuthority.put(names[j], p);
5031                            if (p.info.authority == null) {
5032                                p.info.authority = names[j];
5033                            } else {
5034                                p.info.authority = p.info.authority + ";" + names[j];
5035                            }
5036                            if (DEBUG_PACKAGE_SCANNING) {
5037                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5038                                    Log.d(TAG, "Registered content provider: " + names[j]
5039                                            + ", className = " + p.info.name + ", isSyncable = "
5040                                            + p.info.isSyncable);
5041                            }
5042                        } else {
5043                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5044                            Slog.w(TAG, "Skipping provider name " + names[j] +
5045                                    " (in package " + pkg.applicationInfo.packageName +
5046                                    "): name already used by "
5047                                    + ((other != null && other.getComponentName() != null)
5048                                            ? other.getComponentName().getPackageName() : "?"));
5049                        }
5050                    }
5051                }
5052                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5053                    if (r == null) {
5054                        r = new StringBuilder(256);
5055                    } else {
5056                        r.append(' ');
5057                    }
5058                    r.append(p.info.name);
5059                }
5060            }
5061            if (r != null) {
5062                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5063            }
5064
5065            N = pkg.services.size();
5066            r = null;
5067            for (i=0; i<N; i++) {
5068                PackageParser.Service s = pkg.services.get(i);
5069                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5070                        s.info.processName, pkg.applicationInfo.uid);
5071                mServices.addService(s);
5072                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5073                    if (r == null) {
5074                        r = new StringBuilder(256);
5075                    } else {
5076                        r.append(' ');
5077                    }
5078                    r.append(s.info.name);
5079                }
5080            }
5081            if (r != null) {
5082                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5083            }
5084
5085            N = pkg.receivers.size();
5086            r = null;
5087            for (i=0; i<N; i++) {
5088                PackageParser.Activity a = pkg.receivers.get(i);
5089                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5090                        a.info.processName, pkg.applicationInfo.uid);
5091                mReceivers.addActivity(a, "receiver");
5092                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5093                    if (r == null) {
5094                        r = new StringBuilder(256);
5095                    } else {
5096                        r.append(' ');
5097                    }
5098                    r.append(a.info.name);
5099                }
5100            }
5101            if (r != null) {
5102                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5103            }
5104
5105            N = pkg.activities.size();
5106            r = null;
5107            for (i=0; i<N; i++) {
5108                PackageParser.Activity a = pkg.activities.get(i);
5109                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5110                        a.info.processName, pkg.applicationInfo.uid);
5111                mActivities.addActivity(a, "activity");
5112                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5113                    if (r == null) {
5114                        r = new StringBuilder(256);
5115                    } else {
5116                        r.append(' ');
5117                    }
5118                    r.append(a.info.name);
5119                }
5120            }
5121            if (r != null) {
5122                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5123            }
5124
5125            N = pkg.permissionGroups.size();
5126            r = null;
5127            for (i=0; i<N; i++) {
5128                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5129                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5130                if (cur == null) {
5131                    mPermissionGroups.put(pg.info.name, pg);
5132                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5133                        if (r == null) {
5134                            r = new StringBuilder(256);
5135                        } else {
5136                            r.append(' ');
5137                        }
5138                        r.append(pg.info.name);
5139                    }
5140                } else {
5141                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5142                            + pg.info.packageName + " ignored: original from "
5143                            + cur.info.packageName);
5144                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5145                        if (r == null) {
5146                            r = new StringBuilder(256);
5147                        } else {
5148                            r.append(' ');
5149                        }
5150                        r.append("DUP:");
5151                        r.append(pg.info.name);
5152                    }
5153                }
5154            }
5155            if (r != null) {
5156                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5157            }
5158
5159            N = pkg.permissions.size();
5160            r = null;
5161            for (i=0; i<N; i++) {
5162                PackageParser.Permission p = pkg.permissions.get(i);
5163                HashMap<String, BasePermission> permissionMap =
5164                        p.tree ? mSettings.mPermissionTrees
5165                        : mSettings.mPermissions;
5166                p.group = mPermissionGroups.get(p.info.group);
5167                if (p.info.group == null || p.group != null) {
5168                    BasePermission bp = permissionMap.get(p.info.name);
5169                    if (bp == null) {
5170                        bp = new BasePermission(p.info.name, p.info.packageName,
5171                                BasePermission.TYPE_NORMAL);
5172                        permissionMap.put(p.info.name, bp);
5173                    }
5174                    if (bp.perm == null) {
5175                        if (bp.sourcePackage != null
5176                                && !bp.sourcePackage.equals(p.info.packageName)) {
5177                            // If this is a permission that was formerly defined by a non-system
5178                            // app, but is now defined by a system app (following an upgrade),
5179                            // discard the previous declaration and consider the system's to be
5180                            // canonical.
5181                            if (isSystemApp(p.owner)) {
5182                                String msg = "New decl " + p.owner + " of permission  "
5183                                        + p.info.name + " is system";
5184                                reportSettingsProblem(Log.WARN, msg);
5185                                bp.sourcePackage = null;
5186                            }
5187                        }
5188                        if (bp.sourcePackage == null
5189                                || bp.sourcePackage.equals(p.info.packageName)) {
5190                            BasePermission tree = findPermissionTreeLP(p.info.name);
5191                            if (tree == null
5192                                    || tree.sourcePackage.equals(p.info.packageName)) {
5193                                bp.packageSetting = pkgSetting;
5194                                bp.perm = p;
5195                                bp.uid = pkg.applicationInfo.uid;
5196                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5197                                    if (r == null) {
5198                                        r = new StringBuilder(256);
5199                                    } else {
5200                                        r.append(' ');
5201                                    }
5202                                    r.append(p.info.name);
5203                                }
5204                            } else {
5205                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5206                                        + p.info.packageName + " ignored: base tree "
5207                                        + tree.name + " is from package "
5208                                        + tree.sourcePackage);
5209                            }
5210                        } else {
5211                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5212                                    + p.info.packageName + " ignored: original from "
5213                                    + bp.sourcePackage);
5214                        }
5215                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5216                        if (r == null) {
5217                            r = new StringBuilder(256);
5218                        } else {
5219                            r.append(' ');
5220                        }
5221                        r.append("DUP:");
5222                        r.append(p.info.name);
5223                    }
5224                    if (bp.perm == p) {
5225                        bp.protectionLevel = p.info.protectionLevel;
5226                    }
5227                } else {
5228                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5229                            + p.info.packageName + " ignored: no group "
5230                            + p.group);
5231                }
5232            }
5233            if (r != null) {
5234                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5235            }
5236
5237            N = pkg.instrumentation.size();
5238            r = null;
5239            for (i=0; i<N; i++) {
5240                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5241                a.info.packageName = pkg.applicationInfo.packageName;
5242                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5243                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5244                a.info.dataDir = pkg.applicationInfo.dataDir;
5245                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5246                mInstrumentation.put(a.getComponentName(), a);
5247                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5248                    if (r == null) {
5249                        r = new StringBuilder(256);
5250                    } else {
5251                        r.append(' ');
5252                    }
5253                    r.append(a.info.name);
5254                }
5255            }
5256            if (r != null) {
5257                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5258            }
5259
5260            if (pkg.protectedBroadcasts != null) {
5261                N = pkg.protectedBroadcasts.size();
5262                for (i=0; i<N; i++) {
5263                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5264                }
5265            }
5266
5267            pkgSetting.setTimeStamp(scanFileTime);
5268
5269            // Create idmap files for pairs of (packages, overlay packages).
5270            // Note: "android", ie framework-res.apk, is handled by native layers.
5271            if (pkg.mOverlayTarget != null) {
5272                // This is an overlay package.
5273                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5274                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5275                        mOverlays.put(pkg.mOverlayTarget,
5276                                new HashMap<String, PackageParser.Package>());
5277                    }
5278                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5279                    map.put(pkg.packageName, pkg);
5280                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5281                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5282                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5283                        return null;
5284                    }
5285                }
5286            } else if (mOverlays.containsKey(pkg.packageName) &&
5287                    !pkg.packageName.equals("android")) {
5288                // This is a regular package, with one or more known overlay packages.
5289                createIdmapsForPackageLI(pkg);
5290            }
5291        }
5292
5293        return pkg;
5294    }
5295
5296    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5297        synchronized (mPackages) {
5298            mResolverReplaced = true;
5299            // Set up information for custom user intent resolution activity.
5300            mResolveActivity.applicationInfo = pkg.applicationInfo;
5301            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5302            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5303            mResolveActivity.processName = null;
5304            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5305            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5306                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5307            mResolveActivity.theme = 0;
5308            mResolveActivity.exported = true;
5309            mResolveActivity.enabled = true;
5310            mResolveInfo.activityInfo = mResolveActivity;
5311            mResolveInfo.priority = 0;
5312            mResolveInfo.preferredOrder = 0;
5313            mResolveInfo.match = 0;
5314            mResolveComponentName = mCustomResolverComponentName;
5315            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5316                    mResolveComponentName);
5317        }
5318    }
5319
5320    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5321            PackageSetting pkgSetting) {
5322        final String apkLibPath = getApkName(pkgSetting.codePathString);
5323        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
5324        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5325        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5326    }
5327
5328    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5329            throws IOException {
5330        if (!nativeLibraryDir.isDirectory()) {
5331            nativeLibraryDir.delete();
5332
5333            if (!nativeLibraryDir.mkdir()) {
5334                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5335            }
5336
5337            try {
5338                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
5339                        | S_IXOTH);
5340            } catch (ErrnoException e) {
5341                throw new IOException("Cannot chmod native library directory "
5342                        + nativeLibraryDir.getPath(), e);
5343            }
5344        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5345            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5346        }
5347
5348        /*
5349         * If this is an internal application or our nativeLibraryPath points to
5350         * the app-lib directory, unpack the libraries if necessary.
5351         */
5352        return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
5353    }
5354
5355    private void killApplication(String pkgName, int appId, String reason) {
5356        // Request the ActivityManager to kill the process(only for existing packages)
5357        // so that we do not end up in a confused state while the user is still using the older
5358        // version of the application while the new one gets installed.
5359        IActivityManager am = ActivityManagerNative.getDefault();
5360        if (am != null) {
5361            try {
5362                am.killApplicationWithAppId(pkgName, appId, reason);
5363            } catch (RemoteException e) {
5364            }
5365        }
5366    }
5367
5368    void removePackageLI(PackageSetting ps, boolean chatty) {
5369        if (DEBUG_INSTALL) {
5370            if (chatty)
5371                Log.d(TAG, "Removing package " + ps.name);
5372        }
5373
5374        // writer
5375        synchronized (mPackages) {
5376            mPackages.remove(ps.name);
5377            if (ps.codePathString != null) {
5378                mAppDirs.remove(ps.codePathString);
5379            }
5380
5381            final PackageParser.Package pkg = ps.pkg;
5382            if (pkg != null) {
5383                cleanPackageDataStructuresLILPw(pkg, chatty);
5384            }
5385        }
5386    }
5387
5388    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5389        if (DEBUG_INSTALL) {
5390            if (chatty)
5391                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5392        }
5393
5394        // writer
5395        synchronized (mPackages) {
5396            mPackages.remove(pkg.applicationInfo.packageName);
5397            if (pkg.mPath != null) {
5398                mAppDirs.remove(pkg.mPath);
5399            }
5400            cleanPackageDataStructuresLILPw(pkg, chatty);
5401        }
5402    }
5403
5404    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5405        int N = pkg.providers.size();
5406        StringBuilder r = null;
5407        int i;
5408        for (i=0; i<N; i++) {
5409            PackageParser.Provider p = pkg.providers.get(i);
5410            mProviders.removeProvider(p);
5411            if (p.info.authority == null) {
5412
5413                /* There was another ContentProvider with this authority when
5414                 * this app was installed so this authority is null,
5415                 * Ignore it as we don't have to unregister the provider.
5416                 */
5417                continue;
5418            }
5419            String names[] = p.info.authority.split(";");
5420            for (int j = 0; j < names.length; j++) {
5421                if (mProvidersByAuthority.get(names[j]) == p) {
5422                    mProvidersByAuthority.remove(names[j]);
5423                    if (DEBUG_REMOVE) {
5424                        if (chatty)
5425                            Log.d(TAG, "Unregistered content provider: " + names[j]
5426                                    + ", className = " + p.info.name + ", isSyncable = "
5427                                    + p.info.isSyncable);
5428                    }
5429                }
5430            }
5431            if (DEBUG_REMOVE && chatty) {
5432                if (r == null) {
5433                    r = new StringBuilder(256);
5434                } else {
5435                    r.append(' ');
5436                }
5437                r.append(p.info.name);
5438            }
5439        }
5440        if (r != null) {
5441            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5442        }
5443
5444        N = pkg.services.size();
5445        r = null;
5446        for (i=0; i<N; i++) {
5447            PackageParser.Service s = pkg.services.get(i);
5448            mServices.removeService(s);
5449            if (chatty) {
5450                if (r == null) {
5451                    r = new StringBuilder(256);
5452                } else {
5453                    r.append(' ');
5454                }
5455                r.append(s.info.name);
5456            }
5457        }
5458        if (r != null) {
5459            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5460        }
5461
5462        N = pkg.receivers.size();
5463        r = null;
5464        for (i=0; i<N; i++) {
5465            PackageParser.Activity a = pkg.receivers.get(i);
5466            mReceivers.removeActivity(a, "receiver");
5467            if (DEBUG_REMOVE && chatty) {
5468                if (r == null) {
5469                    r = new StringBuilder(256);
5470                } else {
5471                    r.append(' ');
5472                }
5473                r.append(a.info.name);
5474            }
5475        }
5476        if (r != null) {
5477            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5478        }
5479
5480        N = pkg.activities.size();
5481        r = null;
5482        for (i=0; i<N; i++) {
5483            PackageParser.Activity a = pkg.activities.get(i);
5484            mActivities.removeActivity(a, "activity");
5485            if (DEBUG_REMOVE && chatty) {
5486                if (r == null) {
5487                    r = new StringBuilder(256);
5488                } else {
5489                    r.append(' ');
5490                }
5491                r.append(a.info.name);
5492            }
5493        }
5494        if (r != null) {
5495            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5496        }
5497
5498        N = pkg.permissions.size();
5499        r = null;
5500        for (i=0; i<N; i++) {
5501            PackageParser.Permission p = pkg.permissions.get(i);
5502            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5503            if (bp == null) {
5504                bp = mSettings.mPermissionTrees.get(p.info.name);
5505            }
5506            if (bp != null && bp.perm == p) {
5507                bp.perm = null;
5508                if (DEBUG_REMOVE && chatty) {
5509                    if (r == null) {
5510                        r = new StringBuilder(256);
5511                    } else {
5512                        r.append(' ');
5513                    }
5514                    r.append(p.info.name);
5515                }
5516            }
5517        }
5518        if (r != null) {
5519            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5520        }
5521
5522        N = pkg.instrumentation.size();
5523        r = null;
5524        for (i=0; i<N; i++) {
5525            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5526            mInstrumentation.remove(a.getComponentName());
5527            if (DEBUG_REMOVE && chatty) {
5528                if (r == null) {
5529                    r = new StringBuilder(256);
5530                } else {
5531                    r.append(' ');
5532                }
5533                r.append(a.info.name);
5534            }
5535        }
5536        if (r != null) {
5537            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5538        }
5539
5540        r = null;
5541        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5542            // Only system apps can hold shared libraries.
5543            if (pkg.libraryNames != null) {
5544                for (i=0; i<pkg.libraryNames.size(); i++) {
5545                    String name = pkg.libraryNames.get(i);
5546                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5547                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5548                        mSharedLibraries.remove(name);
5549                        if (DEBUG_REMOVE && chatty) {
5550                            if (r == null) {
5551                                r = new StringBuilder(256);
5552                            } else {
5553                                r.append(' ');
5554                            }
5555                            r.append(name);
5556                        }
5557                    }
5558                }
5559            }
5560        }
5561        if (r != null) {
5562            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5563        }
5564    }
5565
5566    private static final boolean isPackageFilename(String name) {
5567        return name != null && name.endsWith(".apk");
5568    }
5569
5570    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5571        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5572            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5573                return true;
5574            }
5575        }
5576        return false;
5577    }
5578
5579    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5580    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5581    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5582
5583    private void updatePermissionsLPw(String changingPkg,
5584            PackageParser.Package pkgInfo, int flags) {
5585        // Make sure there are no dangling permission trees.
5586        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5587        while (it.hasNext()) {
5588            final BasePermission bp = it.next();
5589            if (bp.packageSetting == null) {
5590                // We may not yet have parsed the package, so just see if
5591                // we still know about its settings.
5592                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5593            }
5594            if (bp.packageSetting == null) {
5595                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5596                        + " from package " + bp.sourcePackage);
5597                it.remove();
5598            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5599                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5600                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5601                            + " from package " + bp.sourcePackage);
5602                    flags |= UPDATE_PERMISSIONS_ALL;
5603                    it.remove();
5604                }
5605            }
5606        }
5607
5608        // Make sure all dynamic permissions have been assigned to a package,
5609        // and make sure there are no dangling permissions.
5610        it = mSettings.mPermissions.values().iterator();
5611        while (it.hasNext()) {
5612            final BasePermission bp = it.next();
5613            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5614                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5615                        + bp.name + " pkg=" + bp.sourcePackage
5616                        + " info=" + bp.pendingInfo);
5617                if (bp.packageSetting == null && bp.pendingInfo != null) {
5618                    final BasePermission tree = findPermissionTreeLP(bp.name);
5619                    if (tree != null && tree.perm != null) {
5620                        bp.packageSetting = tree.packageSetting;
5621                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5622                                new PermissionInfo(bp.pendingInfo));
5623                        bp.perm.info.packageName = tree.perm.info.packageName;
5624                        bp.perm.info.name = bp.name;
5625                        bp.uid = tree.uid;
5626                    }
5627                }
5628            }
5629            if (bp.packageSetting == null) {
5630                // We may not yet have parsed the package, so just see if
5631                // we still know about its settings.
5632                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5633            }
5634            if (bp.packageSetting == null) {
5635                Slog.w(TAG, "Removing dangling permission: " + bp.name
5636                        + " from package " + bp.sourcePackage);
5637                it.remove();
5638            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5639                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5640                    Slog.i(TAG, "Removing old permission: " + bp.name
5641                            + " from package " + bp.sourcePackage);
5642                    flags |= UPDATE_PERMISSIONS_ALL;
5643                    it.remove();
5644                }
5645            }
5646        }
5647
5648        // Now update the permissions for all packages, in particular
5649        // replace the granted permissions of the system packages.
5650        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5651            for (PackageParser.Package pkg : mPackages.values()) {
5652                if (pkg != pkgInfo) {
5653                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5654                }
5655            }
5656        }
5657
5658        if (pkgInfo != null) {
5659            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5660        }
5661    }
5662
5663    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5664        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5665        if (ps == null) {
5666            return;
5667        }
5668        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5669        HashSet<String> origPermissions = gp.grantedPermissions;
5670        boolean changedPermission = false;
5671
5672        if (replace) {
5673            ps.permissionsFixed = false;
5674            if (gp == ps) {
5675                origPermissions = new HashSet<String>(gp.grantedPermissions);
5676                gp.grantedPermissions.clear();
5677                gp.gids = mGlobalGids;
5678            }
5679        }
5680
5681        if (gp.gids == null) {
5682            gp.gids = mGlobalGids;
5683        }
5684
5685        final int N = pkg.requestedPermissions.size();
5686        for (int i=0; i<N; i++) {
5687            final String name = pkg.requestedPermissions.get(i);
5688            final boolean required = pkg.requestedPermissionsRequired.get(i);
5689            final BasePermission bp = mSettings.mPermissions.get(name);
5690            if (DEBUG_INSTALL) {
5691                if (gp != ps) {
5692                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5693                }
5694            }
5695
5696            if (bp == null || bp.packageSetting == null) {
5697                Slog.w(TAG, "Unknown permission " + name
5698                        + " in package " + pkg.packageName);
5699                continue;
5700            }
5701
5702            final String perm = bp.name;
5703            boolean allowed;
5704            boolean allowedSig = false;
5705            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5706            if (level == PermissionInfo.PROTECTION_NORMAL
5707                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5708                // We grant a normal or dangerous permission if any of the following
5709                // are true:
5710                // 1) The permission is required
5711                // 2) The permission is optional, but was granted in the past
5712                // 3) The permission is optional, but was requested by an
5713                //    app in /system (not /data)
5714                //
5715                // Otherwise, reject the permission.
5716                allowed = (required || origPermissions.contains(perm)
5717                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5718            } else if (bp.packageSetting == null) {
5719                // This permission is invalid; skip it.
5720                allowed = false;
5721            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5722                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5723                if (allowed) {
5724                    allowedSig = true;
5725                }
5726            } else {
5727                allowed = false;
5728            }
5729            if (DEBUG_INSTALL) {
5730                if (gp != ps) {
5731                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5732                }
5733            }
5734            if (allowed) {
5735                if (!isSystemApp(ps) && ps.permissionsFixed) {
5736                    // If this is an existing, non-system package, then
5737                    // we can't add any new permissions to it.
5738                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5739                        // Except...  if this is a permission that was added
5740                        // to the platform (note: need to only do this when
5741                        // updating the platform).
5742                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5743                    }
5744                }
5745                if (allowed) {
5746                    if (!gp.grantedPermissions.contains(perm)) {
5747                        changedPermission = true;
5748                        gp.grantedPermissions.add(perm);
5749                        gp.gids = appendInts(gp.gids, bp.gids);
5750                    } else if (!ps.haveGids) {
5751                        gp.gids = appendInts(gp.gids, bp.gids);
5752                    }
5753                } else {
5754                    Slog.w(TAG, "Not granting permission " + perm
5755                            + " to package " + pkg.packageName
5756                            + " because it was previously installed without");
5757                }
5758            } else {
5759                if (gp.grantedPermissions.remove(perm)) {
5760                    changedPermission = true;
5761                    gp.gids = removeInts(gp.gids, bp.gids);
5762                    Slog.i(TAG, "Un-granting permission " + perm
5763                            + " from package " + pkg.packageName
5764                            + " (protectionLevel=" + bp.protectionLevel
5765                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5766                            + ")");
5767                } else {
5768                    Slog.w(TAG, "Not granting permission " + perm
5769                            + " to package " + pkg.packageName
5770                            + " (protectionLevel=" + bp.protectionLevel
5771                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5772                            + ")");
5773                }
5774            }
5775        }
5776
5777        if ((changedPermission || replace) && !ps.permissionsFixed &&
5778                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
5779            // This is the first that we have heard about this package, so the
5780            // permissions we have now selected are fixed until explicitly
5781            // changed.
5782            ps.permissionsFixed = true;
5783        }
5784        ps.haveGids = true;
5785    }
5786
5787    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5788        boolean allowed = false;
5789        final int NP = PackageParser.NEW_PERMISSIONS.length;
5790        for (int ip=0; ip<NP; ip++) {
5791            final PackageParser.NewPermissionInfo npi
5792                    = PackageParser.NEW_PERMISSIONS[ip];
5793            if (npi.name.equals(perm)
5794                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5795                allowed = true;
5796                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5797                        + pkg.packageName);
5798                break;
5799            }
5800        }
5801        return allowed;
5802    }
5803
5804    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
5805                                          BasePermission bp, HashSet<String> origPermissions) {
5806        boolean allowed;
5807        allowed = (compareSignatures(
5808                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5809                        == PackageManager.SIGNATURE_MATCH)
5810                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5811                        == PackageManager.SIGNATURE_MATCH);
5812        if (!allowed && (bp.protectionLevel
5813                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5814            if (isSystemApp(pkg)) {
5815                // For updated system applications, a system permission
5816                // is granted only if it had been defined by the original application.
5817                if (isUpdatedSystemApp(pkg)) {
5818                    final PackageSetting sysPs = mSettings
5819                            .getDisabledSystemPkgLPr(pkg.packageName);
5820                    final GrantedPermissions origGp = sysPs.sharedUser != null
5821                            ? sysPs.sharedUser : sysPs;
5822
5823                    if (origGp.grantedPermissions.contains(perm)) {
5824                        // If the original was granted this permission, we take
5825                        // that grant decision as read and propagate it to the
5826                        // update.
5827                        allowed = true;
5828                    } else {
5829                        // The system apk may have been updated with an older
5830                        // version of the one on the data partition, but which
5831                        // granted a new system permission that it didn't have
5832                        // before.  In this case we do want to allow the app to
5833                        // now get the new permission if the ancestral apk is
5834                        // privileged to get it.
5835                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
5836                            for (int j=0;
5837                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
5838                                if (perm.equals(
5839                                        sysPs.pkg.requestedPermissions.get(j))) {
5840                                    allowed = true;
5841                                    break;
5842                                }
5843                            }
5844                        }
5845                    }
5846                } else {
5847                    allowed = isPrivilegedApp(pkg);
5848                }
5849            }
5850        }
5851        if (!allowed && (bp.protectionLevel
5852                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5853            // For development permissions, a development permission
5854            // is granted only if it was already granted.
5855            allowed = origPermissions.contains(perm);
5856        }
5857        return allowed;
5858    }
5859
5860    final class ActivityIntentResolver
5861            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
5862        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5863                boolean defaultOnly, int userId) {
5864            if (!sUserManager.exists(userId)) return null;
5865            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5866            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5867        }
5868
5869        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5870                int userId) {
5871            if (!sUserManager.exists(userId)) return null;
5872            mFlags = flags;
5873            return super.queryIntent(intent, resolvedType,
5874                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5875        }
5876
5877        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5878                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
5879            if (!sUserManager.exists(userId)) return null;
5880            if (packageActivities == null) {
5881                return null;
5882            }
5883            mFlags = flags;
5884            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5885            final int N = packageActivities.size();
5886            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
5887                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
5888
5889            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
5890            for (int i = 0; i < N; ++i) {
5891                intentFilters = packageActivities.get(i).intents;
5892                if (intentFilters != null && intentFilters.size() > 0) {
5893                    PackageParser.ActivityIntentInfo[] array =
5894                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
5895                    intentFilters.toArray(array);
5896                    listCut.add(array);
5897                }
5898            }
5899            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5900        }
5901
5902        public final void addActivity(PackageParser.Activity a, String type) {
5903            final boolean systemApp = isSystemApp(a.info.applicationInfo);
5904            mActivities.put(a.getComponentName(), a);
5905            if (DEBUG_SHOW_INFO)
5906                Log.v(
5907                TAG, "  " + type + " " +
5908                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
5909            if (DEBUG_SHOW_INFO)
5910                Log.v(TAG, "    Class=" + a.info.name);
5911            final int NI = a.intents.size();
5912            for (int j=0; j<NI; j++) {
5913                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5914                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
5915                    intent.setPriority(0);
5916                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5917                            + a.className + " with priority > 0, forcing to 0");
5918                }
5919                if (DEBUG_SHOW_INFO) {
5920                    Log.v(TAG, "    IntentFilter:");
5921                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5922                }
5923                if (!intent.debugCheck()) {
5924                    Log.w(TAG, "==> For Activity " + a.info.name);
5925                }
5926                addFilter(intent);
5927            }
5928        }
5929
5930        public final void removeActivity(PackageParser.Activity a, String type) {
5931            mActivities.remove(a.getComponentName());
5932            if (DEBUG_SHOW_INFO) {
5933                Log.v(TAG, "  " + type + " "
5934                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5935                                : a.info.name) + ":");
5936                Log.v(TAG, "    Class=" + a.info.name);
5937            }
5938            final int NI = a.intents.size();
5939            for (int j=0; j<NI; j++) {
5940                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5941                if (DEBUG_SHOW_INFO) {
5942                    Log.v(TAG, "    IntentFilter:");
5943                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5944                }
5945                removeFilter(intent);
5946            }
5947        }
5948
5949        @Override
5950        protected boolean allowFilterResult(
5951                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5952            ActivityInfo filterAi = filter.activity.info;
5953            for (int i=dest.size()-1; i>=0; i--) {
5954                ActivityInfo destAi = dest.get(i).activityInfo;
5955                if (destAi.name == filterAi.name
5956                        && destAi.packageName == filterAi.packageName) {
5957                    return false;
5958                }
5959            }
5960            return true;
5961        }
5962
5963        @Override
5964        protected ActivityIntentInfo[] newArray(int size) {
5965            return new ActivityIntentInfo[size];
5966        }
5967
5968        @Override
5969        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
5970            if (!sUserManager.exists(userId)) return true;
5971            PackageParser.Package p = filter.activity.owner;
5972            if (p != null) {
5973                PackageSetting ps = (PackageSetting)p.mExtras;
5974                if (ps != null) {
5975                    // System apps are never considered stopped for purposes of
5976                    // filtering, because there may be no way for the user to
5977                    // actually re-launch them.
5978                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5979                            && ps.getStopped(userId);
5980                }
5981            }
5982            return false;
5983        }
5984
5985        @Override
5986        protected boolean isPackageForFilter(String packageName,
5987                PackageParser.ActivityIntentInfo info) {
5988            return packageName.equals(info.activity.owner.packageName);
5989        }
5990
5991        @Override
5992        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
5993                int match, int userId) {
5994            if (!sUserManager.exists(userId)) return null;
5995            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
5996                return null;
5997            }
5998            final PackageParser.Activity activity = info.activity;
5999            if (mSafeMode && (activity.info.applicationInfo.flags
6000                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6001                return null;
6002            }
6003            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6004            if (ps == null) {
6005                return null;
6006            }
6007            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6008                    ps.readUserState(userId), userId);
6009            if (ai == null) {
6010                return null;
6011            }
6012            final ResolveInfo res = new ResolveInfo();
6013            res.activityInfo = ai;
6014            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6015                res.filter = info;
6016            }
6017            res.priority = info.getPriority();
6018            res.preferredOrder = activity.owner.mPreferredOrder;
6019            //System.out.println("Result: " + res.activityInfo.className +
6020            //                   " = " + res.priority);
6021            res.match = match;
6022            res.isDefault = info.hasDefault;
6023            res.labelRes = info.labelRes;
6024            res.nonLocalizedLabel = info.nonLocalizedLabel;
6025            res.icon = info.icon;
6026            res.system = isSystemApp(res.activityInfo.applicationInfo);
6027            return res;
6028        }
6029
6030        @Override
6031        protected void sortResults(List<ResolveInfo> results) {
6032            Collections.sort(results, mResolvePrioritySorter);
6033        }
6034
6035        @Override
6036        protected void dumpFilter(PrintWriter out, String prefix,
6037                PackageParser.ActivityIntentInfo filter) {
6038            out.print(prefix); out.print(
6039                    Integer.toHexString(System.identityHashCode(filter.activity)));
6040                    out.print(' ');
6041                    filter.activity.printComponentShortName(out);
6042                    out.print(" filter ");
6043                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6044        }
6045
6046//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6047//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6048//            final List<ResolveInfo> retList = Lists.newArrayList();
6049//            while (i.hasNext()) {
6050//                final ResolveInfo resolveInfo = i.next();
6051//                if (isEnabledLP(resolveInfo.activityInfo)) {
6052//                    retList.add(resolveInfo);
6053//                }
6054//            }
6055//            return retList;
6056//        }
6057
6058        // Keys are String (activity class name), values are Activity.
6059        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6060                = new HashMap<ComponentName, PackageParser.Activity>();
6061        private int mFlags;
6062    }
6063
6064    private final class ServiceIntentResolver
6065            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6066        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6067                boolean defaultOnly, int userId) {
6068            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6069            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6070        }
6071
6072        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6073                int userId) {
6074            if (!sUserManager.exists(userId)) return null;
6075            mFlags = flags;
6076            return super.queryIntent(intent, resolvedType,
6077                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6078        }
6079
6080        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6081                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6082            if (!sUserManager.exists(userId)) return null;
6083            if (packageServices == null) {
6084                return null;
6085            }
6086            mFlags = flags;
6087            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6088            final int N = packageServices.size();
6089            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6090                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6091
6092            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6093            for (int i = 0; i < N; ++i) {
6094                intentFilters = packageServices.get(i).intents;
6095                if (intentFilters != null && intentFilters.size() > 0) {
6096                    PackageParser.ServiceIntentInfo[] array =
6097                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6098                    intentFilters.toArray(array);
6099                    listCut.add(array);
6100                }
6101            }
6102            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6103        }
6104
6105        public final void addService(PackageParser.Service s) {
6106            mServices.put(s.getComponentName(), s);
6107            if (DEBUG_SHOW_INFO) {
6108                Log.v(TAG, "  "
6109                        + (s.info.nonLocalizedLabel != null
6110                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6111                Log.v(TAG, "    Class=" + s.info.name);
6112            }
6113            final int NI = s.intents.size();
6114            int j;
6115            for (j=0; j<NI; j++) {
6116                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6117                if (DEBUG_SHOW_INFO) {
6118                    Log.v(TAG, "    IntentFilter:");
6119                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6120                }
6121                if (!intent.debugCheck()) {
6122                    Log.w(TAG, "==> For Service " + s.info.name);
6123                }
6124                addFilter(intent);
6125            }
6126        }
6127
6128        public final void removeService(PackageParser.Service s) {
6129            mServices.remove(s.getComponentName());
6130            if (DEBUG_SHOW_INFO) {
6131                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6132                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6133                Log.v(TAG, "    Class=" + s.info.name);
6134            }
6135            final int NI = s.intents.size();
6136            int j;
6137            for (j=0; j<NI; j++) {
6138                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6139                if (DEBUG_SHOW_INFO) {
6140                    Log.v(TAG, "    IntentFilter:");
6141                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6142                }
6143                removeFilter(intent);
6144            }
6145        }
6146
6147        @Override
6148        protected boolean allowFilterResult(
6149                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6150            ServiceInfo filterSi = filter.service.info;
6151            for (int i=dest.size()-1; i>=0; i--) {
6152                ServiceInfo destAi = dest.get(i).serviceInfo;
6153                if (destAi.name == filterSi.name
6154                        && destAi.packageName == filterSi.packageName) {
6155                    return false;
6156                }
6157            }
6158            return true;
6159        }
6160
6161        @Override
6162        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6163            return new PackageParser.ServiceIntentInfo[size];
6164        }
6165
6166        @Override
6167        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6168            if (!sUserManager.exists(userId)) return true;
6169            PackageParser.Package p = filter.service.owner;
6170            if (p != null) {
6171                PackageSetting ps = (PackageSetting)p.mExtras;
6172                if (ps != null) {
6173                    // System apps are never considered stopped for purposes of
6174                    // filtering, because there may be no way for the user to
6175                    // actually re-launch them.
6176                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6177                            && ps.getStopped(userId);
6178                }
6179            }
6180            return false;
6181        }
6182
6183        @Override
6184        protected boolean isPackageForFilter(String packageName,
6185                PackageParser.ServiceIntentInfo info) {
6186            return packageName.equals(info.service.owner.packageName);
6187        }
6188
6189        @Override
6190        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6191                int match, int userId) {
6192            if (!sUserManager.exists(userId)) return null;
6193            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6194            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6195                return null;
6196            }
6197            final PackageParser.Service service = info.service;
6198            if (mSafeMode && (service.info.applicationInfo.flags
6199                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6200                return null;
6201            }
6202            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6203            if (ps == null) {
6204                return null;
6205            }
6206            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6207                    ps.readUserState(userId), userId);
6208            if (si == null) {
6209                return null;
6210            }
6211            final ResolveInfo res = new ResolveInfo();
6212            res.serviceInfo = si;
6213            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6214                res.filter = filter;
6215            }
6216            res.priority = info.getPriority();
6217            res.preferredOrder = service.owner.mPreferredOrder;
6218            //System.out.println("Result: " + res.activityInfo.className +
6219            //                   " = " + res.priority);
6220            res.match = match;
6221            res.isDefault = info.hasDefault;
6222            res.labelRes = info.labelRes;
6223            res.nonLocalizedLabel = info.nonLocalizedLabel;
6224            res.icon = info.icon;
6225            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6226            return res;
6227        }
6228
6229        @Override
6230        protected void sortResults(List<ResolveInfo> results) {
6231            Collections.sort(results, mResolvePrioritySorter);
6232        }
6233
6234        @Override
6235        protected void dumpFilter(PrintWriter out, String prefix,
6236                PackageParser.ServiceIntentInfo filter) {
6237            out.print(prefix); out.print(
6238                    Integer.toHexString(System.identityHashCode(filter.service)));
6239                    out.print(' ');
6240                    filter.service.printComponentShortName(out);
6241                    out.print(" filter ");
6242                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6243        }
6244
6245//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6246//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6247//            final List<ResolveInfo> retList = Lists.newArrayList();
6248//            while (i.hasNext()) {
6249//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6250//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6251//                    retList.add(resolveInfo);
6252//                }
6253//            }
6254//            return retList;
6255//        }
6256
6257        // Keys are String (activity class name), values are Activity.
6258        private final HashMap<ComponentName, PackageParser.Service> mServices
6259                = new HashMap<ComponentName, PackageParser.Service>();
6260        private int mFlags;
6261    };
6262
6263    private final class ProviderIntentResolver
6264            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6265        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6266                boolean defaultOnly, int userId) {
6267            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6268            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6269        }
6270
6271        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6272                int userId) {
6273            if (!sUserManager.exists(userId))
6274                return null;
6275            mFlags = flags;
6276            return super.queryIntent(intent, resolvedType,
6277                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6278        }
6279
6280        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6281                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6282            if (!sUserManager.exists(userId))
6283                return null;
6284            if (packageProviders == null) {
6285                return null;
6286            }
6287            mFlags = flags;
6288            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6289            final int N = packageProviders.size();
6290            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6291                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6292
6293            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6294            for (int i = 0; i < N; ++i) {
6295                intentFilters = packageProviders.get(i).intents;
6296                if (intentFilters != null && intentFilters.size() > 0) {
6297                    PackageParser.ProviderIntentInfo[] array =
6298                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6299                    intentFilters.toArray(array);
6300                    listCut.add(array);
6301                }
6302            }
6303            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6304        }
6305
6306        public final void addProvider(PackageParser.Provider p) {
6307            if (mProviders.containsKey(p.getComponentName())) {
6308                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6309                return;
6310            }
6311
6312            mProviders.put(p.getComponentName(), p);
6313            if (DEBUG_SHOW_INFO) {
6314                Log.v(TAG, "  "
6315                        + (p.info.nonLocalizedLabel != null
6316                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6317                Log.v(TAG, "    Class=" + p.info.name);
6318            }
6319            final int NI = p.intents.size();
6320            int j;
6321            for (j = 0; j < NI; j++) {
6322                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6323                if (DEBUG_SHOW_INFO) {
6324                    Log.v(TAG, "    IntentFilter:");
6325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6326                }
6327                if (!intent.debugCheck()) {
6328                    Log.w(TAG, "==> For Provider " + p.info.name);
6329                }
6330                addFilter(intent);
6331            }
6332        }
6333
6334        public final void removeProvider(PackageParser.Provider p) {
6335            mProviders.remove(p.getComponentName());
6336            if (DEBUG_SHOW_INFO) {
6337                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6338                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6339                Log.v(TAG, "    Class=" + p.info.name);
6340            }
6341            final int NI = p.intents.size();
6342            int j;
6343            for (j = 0; j < NI; j++) {
6344                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6345                if (DEBUG_SHOW_INFO) {
6346                    Log.v(TAG, "    IntentFilter:");
6347                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6348                }
6349                removeFilter(intent);
6350            }
6351        }
6352
6353        @Override
6354        protected boolean allowFilterResult(
6355                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6356            ProviderInfo filterPi = filter.provider.info;
6357            for (int i = dest.size() - 1; i >= 0; i--) {
6358                ProviderInfo destPi = dest.get(i).providerInfo;
6359                if (destPi.name == filterPi.name
6360                        && destPi.packageName == filterPi.packageName) {
6361                    return false;
6362                }
6363            }
6364            return true;
6365        }
6366
6367        @Override
6368        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6369            return new PackageParser.ProviderIntentInfo[size];
6370        }
6371
6372        @Override
6373        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6374            if (!sUserManager.exists(userId))
6375                return true;
6376            PackageParser.Package p = filter.provider.owner;
6377            if (p != null) {
6378                PackageSetting ps = (PackageSetting) p.mExtras;
6379                if (ps != null) {
6380                    // System apps are never considered stopped for purposes of
6381                    // filtering, because there may be no way for the user to
6382                    // actually re-launch them.
6383                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6384                            && ps.getStopped(userId);
6385                }
6386            }
6387            return false;
6388        }
6389
6390        @Override
6391        protected boolean isPackageForFilter(String packageName,
6392                PackageParser.ProviderIntentInfo info) {
6393            return packageName.equals(info.provider.owner.packageName);
6394        }
6395
6396        @Override
6397        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6398                int match, int userId) {
6399            if (!sUserManager.exists(userId))
6400                return null;
6401            final PackageParser.ProviderIntentInfo info = filter;
6402            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6403                return null;
6404            }
6405            final PackageParser.Provider provider = info.provider;
6406            if (mSafeMode && (provider.info.applicationInfo.flags
6407                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6408                return null;
6409            }
6410            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6411            if (ps == null) {
6412                return null;
6413            }
6414            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6415                    ps.readUserState(userId), userId);
6416            if (pi == null) {
6417                return null;
6418            }
6419            final ResolveInfo res = new ResolveInfo();
6420            res.providerInfo = pi;
6421            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6422                res.filter = filter;
6423            }
6424            res.priority = info.getPriority();
6425            res.preferredOrder = provider.owner.mPreferredOrder;
6426            res.match = match;
6427            res.isDefault = info.hasDefault;
6428            res.labelRes = info.labelRes;
6429            res.nonLocalizedLabel = info.nonLocalizedLabel;
6430            res.icon = info.icon;
6431            res.system = isSystemApp(res.providerInfo.applicationInfo);
6432            return res;
6433        }
6434
6435        @Override
6436        protected void sortResults(List<ResolveInfo> results) {
6437            Collections.sort(results, mResolvePrioritySorter);
6438        }
6439
6440        @Override
6441        protected void dumpFilter(PrintWriter out, String prefix,
6442                PackageParser.ProviderIntentInfo filter) {
6443            out.print(prefix);
6444            out.print(
6445                    Integer.toHexString(System.identityHashCode(filter.provider)));
6446            out.print(' ');
6447            filter.provider.printComponentShortName(out);
6448            out.print(" filter ");
6449            out.println(Integer.toHexString(System.identityHashCode(filter)));
6450        }
6451
6452        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6453                = new HashMap<ComponentName, PackageParser.Provider>();
6454        private int mFlags;
6455    };
6456
6457    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6458            new Comparator<ResolveInfo>() {
6459        public int compare(ResolveInfo r1, ResolveInfo r2) {
6460            int v1 = r1.priority;
6461            int v2 = r2.priority;
6462            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6463            if (v1 != v2) {
6464                return (v1 > v2) ? -1 : 1;
6465            }
6466            v1 = r1.preferredOrder;
6467            v2 = r2.preferredOrder;
6468            if (v1 != v2) {
6469                return (v1 > v2) ? -1 : 1;
6470            }
6471            if (r1.isDefault != r2.isDefault) {
6472                return r1.isDefault ? -1 : 1;
6473            }
6474            v1 = r1.match;
6475            v2 = r2.match;
6476            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6477            if (v1 != v2) {
6478                return (v1 > v2) ? -1 : 1;
6479            }
6480            if (r1.system != r2.system) {
6481                return r1.system ? -1 : 1;
6482            }
6483            return 0;
6484        }
6485    };
6486
6487    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6488            new Comparator<ProviderInfo>() {
6489        public int compare(ProviderInfo p1, ProviderInfo p2) {
6490            final int v1 = p1.initOrder;
6491            final int v2 = p2.initOrder;
6492            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6493        }
6494    };
6495
6496    static final void sendPackageBroadcast(String action, String pkg,
6497            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6498            int[] userIds) {
6499        IActivityManager am = ActivityManagerNative.getDefault();
6500        if (am != null) {
6501            try {
6502                if (userIds == null) {
6503                    userIds = am.getRunningUserIds();
6504                }
6505                for (int id : userIds) {
6506                    final Intent intent = new Intent(action,
6507                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6508                    if (extras != null) {
6509                        intent.putExtras(extras);
6510                    }
6511                    if (targetPkg != null) {
6512                        intent.setPackage(targetPkg);
6513                    }
6514                    // Modify the UID when posting to other users
6515                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6516                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6517                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6518                        intent.putExtra(Intent.EXTRA_UID, uid);
6519                    }
6520                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6521                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6522                    if (DEBUG_BROADCASTS) {
6523                        RuntimeException here = new RuntimeException("here");
6524                        here.fillInStackTrace();
6525                        Slog.d(TAG, "Sending to user " + id + ": "
6526                                + intent.toShortString(false, true, false, false)
6527                                + " " + intent.getExtras(), here);
6528                    }
6529                    am.broadcastIntent(null, intent, null, finishedReceiver,
6530                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6531                            finishedReceiver != null, false, id);
6532                }
6533            } catch (RemoteException ex) {
6534            }
6535        }
6536    }
6537
6538    /**
6539     * Check if the external storage media is available. This is true if there
6540     * is a mounted external storage medium or if the external storage is
6541     * emulated.
6542     */
6543    private boolean isExternalMediaAvailable() {
6544        return mMediaMounted || Environment.isExternalStorageEmulated();
6545    }
6546
6547    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6548        // writer
6549        synchronized (mPackages) {
6550            if (!isExternalMediaAvailable()) {
6551                // If the external storage is no longer mounted at this point,
6552                // the caller may not have been able to delete all of this
6553                // packages files and can not delete any more.  Bail.
6554                return null;
6555            }
6556            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6557            if (lastPackage != null) {
6558                pkgs.remove(lastPackage);
6559            }
6560            if (pkgs.size() > 0) {
6561                return pkgs.get(0);
6562            }
6563        }
6564        return null;
6565    }
6566
6567    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6568        if (false) {
6569            RuntimeException here = new RuntimeException("here");
6570            here.fillInStackTrace();
6571            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6572                    + " andCode=" + andCode, here);
6573        }
6574        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6575                userId, andCode ? 1 : 0, packageName));
6576    }
6577
6578    void startCleaningPackages() {
6579        // reader
6580        synchronized (mPackages) {
6581            if (!isExternalMediaAvailable()) {
6582                return;
6583            }
6584            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6585                return;
6586            }
6587        }
6588        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6589        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6590        IActivityManager am = ActivityManagerNative.getDefault();
6591        if (am != null) {
6592            try {
6593                am.startService(null, intent, null, UserHandle.USER_OWNER);
6594            } catch (RemoteException e) {
6595            }
6596        }
6597    }
6598
6599    private final class AppDirObserver extends FileObserver {
6600        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6601            super(path, mask);
6602            mRootDir = path;
6603            mIsRom = isrom;
6604            mIsPrivileged = isPrivileged;
6605        }
6606
6607        public void onEvent(int event, String path) {
6608            String removedPackage = null;
6609            int removedAppId = -1;
6610            int[] removedUsers = null;
6611            String addedPackage = null;
6612            int addedAppId = -1;
6613            int[] addedUsers = null;
6614
6615            // TODO post a message to the handler to obtain serial ordering
6616            synchronized (mInstallLock) {
6617                String fullPathStr = null;
6618                File fullPath = null;
6619                if (path != null) {
6620                    fullPath = new File(mRootDir, path);
6621                    fullPathStr = fullPath.getPath();
6622                }
6623
6624                if (DEBUG_APP_DIR_OBSERVER)
6625                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6626
6627                if (!isPackageFilename(path)) {
6628                    if (DEBUG_APP_DIR_OBSERVER)
6629                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6630                    return;
6631                }
6632
6633                // Ignore packages that are being installed or
6634                // have just been installed.
6635                if (ignoreCodePath(fullPathStr)) {
6636                    return;
6637                }
6638                PackageParser.Package p = null;
6639                PackageSetting ps = null;
6640                // reader
6641                synchronized (mPackages) {
6642                    p = mAppDirs.get(fullPathStr);
6643                    if (p != null) {
6644                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6645                        if (ps != null) {
6646                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6647                        } else {
6648                            removedUsers = sUserManager.getUserIds();
6649                        }
6650                    }
6651                    addedUsers = sUserManager.getUserIds();
6652                }
6653                if ((event&REMOVE_EVENTS) != 0) {
6654                    if (ps != null) {
6655                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6656                        removePackageLI(ps, true);
6657                        removedPackage = ps.name;
6658                        removedAppId = ps.appId;
6659                    }
6660                }
6661
6662                if ((event&ADD_EVENTS) != 0) {
6663                    if (p == null) {
6664                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6665                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6666                        if (mIsRom) {
6667                            flags |= PackageParser.PARSE_IS_SYSTEM
6668                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6669                            if (mIsPrivileged) {
6670                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6671                            }
6672                        }
6673                        p = scanPackageLI(fullPath, flags,
6674                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6675                                System.currentTimeMillis(), UserHandle.ALL);
6676                        if (p != null) {
6677                            /*
6678                             * TODO this seems dangerous as the package may have
6679                             * changed since we last acquired the mPackages
6680                             * lock.
6681                             */
6682                            // writer
6683                            synchronized (mPackages) {
6684                                updatePermissionsLPw(p.packageName, p,
6685                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6686                            }
6687                            addedPackage = p.applicationInfo.packageName;
6688                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6689                        }
6690                    }
6691                }
6692
6693                // reader
6694                synchronized (mPackages) {
6695                    mSettings.writeLPr();
6696                }
6697            }
6698
6699            if (removedPackage != null) {
6700                Bundle extras = new Bundle(1);
6701                extras.putInt(Intent.EXTRA_UID, removedAppId);
6702                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6703                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6704                        extras, null, null, removedUsers);
6705            }
6706            if (addedPackage != null) {
6707                Bundle extras = new Bundle(1);
6708                extras.putInt(Intent.EXTRA_UID, addedAppId);
6709                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6710                        extras, null, null, addedUsers);
6711            }
6712        }
6713
6714        private final String mRootDir;
6715        private final boolean mIsRom;
6716        private final boolean mIsPrivileged;
6717    }
6718
6719    /* Called when a downloaded package installation has been confirmed by the user */
6720    public void installPackage(
6721            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6722        installPackage(packageURI, observer, flags, null);
6723    }
6724
6725    /* Called when a downloaded package installation has been confirmed by the user */
6726    public void installPackage(
6727            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6728            final String installerPackageName) {
6729        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
6730                null, null);
6731    }
6732
6733    @Override
6734    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6735            int flags, String installerPackageName, Uri verificationURI,
6736            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6737        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6738                VerificationParams.NO_UID, manifestDigest);
6739        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
6740                installerPackageName, verificationParams, encryptionParams);
6741    }
6742
6743    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6744            IPackageInstallObserver observer, int flags, String installerPackageName,
6745            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6746        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6747                null);
6748
6749        final int uid = Binder.getCallingUid();
6750        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
6751            try {
6752                observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6753            } catch (RemoteException re) {
6754            }
6755            return;
6756        }
6757
6758        UserHandle user;
6759        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6760            user = UserHandle.ALL;
6761        } else {
6762            user = new UserHandle(UserHandle.getUserId(uid));
6763        }
6764
6765        final int filteredFlags;
6766
6767        if (uid == Process.SHELL_UID || uid == 0) {
6768            if (DEBUG_INSTALL) {
6769                Slog.v(TAG, "Install from ADB");
6770            }
6771            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6772        } else {
6773            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6774        }
6775
6776        verificationParams.setInstallerUid(uid);
6777
6778        final Message msg = mHandler.obtainMessage(INIT_COPY);
6779        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
6780                verificationParams, encryptionParams, user);
6781        mHandler.sendMessage(msg);
6782    }
6783
6784    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
6785        Bundle extras = new Bundle(1);
6786        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6787
6788        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6789                packageName, extras, null, null, new int[] {userId});
6790        try {
6791            IActivityManager am = ActivityManagerNative.getDefault();
6792            final boolean isSystem =
6793                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6794            if (isSystem && am.isUserRunning(userId, false)) {
6795                // The just-installed/enabled app is bundled on the system, so presumed
6796                // to be able to run automatically without needing an explicit launch.
6797                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6798                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6799                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6800                        .setPackage(packageName);
6801                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6802                        android.app.AppOpsManager.OP_NONE, false, false, userId);
6803            }
6804        } catch (RemoteException e) {
6805            // shouldn't happen
6806            Slog.w(TAG, "Unable to bootstrap installed package", e);
6807        }
6808    }
6809
6810    @Override
6811    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
6812            int userId) {
6813        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6814        PackageSetting pkgSetting;
6815        final int uid = Binder.getCallingUid();
6816        if (UserHandle.getUserId(uid) != userId) {
6817            mContext.enforceCallingOrSelfPermission(
6818                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6819                    "setApplicationBlockedSetting for user " + userId);
6820        }
6821
6822        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
6823            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
6824            return false;
6825        }
6826
6827        long callingId = Binder.clearCallingIdentity();
6828        try {
6829            boolean sendAdded = false;
6830            boolean sendRemoved = false;
6831            // writer
6832            synchronized (mPackages) {
6833                pkgSetting = mSettings.mPackages.get(packageName);
6834                if (pkgSetting == null) {
6835                    return false;
6836                }
6837                if (pkgSetting.getBlocked(userId) != blocked) {
6838                    pkgSetting.setBlocked(blocked, userId);
6839                    mSettings.writePackageRestrictionsLPr(userId);
6840                    if (blocked) {
6841                        sendRemoved = true;
6842                    } else {
6843                        sendAdded = true;
6844                    }
6845                }
6846            }
6847            if (sendAdded) {
6848                sendPackageAddedForUser(packageName, pkgSetting, userId);
6849                return true;
6850            }
6851            if (sendRemoved) {
6852                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
6853                        "blocking pkg");
6854                sendPackageBlockedForUser(packageName, pkgSetting, userId);
6855            }
6856        } finally {
6857            Binder.restoreCallingIdentity(callingId);
6858        }
6859        return false;
6860    }
6861
6862    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
6863            int userId) {
6864        final PackageRemovedInfo info = new PackageRemovedInfo();
6865        info.removedPackage = packageName;
6866        info.removedUsers = new int[] {userId};
6867        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
6868        info.sendBroadcast(false, false, false);
6869    }
6870
6871    /**
6872     * Returns true if application is not found or there was an error. Otherwise it returns
6873     * the blocked state of the package for the given user.
6874     */
6875    @Override
6876    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
6877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6878        PackageSetting pkgSetting;
6879        final int uid = Binder.getCallingUid();
6880        if (UserHandle.getUserId(uid) != userId) {
6881            mContext.enforceCallingPermission(
6882                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6883                    "getApplicationBlocked for user " + userId);
6884        }
6885        long callingId = Binder.clearCallingIdentity();
6886        try {
6887            // writer
6888            synchronized (mPackages) {
6889                pkgSetting = mSettings.mPackages.get(packageName);
6890                if (pkgSetting == null) {
6891                    return true;
6892                }
6893                return pkgSetting.getBlocked(userId);
6894            }
6895        } finally {
6896            Binder.restoreCallingIdentity(callingId);
6897        }
6898    }
6899
6900    /**
6901     * @hide
6902     */
6903    @Override
6904    public int installExistingPackageAsUser(String packageName, int userId) {
6905        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6906                null);
6907        PackageSetting pkgSetting;
6908        final int uid = Binder.getCallingUid();
6909        if (UserHandle.getUserId(uid) != userId) {
6910            mContext.enforceCallingPermission(
6911                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6912                    "installExistingPackage for user " + userId);
6913        }
6914        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
6915            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
6916        }
6917
6918        long callingId = Binder.clearCallingIdentity();
6919        try {
6920            boolean sendAdded = false;
6921            Bundle extras = new Bundle(1);
6922
6923            // writer
6924            synchronized (mPackages) {
6925                pkgSetting = mSettings.mPackages.get(packageName);
6926                if (pkgSetting == null) {
6927                    return PackageManager.INSTALL_FAILED_INVALID_URI;
6928                }
6929                if (!pkgSetting.getInstalled(userId)) {
6930                    pkgSetting.setInstalled(true, userId);
6931                    pkgSetting.setBlocked(false, userId);
6932                    mSettings.writePackageRestrictionsLPr(userId);
6933                    sendAdded = true;
6934                }
6935            }
6936
6937            if (sendAdded) {
6938                sendPackageAddedForUser(packageName, pkgSetting, userId);
6939            }
6940        } finally {
6941            Binder.restoreCallingIdentity(callingId);
6942        }
6943
6944        return PackageManager.INSTALL_SUCCEEDED;
6945    }
6946
6947    private boolean isUserRestricted(int userId, String restrictionKey) {
6948        Bundle restrictions = sUserManager.getUserRestrictions(userId);
6949        if (restrictions.getBoolean(restrictionKey, false)) {
6950            Log.w(TAG, "User is restricted: " + restrictionKey);
6951            return true;
6952        }
6953        return false;
6954    }
6955
6956    @Override
6957    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
6958        mContext.enforceCallingOrSelfPermission(
6959                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6960                "Only package verification agents can verify applications");
6961
6962        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
6963        final PackageVerificationResponse response = new PackageVerificationResponse(
6964                verificationCode, Binder.getCallingUid());
6965        msg.arg1 = id;
6966        msg.obj = response;
6967        mHandler.sendMessage(msg);
6968    }
6969
6970    @Override
6971    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
6972            long millisecondsToDelay) {
6973        mContext.enforceCallingOrSelfPermission(
6974                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6975                "Only package verification agents can extend verification timeouts");
6976
6977        final PackageVerificationState state = mPendingVerification.get(id);
6978        final PackageVerificationResponse response = new PackageVerificationResponse(
6979                verificationCodeAtTimeout, Binder.getCallingUid());
6980
6981        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
6982            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
6983        }
6984        if (millisecondsToDelay < 0) {
6985            millisecondsToDelay = 0;
6986        }
6987        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
6988                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
6989            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
6990        }
6991
6992        if ((state != null) && !state.timeoutExtended()) {
6993            state.extendTimeout();
6994
6995            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
6996            msg.arg1 = id;
6997            msg.obj = response;
6998            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
6999        }
7000    }
7001
7002    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7003            int verificationCode, UserHandle user) {
7004        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7005        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7006        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7007        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7008        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7009
7010        mContext.sendBroadcastAsUser(intent, user,
7011                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7012    }
7013
7014    private ComponentName matchComponentForVerifier(String packageName,
7015            List<ResolveInfo> receivers) {
7016        ActivityInfo targetReceiver = null;
7017
7018        final int NR = receivers.size();
7019        for (int i = 0; i < NR; i++) {
7020            final ResolveInfo info = receivers.get(i);
7021            if (info.activityInfo == null) {
7022                continue;
7023            }
7024
7025            if (packageName.equals(info.activityInfo.packageName)) {
7026                targetReceiver = info.activityInfo;
7027                break;
7028            }
7029        }
7030
7031        if (targetReceiver == null) {
7032            return null;
7033        }
7034
7035        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7036    }
7037
7038    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7039            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7040        if (pkgInfo.verifiers.length == 0) {
7041            return null;
7042        }
7043
7044        final int N = pkgInfo.verifiers.length;
7045        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7046        for (int i = 0; i < N; i++) {
7047            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7048
7049            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7050                    receivers);
7051            if (comp == null) {
7052                continue;
7053            }
7054
7055            final int verifierUid = getUidForVerifier(verifierInfo);
7056            if (verifierUid == -1) {
7057                continue;
7058            }
7059
7060            if (DEBUG_VERIFY) {
7061                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7062                        + " with the correct signature");
7063            }
7064            sufficientVerifiers.add(comp);
7065            verificationState.addSufficientVerifier(verifierUid);
7066        }
7067
7068        return sufficientVerifiers;
7069    }
7070
7071    private int getUidForVerifier(VerifierInfo verifierInfo) {
7072        synchronized (mPackages) {
7073            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7074            if (pkg == null) {
7075                return -1;
7076            } else if (pkg.mSignatures.length != 1) {
7077                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7078                        + " has more than one signature; ignoring");
7079                return -1;
7080            }
7081
7082            /*
7083             * If the public key of the package's signature does not match
7084             * our expected public key, then this is a different package and
7085             * we should skip.
7086             */
7087
7088            final byte[] expectedPublicKey;
7089            try {
7090                final Signature verifierSig = pkg.mSignatures[0];
7091                final PublicKey publicKey = verifierSig.getPublicKey();
7092                expectedPublicKey = publicKey.getEncoded();
7093            } catch (CertificateException e) {
7094                return -1;
7095            }
7096
7097            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7098
7099            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7100                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7101                        + " does not have the expected public key; ignoring");
7102                return -1;
7103            }
7104
7105            return pkg.applicationInfo.uid;
7106        }
7107    }
7108
7109    public void finishPackageInstall(int token) {
7110        enforceSystemOrRoot("Only the system is allowed to finish installs");
7111
7112        if (DEBUG_INSTALL) {
7113            Slog.v(TAG, "BM finishing package install for " + token);
7114        }
7115
7116        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7117        mHandler.sendMessage(msg);
7118    }
7119
7120    /**
7121     * Get the verification agent timeout.
7122     *
7123     * @return verification timeout in milliseconds
7124     */
7125    private long getVerificationTimeout() {
7126        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7127                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7128                DEFAULT_VERIFICATION_TIMEOUT);
7129    }
7130
7131    /**
7132     * Get the default verification agent response code.
7133     *
7134     * @return default verification response code
7135     */
7136    private int getDefaultVerificationResponse() {
7137        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7138                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7139                DEFAULT_VERIFICATION_RESPONSE);
7140    }
7141
7142    /**
7143     * Check whether or not package verification has been enabled.
7144     *
7145     * @return true if verification should be performed
7146     */
7147    private boolean isVerificationEnabled(int flags) {
7148        if (!DEFAULT_VERIFY_ENABLE) {
7149            return false;
7150        }
7151
7152        // Check if installing from ADB
7153        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7154            // Do not run verification in a test harness environment
7155            if (ActivityManager.isRunningInTestHarness()) {
7156                return false;
7157            }
7158            // Check if the developer does not want package verification for ADB installs
7159            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7160                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7161                return false;
7162            }
7163        }
7164
7165        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7166                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7167    }
7168
7169    /**
7170     * Get the "allow unknown sources" setting.
7171     *
7172     * @return the current "allow unknown sources" setting
7173     */
7174    private int getUnknownSourcesSettings() {
7175        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7176                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7177                -1);
7178    }
7179
7180    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7181        final int uid = Binder.getCallingUid();
7182        // writer
7183        synchronized (mPackages) {
7184            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7185            if (targetPackageSetting == null) {
7186                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7187            }
7188
7189            PackageSetting installerPackageSetting;
7190            if (installerPackageName != null) {
7191                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7192                if (installerPackageSetting == null) {
7193                    throw new IllegalArgumentException("Unknown installer package: "
7194                            + installerPackageName);
7195                }
7196            } else {
7197                installerPackageSetting = null;
7198            }
7199
7200            Signature[] callerSignature;
7201            Object obj = mSettings.getUserIdLPr(uid);
7202            if (obj != null) {
7203                if (obj instanceof SharedUserSetting) {
7204                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7205                } else if (obj instanceof PackageSetting) {
7206                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7207                } else {
7208                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7209                }
7210            } else {
7211                throw new SecurityException("Unknown calling uid " + uid);
7212            }
7213
7214            // Verify: can't set installerPackageName to a package that is
7215            // not signed with the same cert as the caller.
7216            if (installerPackageSetting != null) {
7217                if (compareSignatures(callerSignature,
7218                        installerPackageSetting.signatures.mSignatures)
7219                        != PackageManager.SIGNATURE_MATCH) {
7220                    throw new SecurityException(
7221                            "Caller does not have same cert as new installer package "
7222                            + installerPackageName);
7223                }
7224            }
7225
7226            // Verify: if target already has an installer package, it must
7227            // be signed with the same cert as the caller.
7228            if (targetPackageSetting.installerPackageName != null) {
7229                PackageSetting setting = mSettings.mPackages.get(
7230                        targetPackageSetting.installerPackageName);
7231                // If the currently set package isn't valid, then it's always
7232                // okay to change it.
7233                if (setting != null) {
7234                    if (compareSignatures(callerSignature,
7235                            setting.signatures.mSignatures)
7236                            != PackageManager.SIGNATURE_MATCH) {
7237                        throw new SecurityException(
7238                                "Caller does not have same cert as old installer package "
7239                                + targetPackageSetting.installerPackageName);
7240                    }
7241                }
7242            }
7243
7244            // Okay!
7245            targetPackageSetting.installerPackageName = installerPackageName;
7246            scheduleWriteSettingsLocked();
7247        }
7248    }
7249
7250    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7251        // Queue up an async operation since the package installation may take a little while.
7252        mHandler.post(new Runnable() {
7253            public void run() {
7254                mHandler.removeCallbacks(this);
7255                 // Result object to be returned
7256                PackageInstalledInfo res = new PackageInstalledInfo();
7257                res.returnCode = currentStatus;
7258                res.uid = -1;
7259                res.pkg = null;
7260                res.removedInfo = new PackageRemovedInfo();
7261                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7262                    args.doPreInstall(res.returnCode);
7263                    synchronized (mInstallLock) {
7264                        installPackageLI(args, true, res);
7265                    }
7266                    args.doPostInstall(res.returnCode, res.uid);
7267                }
7268
7269                // A restore should be performed at this point if (a) the install
7270                // succeeded, (b) the operation is not an update, and (c) the new
7271                // package has a backupAgent defined.
7272                final boolean update = res.removedInfo.removedPackage != null;
7273                boolean doRestore = (!update
7274                        && res.pkg != null
7275                        && res.pkg.applicationInfo.backupAgentName != null);
7276
7277                // Set up the post-install work request bookkeeping.  This will be used
7278                // and cleaned up by the post-install event handling regardless of whether
7279                // there's a restore pass performed.  Token values are >= 1.
7280                int token;
7281                if (mNextInstallToken < 0) mNextInstallToken = 1;
7282                token = mNextInstallToken++;
7283
7284                PostInstallData data = new PostInstallData(args, res);
7285                mRunningInstalls.put(token, data);
7286                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7287
7288                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7289                    // Pass responsibility to the Backup Manager.  It will perform a
7290                    // restore if appropriate, then pass responsibility back to the
7291                    // Package Manager to run the post-install observer callbacks
7292                    // and broadcasts.
7293                    IBackupManager bm = IBackupManager.Stub.asInterface(
7294                            ServiceManager.getService(Context.BACKUP_SERVICE));
7295                    if (bm != null) {
7296                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7297                                + " to BM for possible restore");
7298                        try {
7299                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7300                        } catch (RemoteException e) {
7301                            // can't happen; the backup manager is local
7302                        } catch (Exception e) {
7303                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7304                            doRestore = false;
7305                        }
7306                    } else {
7307                        Slog.e(TAG, "Backup Manager not found!");
7308                        doRestore = false;
7309                    }
7310                }
7311
7312                if (!doRestore) {
7313                    // No restore possible, or the Backup Manager was mysteriously not
7314                    // available -- just fire the post-install work request directly.
7315                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7316                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7317                    mHandler.sendMessage(msg);
7318                }
7319            }
7320        });
7321    }
7322
7323    private abstract class HandlerParams {
7324        private static final int MAX_RETRIES = 4;
7325
7326        /**
7327         * Number of times startCopy() has been attempted and had a non-fatal
7328         * error.
7329         */
7330        private int mRetries = 0;
7331
7332        /** User handle for the user requesting the information or installation. */
7333        private final UserHandle mUser;
7334
7335        HandlerParams(UserHandle user) {
7336            mUser = user;
7337        }
7338
7339        UserHandle getUser() {
7340            return mUser;
7341        }
7342
7343        final boolean startCopy() {
7344            boolean res;
7345            try {
7346                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7347
7348                if (++mRetries > MAX_RETRIES) {
7349                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7350                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7351                    handleServiceError();
7352                    return false;
7353                } else {
7354                    handleStartCopy();
7355                    res = true;
7356                }
7357            } catch (RemoteException e) {
7358                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7359                mHandler.sendEmptyMessage(MCS_RECONNECT);
7360                res = false;
7361            }
7362            handleReturnCode();
7363            return res;
7364        }
7365
7366        final void serviceError() {
7367            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7368            handleServiceError();
7369            handleReturnCode();
7370        }
7371
7372        abstract void handleStartCopy() throws RemoteException;
7373        abstract void handleServiceError();
7374        abstract void handleReturnCode();
7375    }
7376
7377    class MeasureParams extends HandlerParams {
7378        private final PackageStats mStats;
7379        private boolean mSuccess;
7380
7381        private final IPackageStatsObserver mObserver;
7382
7383        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7384            super(new UserHandle(stats.userHandle));
7385            mObserver = observer;
7386            mStats = stats;
7387        }
7388
7389        @Override
7390        public String toString() {
7391            return "MeasureParams{"
7392                + Integer.toHexString(System.identityHashCode(this))
7393                + " " + mStats.packageName + "}";
7394        }
7395
7396        @Override
7397        void handleStartCopy() throws RemoteException {
7398            synchronized (mInstallLock) {
7399                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7400            }
7401
7402            final boolean mounted;
7403            if (Environment.isExternalStorageEmulated()) {
7404                mounted = true;
7405            } else {
7406                final String status = Environment.getExternalStorageState();
7407                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7408                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7409            }
7410
7411            if (mounted) {
7412                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7413
7414                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7415                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7416
7417                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7418                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7419
7420                // Always subtract cache size, since it's a subdirectory
7421                mStats.externalDataSize -= mStats.externalCacheSize;
7422
7423                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7424                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7425
7426                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7427                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7428            }
7429        }
7430
7431        @Override
7432        void handleReturnCode() {
7433            if (mObserver != null) {
7434                try {
7435                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7436                } catch (RemoteException e) {
7437                    Slog.i(TAG, "Observer no longer exists.");
7438                }
7439            }
7440        }
7441
7442        @Override
7443        void handleServiceError() {
7444            Slog.e(TAG, "Could not measure application " + mStats.packageName
7445                            + " external storage");
7446        }
7447    }
7448
7449    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7450            throws RemoteException {
7451        long result = 0;
7452        for (File path : paths) {
7453            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7454        }
7455        return result;
7456    }
7457
7458    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7459        for (File path : paths) {
7460            try {
7461                mcs.clearDirectory(path.getAbsolutePath());
7462            } catch (RemoteException e) {
7463            }
7464        }
7465    }
7466
7467    class InstallParams extends HandlerParams {
7468        final IPackageInstallObserver observer;
7469        int flags;
7470
7471        private final Uri mPackageURI;
7472        final String installerPackageName;
7473        final VerificationParams verificationParams;
7474        private InstallArgs mArgs;
7475        private int mRet;
7476        private File mTempPackage;
7477        final ContainerEncryptionParams encryptionParams;
7478
7479        InstallParams(Uri packageURI,
7480                IPackageInstallObserver observer, int flags,
7481                String installerPackageName, VerificationParams verificationParams,
7482                ContainerEncryptionParams encryptionParams, UserHandle user) {
7483            super(user);
7484            this.mPackageURI = packageURI;
7485            this.flags = flags;
7486            this.observer = observer;
7487            this.installerPackageName = installerPackageName;
7488            this.verificationParams = verificationParams;
7489            this.encryptionParams = encryptionParams;
7490        }
7491
7492        @Override
7493        public String toString() {
7494            return "InstallParams{"
7495                + Integer.toHexString(System.identityHashCode(this))
7496                + " " + mPackageURI + "}";
7497        }
7498
7499        public ManifestDigest getManifestDigest() {
7500            if (verificationParams == null) {
7501                return null;
7502            }
7503            return verificationParams.getManifestDigest();
7504        }
7505
7506        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7507            String packageName = pkgLite.packageName;
7508            int installLocation = pkgLite.installLocation;
7509            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7510            // reader
7511            synchronized (mPackages) {
7512                PackageParser.Package pkg = mPackages.get(packageName);
7513                if (pkg != null) {
7514                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7515                        // Check for downgrading.
7516                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7517                            if (pkgLite.versionCode < pkg.mVersionCode) {
7518                                Slog.w(TAG, "Can't install update of " + packageName
7519                                        + " update version " + pkgLite.versionCode
7520                                        + " is older than installed version "
7521                                        + pkg.mVersionCode);
7522                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7523                            }
7524                        }
7525                        // Check for updated system application.
7526                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7527                            if (onSd) {
7528                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7529                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7530                            }
7531                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7532                        } else {
7533                            if (onSd) {
7534                                // Install flag overrides everything.
7535                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7536                            }
7537                            // If current upgrade specifies particular preference
7538                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7539                                // Application explicitly specified internal.
7540                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7541                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7542                                // App explictly prefers external. Let policy decide
7543                            } else {
7544                                // Prefer previous location
7545                                if (isExternal(pkg)) {
7546                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7547                                }
7548                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7549                            }
7550                        }
7551                    } else {
7552                        // Invalid install. Return error code
7553                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7554                    }
7555                }
7556            }
7557            // All the special cases have been taken care of.
7558            // Return result based on recommended install location.
7559            if (onSd) {
7560                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7561            }
7562            return pkgLite.recommendedInstallLocation;
7563        }
7564
7565        private long getMemoryLowThreshold() {
7566            final DeviceStorageMonitorInternal
7567                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7568            if (dsm == null) {
7569                return 0L;
7570            }
7571            return dsm.getMemoryLowThreshold();
7572        }
7573
7574        /*
7575         * Invoke remote method to get package information and install
7576         * location values. Override install location based on default
7577         * policy if needed and then create install arguments based
7578         * on the install location.
7579         */
7580        public void handleStartCopy() throws RemoteException {
7581            int ret = PackageManager.INSTALL_SUCCEEDED;
7582            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7583            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7584            PackageInfoLite pkgLite = null;
7585
7586            if (onInt && onSd) {
7587                // Check if both bits are set.
7588                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7589                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7590            } else {
7591                final long lowThreshold = getMemoryLowThreshold();
7592                if (lowThreshold == 0L) {
7593                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7594                }
7595
7596                try {
7597                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7598                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7599
7600                    final File packageFile;
7601                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7602                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7603                        if (mTempPackage != null) {
7604                            ParcelFileDescriptor out;
7605                            try {
7606                                out = ParcelFileDescriptor.open(mTempPackage,
7607                                        ParcelFileDescriptor.MODE_READ_WRITE);
7608                            } catch (FileNotFoundException e) {
7609                                out = null;
7610                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7611                            }
7612
7613                            // Make a temporary file for decryption.
7614                            ret = mContainerService
7615                                    .copyResource(mPackageURI, encryptionParams, out);
7616                            IoUtils.closeQuietly(out);
7617
7618                            packageFile = mTempPackage;
7619
7620                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7621                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7622                                            | FileUtils.S_IROTH,
7623                                    -1, -1);
7624                        } else {
7625                            packageFile = null;
7626                        }
7627                    } else {
7628                        packageFile = new File(mPackageURI.getPath());
7629                    }
7630
7631                    if (packageFile != null) {
7632                        // Remote call to find out default install location
7633                        final String packageFilePath = packageFile.getAbsolutePath();
7634                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7635                                lowThreshold);
7636
7637                        /*
7638                         * If we have too little free space, try to free cache
7639                         * before giving up.
7640                         */
7641                        if (pkgLite.recommendedInstallLocation
7642                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7643                            final long size = mContainerService.calculateInstalledSize(
7644                                    packageFilePath, isForwardLocked());
7645                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7646                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7647                                        flags, lowThreshold);
7648                            }
7649                            /*
7650                             * The cache free must have deleted the file we
7651                             * downloaded to install.
7652                             *
7653                             * TODO: fix the "freeCache" call to not delete
7654                             *       the file we care about.
7655                             */
7656                            if (pkgLite.recommendedInstallLocation
7657                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7658                                pkgLite.recommendedInstallLocation
7659                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7660                            }
7661                        }
7662                    }
7663                } finally {
7664                    mContext.revokeUriPermission(mPackageURI,
7665                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7666                }
7667            }
7668
7669            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7670                int loc = pkgLite.recommendedInstallLocation;
7671                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7672                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7673                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7674                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7675                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7676                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7677                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7678                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7679                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7680                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7681                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7682                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7683                } else {
7684                    // Override with defaults if needed.
7685                    loc = installLocationPolicy(pkgLite, flags);
7686                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7687                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7688                    } else if (!onSd && !onInt) {
7689                        // Override install location with flags
7690                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7691                            // Set the flag to install on external media.
7692                            flags |= PackageManager.INSTALL_EXTERNAL;
7693                            flags &= ~PackageManager.INSTALL_INTERNAL;
7694                        } else {
7695                            // Make sure the flag for installing on external
7696                            // media is unset
7697                            flags |= PackageManager.INSTALL_INTERNAL;
7698                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7699                        }
7700                    }
7701                }
7702            }
7703
7704            final InstallArgs args = createInstallArgs(this);
7705            mArgs = args;
7706
7707            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7708                 /*
7709                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
7710                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
7711                 */
7712                int userIdentifier = getUser().getIdentifier();
7713                if (userIdentifier == UserHandle.USER_ALL
7714                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
7715                    userIdentifier = UserHandle.USER_OWNER;
7716                }
7717
7718                /*
7719                 * Determine if we have any installed package verifiers. If we
7720                 * do, then we'll defer to them to verify the packages.
7721                 */
7722                final int requiredUid = mRequiredVerifierPackage == null ? -1
7723                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
7724                if (requiredUid != -1 && isVerificationEnabled(flags)) {
7725                    final Intent verification = new Intent(
7726                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
7727                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
7728                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7729
7730                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
7731                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
7732                            0 /* TODO: Which userId? */);
7733
7734                    if (DEBUG_VERIFY) {
7735                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
7736                                + verification.toString() + " with " + pkgLite.verifiers.length
7737                                + " optional verifiers");
7738                    }
7739
7740                    final int verificationId = mPendingVerificationToken++;
7741
7742                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7743
7744                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
7745                            installerPackageName);
7746
7747                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
7748
7749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
7750                            pkgLite.packageName);
7751
7752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
7753                            pkgLite.versionCode);
7754
7755                    if (verificationParams != null) {
7756                        if (verificationParams.getVerificationURI() != null) {
7757                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
7758                                 verificationParams.getVerificationURI());
7759                        }
7760                        if (verificationParams.getOriginatingURI() != null) {
7761                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
7762                                  verificationParams.getOriginatingURI());
7763                        }
7764                        if (verificationParams.getReferrer() != null) {
7765                            verification.putExtra(Intent.EXTRA_REFERRER,
7766                                  verificationParams.getReferrer());
7767                        }
7768                        if (verificationParams.getOriginatingUid() >= 0) {
7769                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
7770                                  verificationParams.getOriginatingUid());
7771                        }
7772                        if (verificationParams.getInstallerUid() >= 0) {
7773                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
7774                                  verificationParams.getInstallerUid());
7775                        }
7776                    }
7777
7778                    final PackageVerificationState verificationState = new PackageVerificationState(
7779                            requiredUid, args);
7780
7781                    mPendingVerification.append(verificationId, verificationState);
7782
7783                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7784                            receivers, verificationState);
7785
7786                    /*
7787                     * If any sufficient verifiers were listed in the package
7788                     * manifest, attempt to ask them.
7789                     */
7790                    if (sufficientVerifiers != null) {
7791                        final int N = sufficientVerifiers.size();
7792                        if (N == 0) {
7793                            Slog.i(TAG, "Additional verifiers required, but none installed.");
7794                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7795                        } else {
7796                            for (int i = 0; i < N; i++) {
7797                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
7798
7799                                final Intent sufficientIntent = new Intent(verification);
7800                                sufficientIntent.setComponent(verifierComponent);
7801
7802                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
7803                            }
7804                        }
7805                    }
7806
7807                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7808                            mRequiredVerifierPackage, receivers);
7809                    if (ret == PackageManager.INSTALL_SUCCEEDED
7810                            && mRequiredVerifierPackage != null) {
7811                        /*
7812                         * Send the intent to the required verification agent,
7813                         * but only start the verification timeout after the
7814                         * target BroadcastReceivers have run.
7815                         */
7816                        verification.setComponent(requiredVerifierComponent);
7817                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
7818                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7819                                new BroadcastReceiver() {
7820                                    @Override
7821                                    public void onReceive(Context context, Intent intent) {
7822                                        final Message msg = mHandler
7823                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
7824                                        msg.arg1 = verificationId;
7825                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7826                                    }
7827                                }, null, 0, null, null);
7828
7829                        /*
7830                         * We don't want the copy to proceed until verification
7831                         * succeeds, so null out this field.
7832                         */
7833                        mArgs = null;
7834                    }
7835                } else {
7836                    /*
7837                     * No package verification is enabled, so immediately start
7838                     * the remote call to initiate copy using temporary file.
7839                     */
7840                    ret = args.copyApk(mContainerService, true);
7841                }
7842            }
7843
7844            mRet = ret;
7845        }
7846
7847        @Override
7848        void handleReturnCode() {
7849            // If mArgs is null, then MCS couldn't be reached. When it
7850            // reconnects, it will try again to install. At that point, this
7851            // will succeed.
7852            if (mArgs != null) {
7853                processPendingInstall(mArgs, mRet);
7854
7855                if (mTempPackage != null) {
7856                    if (!mTempPackage.delete()) {
7857                        Slog.w(TAG, "Couldn't delete temporary file: " +
7858                                mTempPackage.getAbsolutePath());
7859                    }
7860                }
7861            }
7862        }
7863
7864        @Override
7865        void handleServiceError() {
7866            mArgs = createInstallArgs(this);
7867            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
7868        }
7869
7870        public boolean isForwardLocked() {
7871            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7872        }
7873
7874        public Uri getPackageUri() {
7875            if (mTempPackage != null) {
7876                return Uri.fromFile(mTempPackage);
7877            } else {
7878                return mPackageURI;
7879            }
7880        }
7881    }
7882
7883    /*
7884     * Utility class used in movePackage api.
7885     * srcArgs and targetArgs are not set for invalid flags and make
7886     * sure to do null checks when invoking methods on them.
7887     * We probably want to return ErrorPrams for both failed installs
7888     * and moves.
7889     */
7890    class MoveParams extends HandlerParams {
7891        final IPackageMoveObserver observer;
7892        final int flags;
7893        final String packageName;
7894        final InstallArgs srcArgs;
7895        final InstallArgs targetArgs;
7896        int uid;
7897        int mRet;
7898
7899        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
7900                String packageName, String dataDir, int uid, UserHandle user) {
7901            super(user);
7902            this.srcArgs = srcArgs;
7903            this.observer = observer;
7904            this.flags = flags;
7905            this.packageName = packageName;
7906            this.uid = uid;
7907            if (srcArgs != null) {
7908                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
7909                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
7910            } else {
7911                targetArgs = null;
7912            }
7913        }
7914
7915        @Override
7916        public String toString() {
7917            return "MoveParams{"
7918                + Integer.toHexString(System.identityHashCode(this))
7919                + " " + packageName + "}";
7920        }
7921
7922        public void handleStartCopy() throws RemoteException {
7923            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7924            // Check for storage space on target medium
7925            if (!targetArgs.checkFreeStorage(mContainerService)) {
7926                Log.w(TAG, "Insufficient storage to install");
7927                return;
7928            }
7929
7930            mRet = srcArgs.doPreCopy();
7931            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7932                return;
7933            }
7934
7935            mRet = targetArgs.copyApk(mContainerService, false);
7936            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7937                srcArgs.doPostCopy(uid);
7938                return;
7939            }
7940
7941            mRet = srcArgs.doPostCopy(uid);
7942            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7943                return;
7944            }
7945
7946            mRet = targetArgs.doPreInstall(mRet);
7947            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7948                return;
7949            }
7950
7951            if (DEBUG_SD_INSTALL) {
7952                StringBuilder builder = new StringBuilder();
7953                if (srcArgs != null) {
7954                    builder.append("src: ");
7955                    builder.append(srcArgs.getCodePath());
7956                }
7957                if (targetArgs != null) {
7958                    builder.append(" target : ");
7959                    builder.append(targetArgs.getCodePath());
7960                }
7961                Log.i(TAG, builder.toString());
7962            }
7963        }
7964
7965        @Override
7966        void handleReturnCode() {
7967            targetArgs.doPostInstall(mRet, uid);
7968            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
7969            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
7970                currentStatus = PackageManager.MOVE_SUCCEEDED;
7971            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
7972                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
7973            }
7974            processPendingMove(this, currentStatus);
7975        }
7976
7977        @Override
7978        void handleServiceError() {
7979            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
7980        }
7981    }
7982
7983    /**
7984     * Used during creation of InstallArgs
7985     *
7986     * @param flags package installation flags
7987     * @return true if should be installed on external storage
7988     */
7989    private static boolean installOnSd(int flags) {
7990        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
7991            return false;
7992        }
7993        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
7994            return true;
7995        }
7996        return false;
7997    }
7998
7999    /**
8000     * Used during creation of InstallArgs
8001     *
8002     * @param flags package installation flags
8003     * @return true if should be installed as forward locked
8004     */
8005    private static boolean installForwardLocked(int flags) {
8006        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8007    }
8008
8009    private InstallArgs createInstallArgs(InstallParams params) {
8010        if (installOnSd(params.flags) || params.isForwardLocked()) {
8011            return new AsecInstallArgs(params);
8012        } else {
8013            return new FileInstallArgs(params);
8014        }
8015    }
8016
8017    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8018            String nativeLibraryPath) {
8019        final boolean isInAsec;
8020        if (installOnSd(flags)) {
8021            /* Apps on SD card are always in ASEC containers. */
8022            isInAsec = true;
8023        } else if (installForwardLocked(flags)
8024                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8025            /*
8026             * Forward-locked apps are only in ASEC containers if they're the
8027             * new style
8028             */
8029            isInAsec = true;
8030        } else {
8031            isInAsec = false;
8032        }
8033
8034        if (isInAsec) {
8035            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8036                    installOnSd(flags), installForwardLocked(flags));
8037        } else {
8038            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
8039        }
8040    }
8041
8042    // Used by package mover
8043    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
8044        if (installOnSd(flags) || installForwardLocked(flags)) {
8045            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8046                    + AsecInstallArgs.RES_FILE_NAME);
8047            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
8048                    installForwardLocked(flags));
8049        } else {
8050            return new FileInstallArgs(packageURI, pkgName, dataDir);
8051        }
8052    }
8053
8054    static abstract class InstallArgs {
8055        final IPackageInstallObserver observer;
8056        // Always refers to PackageManager flags only
8057        final int flags;
8058        final Uri packageURI;
8059        final String installerPackageName;
8060        final ManifestDigest manifestDigest;
8061        final UserHandle user;
8062
8063        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
8064                String installerPackageName, ManifestDigest manifestDigest,
8065                UserHandle user) {
8066            this.packageURI = packageURI;
8067            this.flags = flags;
8068            this.observer = observer;
8069            this.installerPackageName = installerPackageName;
8070            this.manifestDigest = manifestDigest;
8071            this.user = user;
8072        }
8073
8074        abstract void createCopyFile();
8075        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8076        abstract int doPreInstall(int status);
8077        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8078
8079        abstract int doPostInstall(int status, int uid);
8080        abstract String getCodePath();
8081        abstract String getResourcePath();
8082        abstract String getNativeLibraryPath();
8083        // Need installer lock especially for dex file removal.
8084        abstract void cleanUpResourcesLI();
8085        abstract boolean doPostDeleteLI(boolean delete);
8086        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8087
8088        /**
8089         * Called before the source arguments are copied. This is used mostly
8090         * for MoveParams when it needs to read the source file to put it in the
8091         * destination.
8092         */
8093        int doPreCopy() {
8094            return PackageManager.INSTALL_SUCCEEDED;
8095        }
8096
8097        /**
8098         * Called after the source arguments are copied. This is used mostly for
8099         * MoveParams when it needs to read the source file to put it in the
8100         * destination.
8101         *
8102         * @return
8103         */
8104        int doPostCopy(int uid) {
8105            return PackageManager.INSTALL_SUCCEEDED;
8106        }
8107
8108        protected boolean isFwdLocked() {
8109            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8110        }
8111
8112        UserHandle getUser() {
8113            return user;
8114        }
8115    }
8116
8117    class FileInstallArgs extends InstallArgs {
8118        File installDir;
8119        String codeFileName;
8120        String resourceFileName;
8121        String libraryPath;
8122        boolean created = false;
8123
8124        FileInstallArgs(InstallParams params) {
8125            super(params.getPackageUri(), params.observer, params.flags,
8126                    params.installerPackageName, params.getManifestDigest(),
8127                    params.getUser());
8128        }
8129
8130        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
8131            super(null, null, 0, null, null, null);
8132            File codeFile = new File(fullCodePath);
8133            installDir = codeFile.getParentFile();
8134            codeFileName = fullCodePath;
8135            resourceFileName = fullResourcePath;
8136            libraryPath = nativeLibraryPath;
8137        }
8138
8139        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
8140            super(packageURI, null, 0, null, null, null);
8141            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8142            String apkName = getNextCodePath(null, pkgName, ".apk");
8143            codeFileName = new File(installDir, apkName + ".apk").getPath();
8144            resourceFileName = getResourcePathFromCodePath();
8145            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8146        }
8147
8148        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8149            final long lowThreshold;
8150
8151            final DeviceStorageMonitorInternal
8152                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8153            if (dsm == null) {
8154                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8155                lowThreshold = 0L;
8156            } else {
8157                if (dsm.isMemoryLow()) {
8158                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8159                    return false;
8160                }
8161
8162                lowThreshold = dsm.getMemoryLowThreshold();
8163            }
8164
8165            try {
8166                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8167                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8168                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8169            } finally {
8170                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8171            }
8172        }
8173
8174        String getCodePath() {
8175            return codeFileName;
8176        }
8177
8178        void createCopyFile() {
8179            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8180            codeFileName = createTempPackageFile(installDir).getPath();
8181            resourceFileName = getResourcePathFromCodePath();
8182            libraryPath = getLibraryPathFromCodePath();
8183            created = true;
8184        }
8185
8186        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8187            if (temp) {
8188                // Generate temp file name
8189                createCopyFile();
8190            }
8191            // Get a ParcelFileDescriptor to write to the output file
8192            File codeFile = new File(codeFileName);
8193            if (!created) {
8194                try {
8195                    codeFile.createNewFile();
8196                    // Set permissions
8197                    if (!setPermissions()) {
8198                        // Failed setting permissions.
8199                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8200                    }
8201                } catch (IOException e) {
8202                   Slog.w(TAG, "Failed to create file " + codeFile);
8203                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8204                }
8205            }
8206            ParcelFileDescriptor out = null;
8207            try {
8208                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8209            } catch (FileNotFoundException e) {
8210                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8211                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8212            }
8213            // Copy the resource now
8214            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8215            try {
8216                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8217                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8218                ret = imcs.copyResource(packageURI, null, out);
8219            } finally {
8220                IoUtils.closeQuietly(out);
8221                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8222            }
8223
8224            if (isFwdLocked()) {
8225                final File destResourceFile = new File(getResourcePath());
8226
8227                // Copy the public files
8228                try {
8229                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8230                } catch (IOException e) {
8231                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8232                            + " forward-locked app.");
8233                    destResourceFile.delete();
8234                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8235                }
8236            }
8237
8238            final File nativeLibraryFile = new File(getNativeLibraryPath());
8239            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8240            if (nativeLibraryFile.exists()) {
8241                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8242                nativeLibraryFile.delete();
8243            }
8244            try {
8245                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8246                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
8247                    return copyRet;
8248                }
8249            } catch (IOException e) {
8250                Slog.e(TAG, "Copying native libraries failed", e);
8251                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8252            }
8253
8254            return ret;
8255        }
8256
8257        int doPreInstall(int status) {
8258            if (status != PackageManager.INSTALL_SUCCEEDED) {
8259                cleanUp();
8260            }
8261            return status;
8262        }
8263
8264        boolean doRename(int status, final String pkgName, String oldCodePath) {
8265            if (status != PackageManager.INSTALL_SUCCEEDED) {
8266                cleanUp();
8267                return false;
8268            } else {
8269                final File oldCodeFile = new File(getCodePath());
8270                final File oldResourceFile = new File(getResourcePath());
8271                final File oldLibraryFile = new File(getNativeLibraryPath());
8272
8273                // Rename APK file based on packageName
8274                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8275                final File newCodeFile = new File(installDir, apkName + ".apk");
8276                if (!oldCodeFile.renameTo(newCodeFile)) {
8277                    return false;
8278                }
8279                codeFileName = newCodeFile.getPath();
8280
8281                // Rename public resource file if it's forward-locked.
8282                final File newResFile = new File(getResourcePathFromCodePath());
8283                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8284                    return false;
8285                }
8286                resourceFileName = newResFile.getPath();
8287
8288                // Rename library path
8289                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8290                if (newLibraryFile.exists()) {
8291                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8292                    newLibraryFile.delete();
8293                }
8294                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8295                    Slog.e(TAG, "Cannot rename native library directory "
8296                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8297                    return false;
8298                }
8299                libraryPath = newLibraryFile.getPath();
8300
8301                // Attempt to set permissions
8302                if (!setPermissions()) {
8303                    return false;
8304                }
8305
8306                if (!SELinux.restorecon(newCodeFile)) {
8307                    return false;
8308                }
8309
8310                return true;
8311            }
8312        }
8313
8314        int doPostInstall(int status, int uid) {
8315            if (status != PackageManager.INSTALL_SUCCEEDED) {
8316                cleanUp();
8317            }
8318            return status;
8319        }
8320
8321        String getResourcePath() {
8322            return resourceFileName;
8323        }
8324
8325        private String getResourcePathFromCodePath() {
8326            final String codePath = getCodePath();
8327            if (isFwdLocked()) {
8328                final StringBuilder sb = new StringBuilder();
8329
8330                sb.append(mAppInstallDir.getPath());
8331                sb.append('/');
8332                sb.append(getApkName(codePath));
8333                sb.append(".zip");
8334
8335                /*
8336                 * If our APK is a temporary file, mark the resource as a
8337                 * temporary file as well so it can be cleaned up after
8338                 * catastrophic failure.
8339                 */
8340                if (codePath.endsWith(".tmp")) {
8341                    sb.append(".tmp");
8342                }
8343
8344                return sb.toString();
8345            } else {
8346                return codePath;
8347            }
8348        }
8349
8350        private String getLibraryPathFromCodePath() {
8351            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8352        }
8353
8354        @Override
8355        String getNativeLibraryPath() {
8356            if (libraryPath == null) {
8357                libraryPath = getLibraryPathFromCodePath();
8358            }
8359            return libraryPath;
8360        }
8361
8362        private boolean cleanUp() {
8363            boolean ret = true;
8364            String sourceDir = getCodePath();
8365            String publicSourceDir = getResourcePath();
8366            if (sourceDir != null) {
8367                File sourceFile = new File(sourceDir);
8368                if (!sourceFile.exists()) {
8369                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8370                    ret = false;
8371                }
8372                // Delete application's code and resources
8373                sourceFile.delete();
8374            }
8375            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8376                final File publicSourceFile = new File(publicSourceDir);
8377                if (!publicSourceFile.exists()) {
8378                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8379                }
8380                if (publicSourceFile.exists()) {
8381                    publicSourceFile.delete();
8382                }
8383            }
8384
8385            if (libraryPath != null) {
8386                File nativeLibraryFile = new File(libraryPath);
8387                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8388                if (!nativeLibraryFile.delete()) {
8389                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8390                }
8391            }
8392
8393            return ret;
8394        }
8395
8396        void cleanUpResourcesLI() {
8397            String sourceDir = getCodePath();
8398            if (cleanUp()) {
8399                int retCode = mInstaller.rmdex(sourceDir);
8400                if (retCode < 0) {
8401                    Slog.w(TAG, "Couldn't remove dex file for package: "
8402                            +  " at location "
8403                            + sourceDir + ", retcode=" + retCode);
8404                    // we don't consider this to be a failure of the core package deletion
8405                }
8406            }
8407        }
8408
8409        private boolean setPermissions() {
8410            // TODO Do this in a more elegant way later on. for now just a hack
8411            if (!isFwdLocked()) {
8412                final int filePermissions =
8413                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8414                    |FileUtils.S_IROTH;
8415                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8416                if (retCode != 0) {
8417                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8418                            getCodePath()
8419                            + ". The return code was: " + retCode);
8420                    // TODO Define new internal error
8421                    return false;
8422                }
8423                return true;
8424            }
8425            return true;
8426        }
8427
8428        boolean doPostDeleteLI(boolean delete) {
8429            // XXX err, shouldn't we respect the delete flag?
8430            cleanUpResourcesLI();
8431            return true;
8432        }
8433    }
8434
8435    private boolean isAsecExternal(String cid) {
8436        final String asecPath = PackageHelper.getSdFilesystem(cid);
8437        return !asecPath.startsWith(mAsecInternalPath);
8438    }
8439
8440    /**
8441     * Extract the MountService "container ID" from the full code path of an
8442     * .apk.
8443     */
8444    static String cidFromCodePath(String fullCodePath) {
8445        int eidx = fullCodePath.lastIndexOf("/");
8446        String subStr1 = fullCodePath.substring(0, eidx);
8447        int sidx = subStr1.lastIndexOf("/");
8448        return subStr1.substring(sidx+1, eidx);
8449    }
8450
8451    class AsecInstallArgs extends InstallArgs {
8452        static final String RES_FILE_NAME = "pkg.apk";
8453        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8454
8455        String cid;
8456        String packagePath;
8457        String resourcePath;
8458        String libraryPath;
8459
8460        AsecInstallArgs(InstallParams params) {
8461            super(params.getPackageUri(), params.observer, params.flags,
8462                    params.installerPackageName, params.getManifestDigest(),
8463                    params.getUser());
8464        }
8465
8466        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8467                boolean isExternal, boolean isForwardLocked) {
8468            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8469                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8470                    null, null, null);
8471            // Extract cid from fullCodePath
8472            int eidx = fullCodePath.lastIndexOf("/");
8473            String subStr1 = fullCodePath.substring(0, eidx);
8474            int sidx = subStr1.lastIndexOf("/");
8475            cid = subStr1.substring(sidx+1, eidx);
8476            setCachePath(subStr1);
8477        }
8478
8479        AsecInstallArgs(String cid, boolean isForwardLocked) {
8480            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8481                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8482                    null, null, null);
8483            this.cid = cid;
8484            setCachePath(PackageHelper.getSdDir(cid));
8485        }
8486
8487        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
8488            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8489                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8490                    null, null, null);
8491            this.cid = cid;
8492        }
8493
8494        void createCopyFile() {
8495            cid = getTempContainerId();
8496        }
8497
8498        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8499            try {
8500                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8501                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8502                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8503            } finally {
8504                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8505            }
8506        }
8507
8508        private final boolean isExternal() {
8509            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8510        }
8511
8512        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8513            if (temp) {
8514                createCopyFile();
8515            } else {
8516                /*
8517                 * Pre-emptively destroy the container since it's destroyed if
8518                 * copying fails due to it existing anyway.
8519                 */
8520                PackageHelper.destroySdDir(cid);
8521            }
8522
8523            final String newCachePath;
8524            try {
8525                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8526                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8527                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8528                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8529            } finally {
8530                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8531            }
8532
8533            if (newCachePath != null) {
8534                setCachePath(newCachePath);
8535                return PackageManager.INSTALL_SUCCEEDED;
8536            } else {
8537                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8538            }
8539        }
8540
8541        @Override
8542        String getCodePath() {
8543            return packagePath;
8544        }
8545
8546        @Override
8547        String getResourcePath() {
8548            return resourcePath;
8549        }
8550
8551        @Override
8552        String getNativeLibraryPath() {
8553            return libraryPath;
8554        }
8555
8556        int doPreInstall(int status) {
8557            if (status != PackageManager.INSTALL_SUCCEEDED) {
8558                // Destroy container
8559                PackageHelper.destroySdDir(cid);
8560            } else {
8561                boolean mounted = PackageHelper.isContainerMounted(cid);
8562                if (!mounted) {
8563                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8564                            Process.SYSTEM_UID);
8565                    if (newCachePath != null) {
8566                        setCachePath(newCachePath);
8567                    } else {
8568                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8569                    }
8570                }
8571            }
8572            return status;
8573        }
8574
8575        boolean doRename(int status, final String pkgName,
8576                String oldCodePath) {
8577            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8578            String newCachePath = null;
8579            if (PackageHelper.isContainerMounted(cid)) {
8580                // Unmount the container
8581                if (!PackageHelper.unMountSdDir(cid)) {
8582                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8583                    return false;
8584                }
8585            }
8586            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8587                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8588                        " which might be stale. Will try to clean up.");
8589                // Clean up the stale container and proceed to recreate.
8590                if (!PackageHelper.destroySdDir(newCacheId)) {
8591                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8592                    return false;
8593                }
8594                // Successfully cleaned up stale container. Try to rename again.
8595                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8596                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8597                            + " inspite of cleaning it up.");
8598                    return false;
8599                }
8600            }
8601            if (!PackageHelper.isContainerMounted(newCacheId)) {
8602                Slog.w(TAG, "Mounting container " + newCacheId);
8603                newCachePath = PackageHelper.mountSdDir(newCacheId,
8604                        getEncryptKey(), Process.SYSTEM_UID);
8605            } else {
8606                newCachePath = PackageHelper.getSdDir(newCacheId);
8607            }
8608            if (newCachePath == null) {
8609                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8610                return false;
8611            }
8612            Log.i(TAG, "Succesfully renamed " + cid +
8613                    " to " + newCacheId +
8614                    " at new path: " + newCachePath);
8615            cid = newCacheId;
8616            setCachePath(newCachePath);
8617            return true;
8618        }
8619
8620        private void setCachePath(String newCachePath) {
8621            File cachePath = new File(newCachePath);
8622            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8623            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8624
8625            if (isFwdLocked()) {
8626                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8627            } else {
8628                resourcePath = packagePath;
8629            }
8630        }
8631
8632        int doPostInstall(int status, int uid) {
8633            if (status != PackageManager.INSTALL_SUCCEEDED) {
8634                cleanUp();
8635            } else {
8636                final int groupOwner;
8637                final String protectedFile;
8638                if (isFwdLocked()) {
8639                    groupOwner = UserHandle.getSharedAppGid(uid);
8640                    protectedFile = RES_FILE_NAME;
8641                } else {
8642                    groupOwner = -1;
8643                    protectedFile = null;
8644                }
8645
8646                if (uid < Process.FIRST_APPLICATION_UID
8647                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8648                    Slog.e(TAG, "Failed to finalize " + cid);
8649                    PackageHelper.destroySdDir(cid);
8650                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8651                }
8652
8653                boolean mounted = PackageHelper.isContainerMounted(cid);
8654                if (!mounted) {
8655                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8656                }
8657            }
8658            return status;
8659        }
8660
8661        private void cleanUp() {
8662            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8663
8664            // Destroy secure container
8665            PackageHelper.destroySdDir(cid);
8666        }
8667
8668        void cleanUpResourcesLI() {
8669            String sourceFile = getCodePath();
8670            // Remove dex file
8671            int retCode = mInstaller.rmdex(sourceFile);
8672            if (retCode < 0) {
8673                Slog.w(TAG, "Couldn't remove dex file for package: "
8674                        + " at location "
8675                        + sourceFile.toString() + ", retcode=" + retCode);
8676                // we don't consider this to be a failure of the core package deletion
8677            }
8678            cleanUp();
8679        }
8680
8681        boolean matchContainer(String app) {
8682            if (cid.startsWith(app)) {
8683                return true;
8684            }
8685            return false;
8686        }
8687
8688        String getPackageName() {
8689            return getAsecPackageName(cid);
8690        }
8691
8692        boolean doPostDeleteLI(boolean delete) {
8693            boolean ret = false;
8694            boolean mounted = PackageHelper.isContainerMounted(cid);
8695            if (mounted) {
8696                // Unmount first
8697                ret = PackageHelper.unMountSdDir(cid);
8698            }
8699            if (ret && delete) {
8700                cleanUpResourcesLI();
8701            }
8702            return ret;
8703        }
8704
8705        @Override
8706        int doPreCopy() {
8707            if (isFwdLocked()) {
8708                if (!PackageHelper.fixSdPermissions(cid,
8709                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
8710                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8711                }
8712            }
8713
8714            return PackageManager.INSTALL_SUCCEEDED;
8715        }
8716
8717        @Override
8718        int doPostCopy(int uid) {
8719            if (isFwdLocked()) {
8720                if (uid < Process.FIRST_APPLICATION_UID
8721                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
8722                                RES_FILE_NAME)) {
8723                    Slog.e(TAG, "Failed to finalize " + cid);
8724                    PackageHelper.destroySdDir(cid);
8725                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8726                }
8727            }
8728
8729            return PackageManager.INSTALL_SUCCEEDED;
8730        }
8731    };
8732
8733    static String getAsecPackageName(String packageCid) {
8734        int idx = packageCid.lastIndexOf("-");
8735        if (idx == -1) {
8736            return packageCid;
8737        }
8738        return packageCid.substring(0, idx);
8739    }
8740
8741    // Utility method used to create code paths based on package name and available index.
8742    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
8743        String idxStr = "";
8744        int idx = 1;
8745        // Fall back to default value of idx=1 if prefix is not
8746        // part of oldCodePath
8747        if (oldCodePath != null) {
8748            String subStr = oldCodePath;
8749            // Drop the suffix right away
8750            if (subStr.endsWith(suffix)) {
8751                subStr = subStr.substring(0, subStr.length() - suffix.length());
8752            }
8753            // If oldCodePath already contains prefix find out the
8754            // ending index to either increment or decrement.
8755            int sidx = subStr.lastIndexOf(prefix);
8756            if (sidx != -1) {
8757                subStr = subStr.substring(sidx + prefix.length());
8758                if (subStr != null) {
8759                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
8760                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
8761                    }
8762                    try {
8763                        idx = Integer.parseInt(subStr);
8764                        if (idx <= 1) {
8765                            idx++;
8766                        } else {
8767                            idx--;
8768                        }
8769                    } catch(NumberFormatException e) {
8770                    }
8771                }
8772            }
8773        }
8774        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
8775        return prefix + idxStr;
8776    }
8777
8778    // Utility method used to ignore ADD/REMOVE events
8779    // by directory observer.
8780    private static boolean ignoreCodePath(String fullPathStr) {
8781        String apkName = getApkName(fullPathStr);
8782        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8783        if (idx != -1 && ((idx+1) < apkName.length())) {
8784            // Make sure the package ends with a numeral
8785            String version = apkName.substring(idx+1);
8786            try {
8787                Integer.parseInt(version);
8788                return true;
8789            } catch (NumberFormatException e) {}
8790        }
8791        return false;
8792    }
8793
8794    // Utility method that returns the relative package path with respect
8795    // to the installation directory. Like say for /data/data/com.test-1.apk
8796    // string com.test-1 is returned.
8797    static String getApkName(String codePath) {
8798        if (codePath == null) {
8799            return null;
8800        }
8801        int sidx = codePath.lastIndexOf("/");
8802        int eidx = codePath.lastIndexOf(".");
8803        if (eidx == -1) {
8804            eidx = codePath.length();
8805        } else if (eidx == 0) {
8806            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
8807            return null;
8808        }
8809        return codePath.substring(sidx+1, eidx);
8810    }
8811
8812    class PackageInstalledInfo {
8813        String name;
8814        int uid;
8815        // The set of users that originally had this package installed.
8816        int[] origUsers;
8817        // The set of users that now have this package installed.
8818        int[] newUsers;
8819        PackageParser.Package pkg;
8820        int returnCode;
8821        PackageRemovedInfo removedInfo;
8822    }
8823
8824    /*
8825     * Install a non-existing package.
8826     */
8827    private void installNewPackageLI(PackageParser.Package pkg,
8828            int parseFlags, int scanMode, UserHandle user,
8829            String installerPackageName, PackageInstalledInfo res) {
8830        // Remember this for later, in case we need to rollback this install
8831        String pkgName = pkg.packageName;
8832
8833        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
8834        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
8835        synchronized(mPackages) {
8836            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8837                // A package with the same name is already installed, though
8838                // it has been renamed to an older name.  The package we
8839                // are trying to install should be installed as an update to
8840                // the existing one, but that has not been requested, so bail.
8841                Slog.w(TAG, "Attempt to re-install " + pkgName
8842                        + " without first uninstalling package running as "
8843                        + mSettings.mRenamedPackages.get(pkgName));
8844                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8845                return;
8846            }
8847            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
8848                // Don't allow installation over an existing package with the same name.
8849                Slog.w(TAG, "Attempt to re-install " + pkgName
8850                        + " without first uninstalling.");
8851                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8852                return;
8853            }
8854        }
8855        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8856        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
8857                System.currentTimeMillis(), user);
8858        if (newPackage == null) {
8859            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
8860            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8861                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8862            }
8863        } else {
8864            updateSettingsLI(newPackage,
8865                    installerPackageName,
8866                    null, null,
8867                    res);
8868            // delete the partially installed application. the data directory will have to be
8869            // restored if it was already existing
8870            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8871                // remove package from internal structures.  Note that we want deletePackageX to
8872                // delete the package data and cache directories that it created in
8873                // scanPackageLocked, unless those directories existed before we even tried to
8874                // install.
8875                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
8876                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
8877                                res.removedInfo, true);
8878            }
8879        }
8880    }
8881
8882    private void replacePackageLI(PackageParser.Package pkg,
8883            int parseFlags, int scanMode, UserHandle user,
8884            String installerPackageName, PackageInstalledInfo res) {
8885
8886        PackageParser.Package oldPackage;
8887        String pkgName = pkg.packageName;
8888        int[] allUsers;
8889        boolean[] perUserInstalled;
8890
8891        // First find the old package info and check signatures
8892        synchronized(mPackages) {
8893            oldPackage = mPackages.get(pkgName);
8894            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
8895            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
8896                    != PackageManager.SIGNATURE_MATCH) {
8897                Slog.w(TAG, "New package has a different signature: " + pkgName);
8898                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
8899                return;
8900            }
8901
8902            // In case of rollback, remember per-user/profile install state
8903            PackageSetting ps = mSettings.mPackages.get(pkgName);
8904            allUsers = sUserManager.getUserIds();
8905            perUserInstalled = new boolean[allUsers.length];
8906            for (int i = 0; i < allUsers.length; i++) {
8907                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
8908            }
8909        }
8910        boolean sysPkg = (isSystemApp(oldPackage));
8911        if (sysPkg) {
8912            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
8913                    user, allUsers, perUserInstalled, installerPackageName, res);
8914        } else {
8915            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
8916                    user, allUsers, perUserInstalled, installerPackageName, res);
8917        }
8918    }
8919
8920    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
8921            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
8922            int[] allUsers, boolean[] perUserInstalled,
8923            String installerPackageName, PackageInstalledInfo res) {
8924        PackageParser.Package newPackage = null;
8925        String pkgName = deletedPackage.packageName;
8926        boolean deletedPkg = true;
8927        boolean updatedSettings = false;
8928
8929        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
8930                + deletedPackage);
8931        long origUpdateTime;
8932        if (pkg.mExtras != null) {
8933            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
8934        } else {
8935            origUpdateTime = 0;
8936        }
8937
8938        // First delete the existing package while retaining the data directory
8939        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
8940                res.removedInfo, true)) {
8941            // If the existing package wasn't successfully deleted
8942            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
8943            deletedPkg = false;
8944        } else {
8945            // Successfully deleted the old package. Now proceed with re-installation
8946            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8947            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
8948                    System.currentTimeMillis(), user);
8949            if (newPackage == null) {
8950                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
8951                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8952                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8953                }
8954            } else {
8955                updateSettingsLI(newPackage,
8956                        installerPackageName,
8957                        allUsers, perUserInstalled,
8958                        res);
8959                updatedSettings = true;
8960            }
8961        }
8962
8963        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8964            // remove package from internal structures.  Note that we want deletePackageX to
8965            // delete the package data and cache directories that it created in
8966            // scanPackageLocked, unless those directories existed before we even tried to
8967            // install.
8968            if(updatedSettings) {
8969                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
8970                deletePackageLI(
8971                        pkgName, null, true, allUsers, perUserInstalled,
8972                        PackageManager.DELETE_KEEP_DATA,
8973                                res.removedInfo, true);
8974            }
8975            // Since we failed to install the new package we need to restore the old
8976            // package that we deleted.
8977            if(deletedPkg) {
8978                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
8979                File restoreFile = new File(deletedPackage.mPath);
8980                // Parse old package
8981                boolean oldOnSd = isExternal(deletedPackage);
8982                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
8983                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
8984                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
8985                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
8986                        | SCAN_UPDATE_TIME;
8987                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
8988                        origUpdateTime, null) == null) {
8989                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
8990                    return;
8991                }
8992                // Restore of old package succeeded. Update permissions.
8993                // writer
8994                synchronized (mPackages) {
8995                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
8996                            UPDATE_PERMISSIONS_ALL);
8997                    // can downgrade to reader
8998                    mSettings.writeLPr();
8999                }
9000                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9001            }
9002        }
9003    }
9004
9005    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9006            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9007            int[] allUsers, boolean[] perUserInstalled,
9008            String installerPackageName, PackageInstalledInfo res) {
9009        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9010                + ", old=" + deletedPackage);
9011        PackageParser.Package newPackage = null;
9012        boolean updatedSettings = false;
9013        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9014                PackageParser.PARSE_IS_SYSTEM;
9015        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9016            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9017        }
9018        String packageName = deletedPackage.packageName;
9019        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9020        if (packageName == null) {
9021            Slog.w(TAG, "Attempt to delete null packageName.");
9022            return;
9023        }
9024        PackageParser.Package oldPkg;
9025        PackageSetting oldPkgSetting;
9026        // reader
9027        synchronized (mPackages) {
9028            oldPkg = mPackages.get(packageName);
9029            oldPkgSetting = mSettings.mPackages.get(packageName);
9030            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9031                    (oldPkgSetting == null)) {
9032                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9033                return;
9034            }
9035        }
9036
9037        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9038
9039        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9040        res.removedInfo.removedPackage = packageName;
9041        // Remove existing system package
9042        removePackageLI(oldPkgSetting, true);
9043        // writer
9044        synchronized (mPackages) {
9045            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9046                // We didn't need to disable the .apk as a current system package,
9047                // which means we are replacing another update that is already
9048                // installed.  We need to make sure to delete the older one's .apk.
9049                res.removedInfo.args = createInstallArgs(0,
9050                        deletedPackage.applicationInfo.sourceDir,
9051                        deletedPackage.applicationInfo.publicSourceDir,
9052                        deletedPackage.applicationInfo.nativeLibraryDir);
9053            } else {
9054                res.removedInfo.args = null;
9055            }
9056        }
9057
9058        // Successfully disabled the old package. Now proceed with re-installation
9059        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9060        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9061        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9062        if (newPackage == null) {
9063            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9064            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9065                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9066            }
9067        } else {
9068            if (newPackage.mExtras != null) {
9069                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9070                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9071                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9072            }
9073            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9074            updatedSettings = true;
9075        }
9076
9077        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9078            // Re installation failed. Restore old information
9079            // Remove new pkg information
9080            if (newPackage != null) {
9081                removeInstalledPackageLI(newPackage, true);
9082            }
9083            // Add back the old system package
9084            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9085            // Restore the old system information in Settings
9086            synchronized(mPackages) {
9087                if (updatedSettings) {
9088                    mSettings.enableSystemPackageLPw(packageName);
9089                    mSettings.setInstallerPackageName(packageName,
9090                            oldPkgSetting.installerPackageName);
9091                }
9092                mSettings.writeLPr();
9093            }
9094        }
9095    }
9096
9097    // Utility method used to move dex files during install.
9098    private int moveDexFilesLI(PackageParser.Package newPackage) {
9099        int retCode;
9100        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9101            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
9102            if (retCode != 0) {
9103                if (mNoDexOpt) {
9104                    /*
9105                     * If we're in an engineering build, programs are lazily run
9106                     * through dexopt. If the .dex file doesn't exist yet, it
9107                     * will be created when the program is run next.
9108                     */
9109                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9110                } else {
9111                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9112                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9113                }
9114            }
9115        }
9116        return PackageManager.INSTALL_SUCCEEDED;
9117    }
9118
9119    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9120            int[] allUsers, boolean[] perUserInstalled,
9121            PackageInstalledInfo res) {
9122        String pkgName = newPackage.packageName;
9123        synchronized (mPackages) {
9124            //write settings. the installStatus will be incomplete at this stage.
9125            //note that the new package setting would have already been
9126            //added to mPackages. It hasn't been persisted yet.
9127            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9128            mSettings.writeLPr();
9129        }
9130
9131        if ((res.returnCode = moveDexFilesLI(newPackage))
9132                != PackageManager.INSTALL_SUCCEEDED) {
9133            // Discontinue if moving dex files failed.
9134            return;
9135        }
9136
9137        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9138
9139        synchronized (mPackages) {
9140            updatePermissionsLPw(newPackage.packageName, newPackage,
9141                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9142                            ? UPDATE_PERMISSIONS_ALL : 0));
9143            // For system-bundled packages, we assume that installing an upgraded version
9144            // of the package implies that the user actually wants to run that new code,
9145            // so we enable the package.
9146            if (isSystemApp(newPackage)) {
9147                // NB: implicit assumption that system package upgrades apply to all users
9148                if (DEBUG_INSTALL) {
9149                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9150                }
9151                PackageSetting ps = mSettings.mPackages.get(pkgName);
9152                if (ps != null) {
9153                    if (res.origUsers != null) {
9154                        for (int userHandle : res.origUsers) {
9155                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9156                                    userHandle, installerPackageName);
9157                        }
9158                    }
9159                    // Also convey the prior install/uninstall state
9160                    if (allUsers != null && perUserInstalled != null) {
9161                        for (int i = 0; i < allUsers.length; i++) {
9162                            if (DEBUG_INSTALL) {
9163                                Slog.d(TAG, "    user " + allUsers[i]
9164                                        + " => " + perUserInstalled[i]);
9165                            }
9166                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9167                        }
9168                        // these install state changes will be persisted in the
9169                        // upcoming call to mSettings.writeLPr().
9170                    }
9171                }
9172            }
9173            res.name = pkgName;
9174            res.uid = newPackage.applicationInfo.uid;
9175            res.pkg = newPackage;
9176            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9177            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9178            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9179            //to update install status
9180            mSettings.writeLPr();
9181        }
9182    }
9183
9184    private void installPackageLI(InstallArgs args,
9185            boolean newInstall, PackageInstalledInfo res) {
9186        int pFlags = args.flags;
9187        String installerPackageName = args.installerPackageName;
9188        File tmpPackageFile = new File(args.getCodePath());
9189        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9190        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9191        boolean replace = false;
9192        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9193                | (newInstall ? SCAN_NEW_INSTALL : 0);
9194        // Result object to be returned
9195        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9196
9197        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9198        // Retrieve PackageSettings and parse package
9199        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9200                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9201                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9202        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9203        pp.setSeparateProcesses(mSeparateProcesses);
9204        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9205                null, mMetrics, parseFlags);
9206        if (pkg == null) {
9207            res.returnCode = pp.getParseError();
9208            return;
9209        }
9210        String pkgName = res.name = pkg.packageName;
9211        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9212            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9213                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9214                return;
9215            }
9216        }
9217        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9218            res.returnCode = pp.getParseError();
9219            return;
9220        }
9221
9222        /* If the installer passed in a manifest digest, compare it now. */
9223        if (args.manifestDigest != null) {
9224            if (DEBUG_INSTALL) {
9225                final String parsedManifest = pkg.manifestDigest == null ? "null"
9226                        : pkg.manifestDigest.toString();
9227                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9228                        + parsedManifest);
9229            }
9230
9231            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9232                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9233                return;
9234            }
9235        } else if (DEBUG_INSTALL) {
9236            final String parsedManifest = pkg.manifestDigest == null
9237                    ? "null" : pkg.manifestDigest.toString();
9238            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9239        }
9240
9241        // Get rid of all references to package scan path via parser.
9242        pp = null;
9243        String oldCodePath = null;
9244        boolean systemApp = false;
9245        synchronized (mPackages) {
9246            // Check if installing already existing package
9247            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9248                String oldName = mSettings.mRenamedPackages.get(pkgName);
9249                if (pkg.mOriginalPackages != null
9250                        && pkg.mOriginalPackages.contains(oldName)
9251                        && mPackages.containsKey(oldName)) {
9252                    // This package is derived from an original package,
9253                    // and this device has been updating from that original
9254                    // name.  We must continue using the original name, so
9255                    // rename the new package here.
9256                    pkg.setPackageName(oldName);
9257                    pkgName = pkg.packageName;
9258                    replace = true;
9259                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9260                            + oldName + " pkgName=" + pkgName);
9261                } else if (mPackages.containsKey(pkgName)) {
9262                    // This package, under its official name, already exists
9263                    // on the device; we should replace it.
9264                    replace = true;
9265                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9266                }
9267            }
9268            PackageSetting ps = mSettings.mPackages.get(pkgName);
9269            if (ps != null) {
9270                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9271                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9272                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9273                    systemApp = (ps.pkg.applicationInfo.flags &
9274                            ApplicationInfo.FLAG_SYSTEM) != 0;
9275                }
9276                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9277            }
9278        }
9279
9280        if (systemApp && onSd) {
9281            // Disable updates to system apps on sdcard
9282            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9283            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9284            return;
9285        }
9286
9287        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9288            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9289            return;
9290        }
9291        // Set application objects path explicitly after the rename
9292        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9293        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9294        if (replace) {
9295            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9296                    installerPackageName, res);
9297        } else {
9298            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9299                    installerPackageName, res);
9300        }
9301        synchronized (mPackages) {
9302            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9303            if (ps != null) {
9304                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9305            }
9306        }
9307    }
9308
9309    private static boolean isForwardLocked(PackageParser.Package pkg) {
9310        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9311    }
9312
9313
9314    private boolean isForwardLocked(PackageSetting ps) {
9315        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9316    }
9317
9318    private static boolean isExternal(PackageParser.Package pkg) {
9319        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9320    }
9321
9322    private static boolean isExternal(PackageSetting ps) {
9323        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9324    }
9325
9326    private static boolean isSystemApp(PackageParser.Package pkg) {
9327        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9328    }
9329
9330    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9331        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9332    }
9333
9334    private static boolean isSystemApp(ApplicationInfo info) {
9335        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9336    }
9337
9338    private static boolean isSystemApp(PackageSetting ps) {
9339        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9340    }
9341
9342    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9343        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9344    }
9345
9346    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9347        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9348    }
9349
9350    private int packageFlagsToInstallFlags(PackageSetting ps) {
9351        int installFlags = 0;
9352        if (isExternal(ps)) {
9353            installFlags |= PackageManager.INSTALL_EXTERNAL;
9354        }
9355        if (isForwardLocked(ps)) {
9356            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9357        }
9358        return installFlags;
9359    }
9360
9361    private void deleteTempPackageFiles() {
9362        final FilenameFilter filter = new FilenameFilter() {
9363            public boolean accept(File dir, String name) {
9364                return name.startsWith("vmdl") && name.endsWith(".tmp");
9365            }
9366        };
9367        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9368        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9369    }
9370
9371    private static final void deleteTempPackageFilesInDirectory(File directory,
9372            FilenameFilter filter) {
9373        final String[] tmpFilesList = directory.list(filter);
9374        if (tmpFilesList == null) {
9375            return;
9376        }
9377        for (int i = 0; i < tmpFilesList.length; i++) {
9378            final File tmpFile = new File(directory, tmpFilesList[i]);
9379            tmpFile.delete();
9380        }
9381    }
9382
9383    private File createTempPackageFile(File installDir) {
9384        File tmpPackageFile;
9385        try {
9386            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9387        } catch (IOException e) {
9388            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9389            return null;
9390        }
9391        try {
9392            FileUtils.setPermissions(
9393                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9394                    -1, -1);
9395            if (!SELinux.restorecon(tmpPackageFile)) {
9396                return null;
9397            }
9398        } catch (IOException e) {
9399            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9400            return null;
9401        }
9402        return tmpPackageFile;
9403    }
9404
9405    @Override
9406    public void deletePackageAsUser(final String packageName,
9407                                    final IPackageDeleteObserver observer,
9408                                    final int userId, final int flags) {
9409        mContext.enforceCallingOrSelfPermission(
9410                android.Manifest.permission.DELETE_PACKAGES, null);
9411        final int uid = Binder.getCallingUid();
9412        if (UserHandle.getUserId(uid) != userId) {
9413            mContext.enforceCallingPermission(
9414                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9415                    "deletePackage for user " + userId);
9416        }
9417        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9418            try {
9419                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9420            } catch (RemoteException re) {
9421            }
9422            return;
9423        }
9424
9425        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9426        // Queue up an async operation since the package deletion may take a little while.
9427        mHandler.post(new Runnable() {
9428            public void run() {
9429                mHandler.removeCallbacks(this);
9430                final int returnCode = deletePackageX(packageName, userId, flags);
9431                if (observer != null) {
9432                    try {
9433                        observer.packageDeleted(packageName, returnCode);
9434                    } catch (RemoteException e) {
9435                        Log.i(TAG, "Observer no longer exists.");
9436                    } //end catch
9437                } //end if
9438            } //end run
9439        });
9440    }
9441
9442    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9443        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9444                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9445        try {
9446            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9447                    || dpm.isDeviceOwner(packageName))) {
9448                return true;
9449            }
9450        } catch (RemoteException e) {
9451        }
9452        return false;
9453    }
9454
9455    /**
9456     *  This method is an internal method that could be get invoked either
9457     *  to delete an installed package or to clean up a failed installation.
9458     *  After deleting an installed package, a broadcast is sent to notify any
9459     *  listeners that the package has been installed. For cleaning up a failed
9460     *  installation, the broadcast is not necessary since the package's
9461     *  installation wouldn't have sent the initial broadcast either
9462     *  The key steps in deleting a package are
9463     *  deleting the package information in internal structures like mPackages,
9464     *  deleting the packages base directories through installd
9465     *  updating mSettings to reflect current status
9466     *  persisting settings for later use
9467     *  sending a broadcast if necessary
9468     */
9469    private int deletePackageX(String packageName, int userId, int flags) {
9470        final PackageRemovedInfo info = new PackageRemovedInfo();
9471        final boolean res;
9472
9473        if (isPackageDeviceAdmin(packageName, userId)) {
9474            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9475            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9476        }
9477
9478        boolean removedForAllUsers = false;
9479        boolean systemUpdate = false;
9480
9481        // for the uninstall-updates case and restricted profiles, remember the per-
9482        // userhandle installed state
9483        int[] allUsers;
9484        boolean[] perUserInstalled;
9485        synchronized (mPackages) {
9486            PackageSetting ps = mSettings.mPackages.get(packageName);
9487            allUsers = sUserManager.getUserIds();
9488            perUserInstalled = new boolean[allUsers.length];
9489            for (int i = 0; i < allUsers.length; i++) {
9490                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9491            }
9492        }
9493
9494        synchronized (mInstallLock) {
9495            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9496            res = deletePackageLI(packageName,
9497                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9498                            ? UserHandle.ALL : new UserHandle(userId),
9499                    true, allUsers, perUserInstalled,
9500                    flags | REMOVE_CHATTY, info, true);
9501            systemUpdate = info.isRemovedPackageSystemUpdate;
9502            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9503                removedForAllUsers = true;
9504            }
9505            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9506                    + " removedForAllUsers=" + removedForAllUsers);
9507        }
9508
9509        if (res) {
9510            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9511
9512            // If the removed package was a system update, the old system package
9513            // was re-enabled; we need to broadcast this information
9514            if (systemUpdate) {
9515                Bundle extras = new Bundle(1);
9516                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9517                        ? info.removedAppId : info.uid);
9518                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9519
9520                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9521                        extras, null, null, null);
9522                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9523                        extras, null, null, null);
9524                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9525                        null, packageName, null, null);
9526            }
9527        }
9528        // Force a gc here.
9529        Runtime.getRuntime().gc();
9530        // Delete the resources here after sending the broadcast to let
9531        // other processes clean up before deleting resources.
9532        if (info.args != null) {
9533            synchronized (mInstallLock) {
9534                info.args.doPostDeleteLI(true);
9535            }
9536        }
9537
9538        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9539    }
9540
9541    static class PackageRemovedInfo {
9542        String removedPackage;
9543        int uid = -1;
9544        int removedAppId = -1;
9545        int[] removedUsers = null;
9546        boolean isRemovedPackageSystemUpdate = false;
9547        // Clean up resources deleted packages.
9548        InstallArgs args = null;
9549
9550        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9551            Bundle extras = new Bundle(1);
9552            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9553            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9554            if (replacing) {
9555                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9556            }
9557            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9558            if (removedPackage != null) {
9559                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9560                        extras, null, null, removedUsers);
9561                if (fullRemove && !replacing) {
9562                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9563                            extras, null, null, removedUsers);
9564                }
9565            }
9566            if (removedAppId >= 0) {
9567                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9568                        removedUsers);
9569            }
9570        }
9571    }
9572
9573    /*
9574     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9575     * flag is not set, the data directory is removed as well.
9576     * make sure this flag is set for partially installed apps. If not its meaningless to
9577     * delete a partially installed application.
9578     */
9579    private void removePackageDataLI(PackageSetting ps,
9580            int[] allUserHandles, boolean[] perUserInstalled,
9581            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9582        String packageName = ps.name;
9583        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9584        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9585        // Retrieve object to delete permissions for shared user later on
9586        final PackageSetting deletedPs;
9587        // reader
9588        synchronized (mPackages) {
9589            deletedPs = mSettings.mPackages.get(packageName);
9590            if (outInfo != null) {
9591                outInfo.removedPackage = packageName;
9592                outInfo.removedUsers = deletedPs != null
9593                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9594                        : null;
9595            }
9596        }
9597        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9598            removeDataDirsLI(packageName);
9599            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9600        }
9601        // writer
9602        synchronized (mPackages) {
9603            if (deletedPs != null) {
9604                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9605                    if (outInfo != null) {
9606                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9607                    }
9608                    if (deletedPs != null) {
9609                        updatePermissionsLPw(deletedPs.name, null, 0);
9610                        if (deletedPs.sharedUser != null) {
9611                            // remove permissions associated with package
9612                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9613                        }
9614                    }
9615                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9616                }
9617                // make sure to preserve per-user disabled state if this removal was just
9618                // a downgrade of a system app to the factory package
9619                if (allUserHandles != null && perUserInstalled != null) {
9620                    if (DEBUG_REMOVE) {
9621                        Slog.d(TAG, "Propagating install state across downgrade");
9622                    }
9623                    for (int i = 0; i < allUserHandles.length; i++) {
9624                        if (DEBUG_REMOVE) {
9625                            Slog.d(TAG, "    user " + allUserHandles[i]
9626                                    + " => " + perUserInstalled[i]);
9627                        }
9628                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9629                    }
9630                }
9631            }
9632            // can downgrade to reader
9633            if (writeSettings) {
9634                // Save settings now
9635                mSettings.writeLPr();
9636            }
9637        }
9638        if (outInfo != null) {
9639            // A user ID was deleted here. Go through all users and remove it
9640            // from KeyStore.
9641            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9642        }
9643    }
9644
9645    static boolean locationIsPrivileged(File path) {
9646        try {
9647            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9648                    .getCanonicalPath();
9649            return path.getCanonicalPath().startsWith(privilegedAppDir);
9650        } catch (IOException e) {
9651            Slog.e(TAG, "Unable to access code path " + path);
9652        }
9653        return false;
9654    }
9655
9656    /*
9657     * Tries to delete system package.
9658     */
9659    private boolean deleteSystemPackageLI(PackageSetting newPs,
9660            int[] allUserHandles, boolean[] perUserInstalled,
9661            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
9662        final boolean applyUserRestrictions
9663                = (allUserHandles != null) && (perUserInstalled != null);
9664        PackageSetting disabledPs = null;
9665        // Confirm if the system package has been updated
9666        // An updated system app can be deleted. This will also have to restore
9667        // the system pkg from system partition
9668        // reader
9669        synchronized (mPackages) {
9670            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
9671        }
9672        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
9673                + " disabledPs=" + disabledPs);
9674        if (disabledPs == null) {
9675            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
9676            return false;
9677        } else if (DEBUG_REMOVE) {
9678            Slog.d(TAG, "Deleting system pkg from data partition");
9679        }
9680        if (DEBUG_REMOVE) {
9681            if (applyUserRestrictions) {
9682                Slog.d(TAG, "Remembering install states:");
9683                for (int i = 0; i < allUserHandles.length; i++) {
9684                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
9685                }
9686            }
9687        }
9688        // Delete the updated package
9689        outInfo.isRemovedPackageSystemUpdate = true;
9690        if (disabledPs.versionCode < newPs.versionCode) {
9691            // Delete data for downgrades
9692            flags &= ~PackageManager.DELETE_KEEP_DATA;
9693        } else {
9694            // Preserve data by setting flag
9695            flags |= PackageManager.DELETE_KEEP_DATA;
9696        }
9697        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
9698                allUserHandles, perUserInstalled, outInfo, writeSettings);
9699        if (!ret) {
9700            return false;
9701        }
9702        // writer
9703        synchronized (mPackages) {
9704            // Reinstate the old system package
9705            mSettings.enableSystemPackageLPw(newPs.name);
9706            // Remove any native libraries from the upgraded package.
9707            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
9708        }
9709        // Install the system package
9710        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
9711        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
9712        if (locationIsPrivileged(disabledPs.codePath)) {
9713            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9714        }
9715        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
9716                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
9717
9718        if (newPkg == null) {
9719            Slog.w(TAG, "Failed to restore system package:" + newPs.name
9720                    + " with error:" + mLastScanError);
9721            return false;
9722        }
9723        // writer
9724        synchronized (mPackages) {
9725            updatePermissionsLPw(newPkg.packageName, newPkg,
9726                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
9727            if (applyUserRestrictions) {
9728                if (DEBUG_REMOVE) {
9729                    Slog.d(TAG, "Propagating install state across reinstall");
9730                }
9731                PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
9732                for (int i = 0; i < allUserHandles.length; i++) {
9733                    if (DEBUG_REMOVE) {
9734                        Slog.d(TAG, "    user " + allUserHandles[i]
9735                                + " => " + perUserInstalled[i]);
9736                    }
9737                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9738                }
9739                // Regardless of writeSettings we need to ensure that this restriction
9740                // state propagation is persisted
9741                mSettings.writeAllUsersPackageRestrictionsLPr();
9742            }
9743            // can downgrade to reader here
9744            if (writeSettings) {
9745                mSettings.writeLPr();
9746            }
9747        }
9748        return true;
9749    }
9750
9751    private boolean deleteInstalledPackageLI(PackageSetting ps,
9752            boolean deleteCodeAndResources, int flags,
9753            int[] allUserHandles, boolean[] perUserInstalled,
9754            PackageRemovedInfo outInfo, boolean writeSettings) {
9755        if (outInfo != null) {
9756            outInfo.uid = ps.appId;
9757        }
9758
9759        // Delete package data from internal structures and also remove data if flag is set
9760        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
9761
9762        // Delete application code and resources
9763        if (deleteCodeAndResources && (outInfo != null)) {
9764            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
9765                    ps.resourcePathString, ps.nativeLibraryPathString);
9766        }
9767        return true;
9768    }
9769
9770    /*
9771     * This method handles package deletion in general
9772     */
9773    private boolean deletePackageLI(String packageName, UserHandle user,
9774            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
9775            int flags, PackageRemovedInfo outInfo,
9776            boolean writeSettings) {
9777        if (packageName == null) {
9778            Slog.w(TAG, "Attempt to delete null packageName.");
9779            return false;
9780        }
9781        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
9782        PackageSetting ps;
9783        boolean dataOnly = false;
9784        int removeUser = -1;
9785        int appId = -1;
9786        synchronized (mPackages) {
9787            ps = mSettings.mPackages.get(packageName);
9788            if (ps == null) {
9789                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9790                return false;
9791            }
9792            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
9793                    && user.getIdentifier() != UserHandle.USER_ALL) {
9794                // The caller is asking that the package only be deleted for a single
9795                // user.  To do this, we just mark its uninstalled state and delete
9796                // its data.  If this is a system app, we only allow this to happen if
9797                // they have set the special DELETE_SYSTEM_APP which requests different
9798                // semantics than normal for uninstalling system apps.
9799                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
9800                ps.setUserState(user.getIdentifier(),
9801                        COMPONENT_ENABLED_STATE_DEFAULT,
9802                        false, //installed
9803                        true,  //stopped
9804                        true,  //notLaunched
9805                        false, //blocked
9806                        null, null, null);
9807                if (!isSystemApp(ps)) {
9808                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
9809                        // Other user still have this package installed, so all
9810                        // we need to do is clear this user's data and save that
9811                        // it is uninstalled.
9812                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
9813                        removeUser = user.getIdentifier();
9814                        appId = ps.appId;
9815                        mSettings.writePackageRestrictionsLPr(removeUser);
9816                    } else {
9817                        // We need to set it back to 'installed' so the uninstall
9818                        // broadcasts will be sent correctly.
9819                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
9820                        ps.setInstalled(true, user.getIdentifier());
9821                    }
9822                } else {
9823                    // This is a system app, so we assume that the
9824                    // other users still have this package installed, so all
9825                    // we need to do is clear this user's data and save that
9826                    // it is uninstalled.
9827                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
9828                    removeUser = user.getIdentifier();
9829                    appId = ps.appId;
9830                    mSettings.writePackageRestrictionsLPr(removeUser);
9831                }
9832            }
9833        }
9834
9835        if (removeUser >= 0) {
9836            // From above, we determined that we are deleting this only
9837            // for a single user.  Continue the work here.
9838            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
9839            if (outInfo != null) {
9840                outInfo.removedPackage = packageName;
9841                outInfo.removedAppId = appId;
9842                outInfo.removedUsers = new int[] {removeUser};
9843            }
9844            mInstaller.clearUserData(packageName, removeUser);
9845            removeKeystoreDataIfNeeded(removeUser, appId);
9846            schedulePackageCleaning(packageName, removeUser, false);
9847            return true;
9848        }
9849
9850        if (dataOnly) {
9851            // Delete application data first
9852            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
9853            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
9854            return true;
9855        }
9856
9857        boolean ret = false;
9858        mSettings.mKeySetManager.removeAppKeySetData(packageName);
9859        if (isSystemApp(ps)) {
9860            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
9861            // When an updated system application is deleted we delete the existing resources as well and
9862            // fall back to existing code in system partition
9863            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
9864                    flags, outInfo, writeSettings);
9865        } else {
9866            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
9867            // Kill application pre-emptively especially for apps on sd.
9868            killApplication(packageName, ps.appId, "uninstall pkg");
9869            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
9870                    allUserHandles, perUserInstalled,
9871                    outInfo, writeSettings);
9872        }
9873
9874        return ret;
9875    }
9876
9877    private final class ClearStorageConnection implements ServiceConnection {
9878        IMediaContainerService mContainerService;
9879
9880        @Override
9881        public void onServiceConnected(ComponentName name, IBinder service) {
9882            synchronized (this) {
9883                mContainerService = IMediaContainerService.Stub.asInterface(service);
9884                notifyAll();
9885            }
9886        }
9887
9888        @Override
9889        public void onServiceDisconnected(ComponentName name) {
9890        }
9891    }
9892
9893    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
9894        final boolean mounted;
9895        if (Environment.isExternalStorageEmulated()) {
9896            mounted = true;
9897        } else {
9898            final String status = Environment.getExternalStorageState();
9899
9900            mounted = status.equals(Environment.MEDIA_MOUNTED)
9901                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
9902        }
9903
9904        if (!mounted) {
9905            return;
9906        }
9907
9908        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
9909        int[] users;
9910        if (userId == UserHandle.USER_ALL) {
9911            users = sUserManager.getUserIds();
9912        } else {
9913            users = new int[] { userId };
9914        }
9915        final ClearStorageConnection conn = new ClearStorageConnection();
9916        if (mContext.bindServiceAsUser(
9917                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
9918            try {
9919                for (int curUser : users) {
9920                    long timeout = SystemClock.uptimeMillis() + 5000;
9921                    synchronized (conn) {
9922                        long now = SystemClock.uptimeMillis();
9923                        while (conn.mContainerService == null && now < timeout) {
9924                            try {
9925                                conn.wait(timeout - now);
9926                            } catch (InterruptedException e) {
9927                            }
9928                        }
9929                    }
9930                    if (conn.mContainerService == null) {
9931                        return;
9932                    }
9933
9934                    final UserEnvironment userEnv = new UserEnvironment(curUser);
9935                    clearDirectory(conn.mContainerService,
9936                            userEnv.buildExternalStorageAppCacheDirs(packageName));
9937                    if (allData) {
9938                        clearDirectory(conn.mContainerService,
9939                                userEnv.buildExternalStorageAppDataDirs(packageName));
9940                        clearDirectory(conn.mContainerService,
9941                                userEnv.buildExternalStorageAppMediaDirs(packageName));
9942                    }
9943                }
9944            } finally {
9945                mContext.unbindService(conn);
9946            }
9947        }
9948    }
9949
9950    @Override
9951    public void clearApplicationUserData(final String packageName,
9952            final IPackageDataObserver observer, final int userId) {
9953        mContext.enforceCallingOrSelfPermission(
9954                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
9955        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
9956        // Queue up an async operation since the package deletion may take a little while.
9957        mHandler.post(new Runnable() {
9958            public void run() {
9959                mHandler.removeCallbacks(this);
9960                final boolean succeeded;
9961                synchronized (mInstallLock) {
9962                    succeeded = clearApplicationUserDataLI(packageName, userId);
9963                }
9964                clearExternalStorageDataSync(packageName, userId, true);
9965                if (succeeded) {
9966                    // invoke DeviceStorageMonitor's update method to clear any notifications
9967                    DeviceStorageMonitorInternal
9968                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9969                    if (dsm != null) {
9970                        dsm.checkMemory();
9971                    }
9972                }
9973                if(observer != null) {
9974                    try {
9975                        observer.onRemoveCompleted(packageName, succeeded);
9976                    } catch (RemoteException e) {
9977                        Log.i(TAG, "Observer no longer exists.");
9978                    }
9979                } //end if observer
9980            } //end run
9981        });
9982    }
9983
9984    private boolean clearApplicationUserDataLI(String packageName, int userId) {
9985        if (packageName == null) {
9986            Slog.w(TAG, "Attempt to delete null packageName.");
9987            return false;
9988        }
9989        PackageParser.Package p;
9990        boolean dataOnly = false;
9991        final int appId;
9992        synchronized (mPackages) {
9993            p = mPackages.get(packageName);
9994            if (p == null) {
9995                dataOnly = true;
9996                PackageSetting ps = mSettings.mPackages.get(packageName);
9997                if ((ps == null) || (ps.pkg == null)) {
9998                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9999                    return false;
10000                }
10001                p = ps.pkg;
10002            }
10003            if (!dataOnly) {
10004                // need to check this only for fully installed applications
10005                if (p == null) {
10006                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10007                    return false;
10008                }
10009                final ApplicationInfo applicationInfo = p.applicationInfo;
10010                if (applicationInfo == null) {
10011                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10012                    return false;
10013                }
10014            }
10015            if (p != null && p.applicationInfo != null) {
10016                appId = p.applicationInfo.uid;
10017            } else {
10018                appId = -1;
10019            }
10020        }
10021        int retCode = mInstaller.clearUserData(packageName, userId);
10022        if (retCode < 0) {
10023            Slog.w(TAG, "Couldn't remove cache files for package: "
10024                    + packageName);
10025            return false;
10026        }
10027        removeKeystoreDataIfNeeded(userId, appId);
10028        return true;
10029    }
10030
10031    /**
10032     * Remove entries from the keystore daemon. Will only remove it if the
10033     * {@code appId} is valid.
10034     */
10035    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10036        if (appId < 0) {
10037            return;
10038        }
10039
10040        final KeyStore keyStore = KeyStore.getInstance();
10041        if (keyStore != null) {
10042            if (userId == UserHandle.USER_ALL) {
10043                for (final int individual : sUserManager.getUserIds()) {
10044                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10045                }
10046            } else {
10047                keyStore.clearUid(UserHandle.getUid(userId, appId));
10048            }
10049        } else {
10050            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10051        }
10052    }
10053
10054    public void deleteApplicationCacheFiles(final String packageName,
10055            final IPackageDataObserver observer) {
10056        mContext.enforceCallingOrSelfPermission(
10057                android.Manifest.permission.DELETE_CACHE_FILES, null);
10058        // Queue up an async operation since the package deletion may take a little while.
10059        final int userId = UserHandle.getCallingUserId();
10060        mHandler.post(new Runnable() {
10061            public void run() {
10062                mHandler.removeCallbacks(this);
10063                final boolean succeded;
10064                synchronized (mInstallLock) {
10065                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10066                }
10067                clearExternalStorageDataSync(packageName, userId, false);
10068                if(observer != null) {
10069                    try {
10070                        observer.onRemoveCompleted(packageName, succeded);
10071                    } catch (RemoteException e) {
10072                        Log.i(TAG, "Observer no longer exists.");
10073                    }
10074                } //end if observer
10075            } //end run
10076        });
10077    }
10078
10079    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10080        if (packageName == null) {
10081            Slog.w(TAG, "Attempt to delete null packageName.");
10082            return false;
10083        }
10084        PackageParser.Package p;
10085        synchronized (mPackages) {
10086            p = mPackages.get(packageName);
10087        }
10088        if (p == null) {
10089            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10090            return false;
10091        }
10092        final ApplicationInfo applicationInfo = p.applicationInfo;
10093        if (applicationInfo == null) {
10094            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10095            return false;
10096        }
10097        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10098        if (retCode < 0) {
10099            Slog.w(TAG, "Couldn't remove cache files for package: "
10100                       + packageName + " u" + userId);
10101            return false;
10102        }
10103        return true;
10104    }
10105
10106    public void getPackageSizeInfo(final String packageName, int userHandle,
10107            final IPackageStatsObserver observer) {
10108        mContext.enforceCallingOrSelfPermission(
10109                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10110
10111        PackageStats stats = new PackageStats(packageName, userHandle);
10112
10113        /*
10114         * Queue up an async operation since the package measurement may take a
10115         * little while.
10116         */
10117        Message msg = mHandler.obtainMessage(INIT_COPY);
10118        msg.obj = new MeasureParams(stats, observer);
10119        mHandler.sendMessage(msg);
10120    }
10121
10122    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10123            PackageStats pStats) {
10124        if (packageName == null) {
10125            Slog.w(TAG, "Attempt to get size of null packageName.");
10126            return false;
10127        }
10128        PackageParser.Package p;
10129        boolean dataOnly = false;
10130        String libDirPath = null;
10131        String asecPath = null;
10132        synchronized (mPackages) {
10133            p = mPackages.get(packageName);
10134            PackageSetting ps = mSettings.mPackages.get(packageName);
10135            if(p == null) {
10136                dataOnly = true;
10137                if((ps == null) || (ps.pkg == null)) {
10138                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10139                    return false;
10140                }
10141                p = ps.pkg;
10142            }
10143            if (ps != null) {
10144                libDirPath = ps.nativeLibraryPathString;
10145            }
10146            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10147                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10148                if (secureContainerId != null) {
10149                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10150                }
10151            }
10152        }
10153        String publicSrcDir = null;
10154        if(!dataOnly) {
10155            final ApplicationInfo applicationInfo = p.applicationInfo;
10156            if (applicationInfo == null) {
10157                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10158                return false;
10159            }
10160            if (isForwardLocked(p)) {
10161                publicSrcDir = applicationInfo.publicSourceDir;
10162            }
10163        }
10164        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10165                publicSrcDir, asecPath, pStats);
10166        if (res < 0) {
10167            return false;
10168        }
10169
10170        // Fix-up for forward-locked applications in ASEC containers.
10171        if (!isExternal(p)) {
10172            pStats.codeSize += pStats.externalCodeSize;
10173            pStats.externalCodeSize = 0L;
10174        }
10175
10176        return true;
10177    }
10178
10179
10180    public void addPackageToPreferred(String packageName) {
10181        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10182    }
10183
10184    public void removePackageFromPreferred(String packageName) {
10185        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10186    }
10187
10188    public List<PackageInfo> getPreferredPackages(int flags) {
10189        return new ArrayList<PackageInfo>();
10190    }
10191
10192    private int getUidTargetSdkVersionLockedLPr(int uid) {
10193        Object obj = mSettings.getUserIdLPr(uid);
10194        if (obj instanceof SharedUserSetting) {
10195            final SharedUserSetting sus = (SharedUserSetting) obj;
10196            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10197            final Iterator<PackageSetting> it = sus.packages.iterator();
10198            while (it.hasNext()) {
10199                final PackageSetting ps = it.next();
10200                if (ps.pkg != null) {
10201                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10202                    if (v < vers) vers = v;
10203                }
10204            }
10205            return vers;
10206        } else if (obj instanceof PackageSetting) {
10207            final PackageSetting ps = (PackageSetting) obj;
10208            if (ps.pkg != null) {
10209                return ps.pkg.applicationInfo.targetSdkVersion;
10210            }
10211        }
10212        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10213    }
10214
10215    public void addPreferredActivity(IntentFilter filter, int match,
10216            ComponentName[] set, ComponentName activity, int userId) {
10217        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10218    }
10219
10220    private void addPreferredActivityInternal(IntentFilter filter, int match,
10221            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10222        // writer
10223        int callingUid = Binder.getCallingUid();
10224        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10225        if (filter.countActions() == 0) {
10226            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10227            return;
10228        }
10229        synchronized (mPackages) {
10230            if (mContext.checkCallingOrSelfPermission(
10231                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10232                    != PackageManager.PERMISSION_GRANTED) {
10233                if (getUidTargetSdkVersionLockedLPr(callingUid)
10234                        < Build.VERSION_CODES.FROYO) {
10235                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10236                            + callingUid);
10237                    return;
10238                }
10239                mContext.enforceCallingOrSelfPermission(
10240                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10241            }
10242
10243            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10244            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10245            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10246                    new PreferredActivity(filter, match, set, activity, always));
10247            mSettings.writePackageRestrictionsLPr(userId);
10248        }
10249    }
10250
10251    public void replacePreferredActivity(IntentFilter filter, int match,
10252            ComponentName[] set, ComponentName activity) {
10253        if (filter.countActions() != 1) {
10254            throw new IllegalArgumentException(
10255                    "replacePreferredActivity expects filter to have only 1 action.");
10256        }
10257        if (filter.countDataAuthorities() != 0
10258                || filter.countDataPaths() != 0
10259                || filter.countDataSchemes() > 1
10260                || filter.countDataTypes() != 0) {
10261            throw new IllegalArgumentException(
10262                    "replacePreferredActivity expects filter to have no data authorities, " +
10263                    "paths, or types; and at most one scheme.");
10264        }
10265        synchronized (mPackages) {
10266            if (mContext.checkCallingOrSelfPermission(
10267                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10268                    != PackageManager.PERMISSION_GRANTED) {
10269                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10270                        < Build.VERSION_CODES.FROYO) {
10271                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10272                            + Binder.getCallingUid());
10273                    return;
10274                }
10275                mContext.enforceCallingOrSelfPermission(
10276                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10277            }
10278
10279            final int callingUserId = UserHandle.getCallingUserId();
10280            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10281            if (pir != null) {
10282                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10283                if (filter.countDataSchemes() == 1) {
10284                    Uri.Builder builder = new Uri.Builder();
10285                    builder.scheme(filter.getDataScheme(0));
10286                    intent.setData(builder.build());
10287                }
10288                List<PreferredActivity> matches = pir.queryIntent(
10289                        intent, null, true, callingUserId);
10290                if (DEBUG_PREFERRED) {
10291                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10292                }
10293                for (int i = 0; i < matches.size(); i++) {
10294                    PreferredActivity pa = matches.get(i);
10295                    if (DEBUG_PREFERRED) {
10296                        Slog.i(TAG, "Removing preferred activity "
10297                                + pa.mPref.mComponent + ":");
10298                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10299                    }
10300                    pir.removeFilter(pa);
10301                }
10302            }
10303            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10304        }
10305    }
10306
10307    public void clearPackagePreferredActivities(String packageName) {
10308        final int uid = Binder.getCallingUid();
10309        // writer
10310        synchronized (mPackages) {
10311            PackageParser.Package pkg = mPackages.get(packageName);
10312            if (pkg == null || pkg.applicationInfo.uid != uid) {
10313                if (mContext.checkCallingOrSelfPermission(
10314                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10315                        != PackageManager.PERMISSION_GRANTED) {
10316                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10317                            < Build.VERSION_CODES.FROYO) {
10318                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10319                                + Binder.getCallingUid());
10320                        return;
10321                    }
10322                    mContext.enforceCallingOrSelfPermission(
10323                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10324                }
10325            }
10326
10327            int user = UserHandle.getCallingUserId();
10328            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10329                mSettings.writePackageRestrictionsLPr(user);
10330                scheduleWriteSettingsLocked();
10331            }
10332        }
10333    }
10334
10335    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10336    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10337        ArrayList<PreferredActivity> removed = null;
10338        boolean changed = false;
10339        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10340            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10341            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10342            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10343                continue;
10344            }
10345            Iterator<PreferredActivity> it = pir.filterIterator();
10346            while (it.hasNext()) {
10347                PreferredActivity pa = it.next();
10348                // Mark entry for removal only if it matches the package name
10349                // and the entry is of type "always".
10350                if (packageName == null ||
10351                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10352                                && pa.mPref.mAlways)) {
10353                    if (removed == null) {
10354                        removed = new ArrayList<PreferredActivity>();
10355                    }
10356                    removed.add(pa);
10357                }
10358            }
10359            if (removed != null) {
10360                for (int j=0; j<removed.size(); j++) {
10361                    PreferredActivity pa = removed.get(j);
10362                    pir.removeFilter(pa);
10363                }
10364                changed = true;
10365            }
10366        }
10367        return changed;
10368    }
10369
10370    public void resetPreferredActivities(int userId) {
10371        mContext.enforceCallingOrSelfPermission(
10372                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10373        // writer
10374        synchronized (mPackages) {
10375            int user = UserHandle.getCallingUserId();
10376            clearPackagePreferredActivitiesLPw(null, user);
10377            mSettings.readDefaultPreferredAppsLPw(this, user);
10378            mSettings.writePackageRestrictionsLPr(user);
10379            scheduleWriteSettingsLocked();
10380        }
10381    }
10382
10383    public int getPreferredActivities(List<IntentFilter> outFilters,
10384            List<ComponentName> outActivities, String packageName) {
10385
10386        int num = 0;
10387        final int userId = UserHandle.getCallingUserId();
10388        // reader
10389        synchronized (mPackages) {
10390            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10391            if (pir != null) {
10392                final Iterator<PreferredActivity> it = pir.filterIterator();
10393                while (it.hasNext()) {
10394                    final PreferredActivity pa = it.next();
10395                    if (packageName == null
10396                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10397                                    && pa.mPref.mAlways)) {
10398                        if (outFilters != null) {
10399                            outFilters.add(new IntentFilter(pa));
10400                        }
10401                        if (outActivities != null) {
10402                            outActivities.add(pa.mPref.mComponent);
10403                        }
10404                    }
10405                }
10406            }
10407        }
10408
10409        return num;
10410    }
10411
10412    @Override
10413    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
10414            int userId) {
10415        int callingUid = Binder.getCallingUid();
10416        if (callingUid != Process.SYSTEM_UID) {
10417            throw new SecurityException(
10418                    "addPersistentPreferredActivity can only be run by the system");
10419        }
10420        if (filter.countActions() == 0) {
10421            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10422            return;
10423        }
10424        synchronized (mPackages) {
10425            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
10426                    " :");
10427            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10428            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
10429                    new PersistentPreferredActivity(filter, activity));
10430            mSettings.writePackageRestrictionsLPr(userId);
10431        }
10432    }
10433
10434    @Override
10435    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
10436        int callingUid = Binder.getCallingUid();
10437        if (callingUid != Process.SYSTEM_UID) {
10438            throw new SecurityException(
10439                    "clearPackagePersistentPreferredActivities can only be run by the system");
10440        }
10441        ArrayList<PersistentPreferredActivity> removed = null;
10442        boolean changed = false;
10443        synchronized (mPackages) {
10444            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
10445                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
10446                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
10447                        .valueAt(i);
10448                if (userId != thisUserId) {
10449                    continue;
10450                }
10451                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
10452                while (it.hasNext()) {
10453                    PersistentPreferredActivity ppa = it.next();
10454                    // Mark entry for removal only if it matches the package name.
10455                    if (ppa.mComponent.getPackageName().equals(packageName)) {
10456                        if (removed == null) {
10457                            removed = new ArrayList<PersistentPreferredActivity>();
10458                        }
10459                        removed.add(ppa);
10460                    }
10461                }
10462                if (removed != null) {
10463                    for (int j=0; j<removed.size(); j++) {
10464                        PersistentPreferredActivity ppa = removed.get(j);
10465                        ppir.removeFilter(ppa);
10466                    }
10467                    changed = true;
10468                }
10469            }
10470
10471            if (changed) {
10472                mSettings.writePackageRestrictionsLPr(userId);
10473            }
10474        }
10475    }
10476
10477    @Override
10478    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10479        Intent intent = new Intent(Intent.ACTION_MAIN);
10480        intent.addCategory(Intent.CATEGORY_HOME);
10481
10482        final int callingUserId = UserHandle.getCallingUserId();
10483        List<ResolveInfo> list = queryIntentActivities(intent, null,
10484                PackageManager.GET_META_DATA, callingUserId);
10485        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10486                true, false, false, callingUserId);
10487
10488        allHomeCandidates.clear();
10489        if (list != null) {
10490            for (ResolveInfo ri : list) {
10491                allHomeCandidates.add(ri);
10492            }
10493        }
10494        return (preferred == null || preferred.activityInfo == null)
10495                ? null
10496                : new ComponentName(preferred.activityInfo.packageName,
10497                        preferred.activityInfo.name);
10498    }
10499
10500    @Override
10501    public void setApplicationEnabledSetting(String appPackageName,
10502            int newState, int flags, int userId, String callingPackage) {
10503        if (!sUserManager.exists(userId)) return;
10504        if (callingPackage == null) {
10505            callingPackage = Integer.toString(Binder.getCallingUid());
10506        }
10507        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10508    }
10509
10510    @Override
10511    public void setComponentEnabledSetting(ComponentName componentName,
10512            int newState, int flags, int userId) {
10513        if (!sUserManager.exists(userId)) return;
10514        setEnabledSetting(componentName.getPackageName(),
10515                componentName.getClassName(), newState, flags, userId, null);
10516    }
10517
10518    private void setEnabledSetting(final String packageName, String className, int newState,
10519            final int flags, int userId, String callingPackage) {
10520        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10521              || newState == COMPONENT_ENABLED_STATE_ENABLED
10522              || newState == COMPONENT_ENABLED_STATE_DISABLED
10523              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10524              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10525            throw new IllegalArgumentException("Invalid new component state: "
10526                    + newState);
10527        }
10528        PackageSetting pkgSetting;
10529        final int uid = Binder.getCallingUid();
10530        final int permission = mContext.checkCallingOrSelfPermission(
10531                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10532        enforceCrossUserPermission(uid, userId, false, "set enabled");
10533        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10534        boolean sendNow = false;
10535        boolean isApp = (className == null);
10536        String componentName = isApp ? packageName : className;
10537        int packageUid = -1;
10538        ArrayList<String> components;
10539
10540        // writer
10541        synchronized (mPackages) {
10542            pkgSetting = mSettings.mPackages.get(packageName);
10543            if (pkgSetting == null) {
10544                if (className == null) {
10545                    throw new IllegalArgumentException(
10546                            "Unknown package: " + packageName);
10547                }
10548                throw new IllegalArgumentException(
10549                        "Unknown component: " + packageName
10550                        + "/" + className);
10551            }
10552            // Allow root and verify that userId is not being specified by a different user
10553            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10554                throw new SecurityException(
10555                        "Permission Denial: attempt to change component state from pid="
10556                        + Binder.getCallingPid()
10557                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10558            }
10559            if (className == null) {
10560                // We're dealing with an application/package level state change
10561                if (pkgSetting.getEnabled(userId) == newState) {
10562                    // Nothing to do
10563                    return;
10564                }
10565                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10566                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10567                    // Don't care about who enables an app.
10568                    callingPackage = null;
10569                }
10570                pkgSetting.setEnabled(newState, userId, callingPackage);
10571                // pkgSetting.pkg.mSetEnabled = newState;
10572            } else {
10573                // We're dealing with a component level state change
10574                // First, verify that this is a valid class name.
10575                PackageParser.Package pkg = pkgSetting.pkg;
10576                if (pkg == null || !pkg.hasComponentClassName(className)) {
10577                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10578                        throw new IllegalArgumentException("Component class " + className
10579                                + " does not exist in " + packageName);
10580                    } else {
10581                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10582                                + className + " does not exist in " + packageName);
10583                    }
10584                }
10585                switch (newState) {
10586                case COMPONENT_ENABLED_STATE_ENABLED:
10587                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10588                        return;
10589                    }
10590                    break;
10591                case COMPONENT_ENABLED_STATE_DISABLED:
10592                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10593                        return;
10594                    }
10595                    break;
10596                case COMPONENT_ENABLED_STATE_DEFAULT:
10597                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10598                        return;
10599                    }
10600                    break;
10601                default:
10602                    Slog.e(TAG, "Invalid new component state: " + newState);
10603                    return;
10604                }
10605            }
10606            mSettings.writePackageRestrictionsLPr(userId);
10607            components = mPendingBroadcasts.get(userId, packageName);
10608            final boolean newPackage = components == null;
10609            if (newPackage) {
10610                components = new ArrayList<String>();
10611            }
10612            if (!components.contains(componentName)) {
10613                components.add(componentName);
10614            }
10615            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10616                sendNow = true;
10617                // Purge entry from pending broadcast list if another one exists already
10618                // since we are sending one right away.
10619                mPendingBroadcasts.remove(userId, packageName);
10620            } else {
10621                if (newPackage) {
10622                    mPendingBroadcasts.put(userId, packageName, components);
10623                }
10624                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10625                    // Schedule a message
10626                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10627                }
10628            }
10629        }
10630
10631        long callingId = Binder.clearCallingIdentity();
10632        try {
10633            if (sendNow) {
10634                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10635                sendPackageChangedBroadcast(packageName,
10636                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10637            }
10638        } finally {
10639            Binder.restoreCallingIdentity(callingId);
10640        }
10641    }
10642
10643    private void sendPackageChangedBroadcast(String packageName,
10644            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10645        if (DEBUG_INSTALL)
10646            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10647                    + componentNames);
10648        Bundle extras = new Bundle(4);
10649        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10650        String nameList[] = new String[componentNames.size()];
10651        componentNames.toArray(nameList);
10652        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10653        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10654        extras.putInt(Intent.EXTRA_UID, packageUid);
10655        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10656                new int[] {UserHandle.getUserId(packageUid)});
10657    }
10658
10659    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
10660        if (!sUserManager.exists(userId)) return;
10661        final int uid = Binder.getCallingUid();
10662        final int permission = mContext.checkCallingOrSelfPermission(
10663                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10664        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10665        enforceCrossUserPermission(uid, userId, true, "stop package");
10666        // writer
10667        synchronized (mPackages) {
10668            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
10669                    uid, userId)) {
10670                scheduleWritePackageRestrictionsLocked(userId);
10671            }
10672        }
10673    }
10674
10675    public String getInstallerPackageName(String packageName) {
10676        // reader
10677        synchronized (mPackages) {
10678            return mSettings.getInstallerPackageNameLPr(packageName);
10679        }
10680    }
10681
10682    @Override
10683    public int getApplicationEnabledSetting(String packageName, int userId) {
10684        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10685        int uid = Binder.getCallingUid();
10686        enforceCrossUserPermission(uid, userId, false, "get enabled");
10687        // reader
10688        synchronized (mPackages) {
10689            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
10690        }
10691    }
10692
10693    @Override
10694    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
10695        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10696        int uid = Binder.getCallingUid();
10697        enforceCrossUserPermission(uid, userId, false, "get component enabled");
10698        // reader
10699        synchronized (mPackages) {
10700            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
10701        }
10702    }
10703
10704    public void enterSafeMode() {
10705        enforceSystemOrRoot("Only the system can request entering safe mode");
10706
10707        if (!mSystemReady) {
10708            mSafeMode = true;
10709        }
10710    }
10711
10712    public void systemReady() {
10713        mSystemReady = true;
10714
10715        // Read the compatibilty setting when the system is ready.
10716        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
10717                mContext.getContentResolver(),
10718                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
10719        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
10720        if (DEBUG_SETTINGS) {
10721            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
10722        }
10723
10724        synchronized (mPackages) {
10725            // Verify that all of the preferred activity components actually
10726            // exist.  It is possible for applications to be updated and at
10727            // that point remove a previously declared activity component that
10728            // had been set as a preferred activity.  We try to clean this up
10729            // the next time we encounter that preferred activity, but it is
10730            // possible for the user flow to never be able to return to that
10731            // situation so here we do a sanity check to make sure we haven't
10732            // left any junk around.
10733            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
10734            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10735                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10736                removed.clear();
10737                for (PreferredActivity pa : pir.filterSet()) {
10738                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
10739                        removed.add(pa);
10740                    }
10741                }
10742                if (removed.size() > 0) {
10743                    for (int j=0; j<removed.size(); j++) {
10744                        PreferredActivity pa = removed.get(i);
10745                        Slog.w(TAG, "Removing dangling preferred activity: "
10746                                + pa.mPref.mComponent);
10747                        pir.removeFilter(pa);
10748                    }
10749                    mSettings.writePackageRestrictionsLPr(
10750                            mSettings.mPreferredActivities.keyAt(i));
10751                }
10752            }
10753        }
10754        sUserManager.systemReady();
10755    }
10756
10757    public boolean isSafeMode() {
10758        return mSafeMode;
10759    }
10760
10761    public boolean hasSystemUidErrors() {
10762        return mHasSystemUidErrors;
10763    }
10764
10765    static String arrayToString(int[] array) {
10766        StringBuffer buf = new StringBuffer(128);
10767        buf.append('[');
10768        if (array != null) {
10769            for (int i=0; i<array.length; i++) {
10770                if (i > 0) buf.append(", ");
10771                buf.append(array[i]);
10772            }
10773        }
10774        buf.append(']');
10775        return buf.toString();
10776    }
10777
10778    static class DumpState {
10779        public static final int DUMP_LIBS = 1 << 0;
10780
10781        public static final int DUMP_FEATURES = 1 << 1;
10782
10783        public static final int DUMP_RESOLVERS = 1 << 2;
10784
10785        public static final int DUMP_PERMISSIONS = 1 << 3;
10786
10787        public static final int DUMP_PACKAGES = 1 << 4;
10788
10789        public static final int DUMP_SHARED_USERS = 1 << 5;
10790
10791        public static final int DUMP_MESSAGES = 1 << 6;
10792
10793        public static final int DUMP_PROVIDERS = 1 << 7;
10794
10795        public static final int DUMP_VERIFIERS = 1 << 8;
10796
10797        public static final int DUMP_PREFERRED = 1 << 9;
10798
10799        public static final int DUMP_PREFERRED_XML = 1 << 10;
10800
10801        public static final int DUMP_KEYSETS = 1 << 11;
10802
10803        public static final int OPTION_SHOW_FILTERS = 1 << 0;
10804
10805        private int mTypes;
10806
10807        private int mOptions;
10808
10809        private boolean mTitlePrinted;
10810
10811        private SharedUserSetting mSharedUser;
10812
10813        public boolean isDumping(int type) {
10814            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
10815                return true;
10816            }
10817
10818            return (mTypes & type) != 0;
10819        }
10820
10821        public void setDump(int type) {
10822            mTypes |= type;
10823        }
10824
10825        public boolean isOptionEnabled(int option) {
10826            return (mOptions & option) != 0;
10827        }
10828
10829        public void setOptionEnabled(int option) {
10830            mOptions |= option;
10831        }
10832
10833        public boolean onTitlePrinted() {
10834            final boolean printed = mTitlePrinted;
10835            mTitlePrinted = true;
10836            return printed;
10837        }
10838
10839        public boolean getTitlePrinted() {
10840            return mTitlePrinted;
10841        }
10842
10843        public void setTitlePrinted(boolean enabled) {
10844            mTitlePrinted = enabled;
10845        }
10846
10847        public SharedUserSetting getSharedUser() {
10848            return mSharedUser;
10849        }
10850
10851        public void setSharedUser(SharedUserSetting user) {
10852            mSharedUser = user;
10853        }
10854    }
10855
10856    @Override
10857    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
10858        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
10859                != PackageManager.PERMISSION_GRANTED) {
10860            pw.println("Permission Denial: can't dump ActivityManager from from pid="
10861                    + Binder.getCallingPid()
10862                    + ", uid=" + Binder.getCallingUid()
10863                    + " without permission "
10864                    + android.Manifest.permission.DUMP);
10865            return;
10866        }
10867
10868        DumpState dumpState = new DumpState();
10869        boolean fullPreferred = false;
10870        boolean checkin = false;
10871
10872        String packageName = null;
10873
10874        int opti = 0;
10875        while (opti < args.length) {
10876            String opt = args[opti];
10877            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10878                break;
10879            }
10880            opti++;
10881            if ("-a".equals(opt)) {
10882                // Right now we only know how to print all.
10883            } else if ("-h".equals(opt)) {
10884                pw.println("Package manager dump options:");
10885                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
10886                pw.println("    --checkin: dump for a checkin");
10887                pw.println("    -f: print details of intent filters");
10888                pw.println("    -h: print this help");
10889                pw.println("  cmd may be one of:");
10890                pw.println("    l[ibraries]: list known shared libraries");
10891                pw.println("    f[ibraries]: list device features");
10892                pw.println("    r[esolvers]: dump intent resolvers");
10893                pw.println("    perm[issions]: dump permissions");
10894                pw.println("    pref[erred]: print preferred package settings");
10895                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
10896                pw.println("    prov[iders]: dump content providers");
10897                pw.println("    p[ackages]: dump installed packages");
10898                pw.println("    s[hared-users]: dump shared user IDs");
10899                pw.println("    m[essages]: print collected runtime messages");
10900                pw.println("    v[erifiers]: print package verifier info");
10901                pw.println("    <package.name>: info about given package");
10902                pw.println("    k[eysets]: print known keysets");
10903                return;
10904            } else if ("--checkin".equals(opt)) {
10905                checkin = true;
10906            } else if ("-f".equals(opt)) {
10907                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
10908            } else {
10909                pw.println("Unknown argument: " + opt + "; use -h for help");
10910            }
10911        }
10912
10913        // Is the caller requesting to dump a particular piece of data?
10914        if (opti < args.length) {
10915            String cmd = args[opti];
10916            opti++;
10917            // Is this a package name?
10918            if ("android".equals(cmd) || cmd.contains(".")) {
10919                packageName = cmd;
10920                // When dumping a single package, we always dump all of its
10921                // filter information since the amount of data will be reasonable.
10922                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
10923            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
10924                dumpState.setDump(DumpState.DUMP_LIBS);
10925            } else if ("f".equals(cmd) || "features".equals(cmd)) {
10926                dumpState.setDump(DumpState.DUMP_FEATURES);
10927            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
10928                dumpState.setDump(DumpState.DUMP_RESOLVERS);
10929            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
10930                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
10931            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
10932                dumpState.setDump(DumpState.DUMP_PREFERRED);
10933            } else if ("preferred-xml".equals(cmd)) {
10934                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
10935                if (opti < args.length && "--full".equals(args[opti])) {
10936                    fullPreferred = true;
10937                    opti++;
10938                }
10939            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
10940                dumpState.setDump(DumpState.DUMP_PACKAGES);
10941            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
10942                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
10943            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
10944                dumpState.setDump(DumpState.DUMP_PROVIDERS);
10945            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
10946                dumpState.setDump(DumpState.DUMP_MESSAGES);
10947            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
10948                dumpState.setDump(DumpState.DUMP_VERIFIERS);
10949            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
10950                dumpState.setDump(DumpState.DUMP_KEYSETS);
10951            }
10952        }
10953
10954        if (checkin) {
10955            pw.println("vers,1");
10956        }
10957
10958        // reader
10959        synchronized (mPackages) {
10960            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
10961                if (!checkin) {
10962                    if (dumpState.onTitlePrinted())
10963                        pw.println();
10964                    pw.println("Verifiers:");
10965                    pw.print("  Required: ");
10966                    pw.print(mRequiredVerifierPackage);
10967                    pw.print(" (uid=");
10968                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
10969                    pw.println(")");
10970                } else if (mRequiredVerifierPackage != null) {
10971                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
10972                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
10973                }
10974            }
10975
10976            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
10977                boolean printedHeader = false;
10978                final Iterator<String> it = mSharedLibraries.keySet().iterator();
10979                while (it.hasNext()) {
10980                    String name = it.next();
10981                    SharedLibraryEntry ent = mSharedLibraries.get(name);
10982                    if (!checkin) {
10983                        if (!printedHeader) {
10984                            if (dumpState.onTitlePrinted())
10985                                pw.println();
10986                            pw.println("Libraries:");
10987                            printedHeader = true;
10988                        }
10989                        pw.print("  ");
10990                    } else {
10991                        pw.print("lib,");
10992                    }
10993                    pw.print(name);
10994                    if (!checkin) {
10995                        pw.print(" -> ");
10996                    }
10997                    if (ent.path != null) {
10998                        if (!checkin) {
10999                            pw.print("(jar) ");
11000                            pw.print(ent.path);
11001                        } else {
11002                            pw.print(",jar,");
11003                            pw.print(ent.path);
11004                        }
11005                    } else {
11006                        if (!checkin) {
11007                            pw.print("(apk) ");
11008                            pw.print(ent.apk);
11009                        } else {
11010                            pw.print(",apk,");
11011                            pw.print(ent.apk);
11012                        }
11013                    }
11014                    pw.println();
11015                }
11016            }
11017
11018            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11019                if (dumpState.onTitlePrinted())
11020                    pw.println();
11021                if (!checkin) {
11022                    pw.println("Features:");
11023                }
11024                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11025                while (it.hasNext()) {
11026                    String name = it.next();
11027                    if (!checkin) {
11028                        pw.print("  ");
11029                    } else {
11030                        pw.print("feat,");
11031                    }
11032                    pw.println(name);
11033                }
11034            }
11035
11036            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11037                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11038                        : "Activity Resolver Table:", "  ", packageName,
11039                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11040                    dumpState.setTitlePrinted(true);
11041                }
11042                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11043                        : "Receiver Resolver Table:", "  ", packageName,
11044                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11045                    dumpState.setTitlePrinted(true);
11046                }
11047                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11048                        : "Service Resolver Table:", "  ", packageName,
11049                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11050                    dumpState.setTitlePrinted(true);
11051                }
11052                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11053                        : "Provider Resolver Table:", "  ", packageName,
11054                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11055                    dumpState.setTitlePrinted(true);
11056                }
11057            }
11058
11059            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11060                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11061                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11062                    int user = mSettings.mPreferredActivities.keyAt(i);
11063                    if (pir.dump(pw,
11064                            dumpState.getTitlePrinted()
11065                                ? "\nPreferred Activities User " + user + ":"
11066                                : "Preferred Activities User " + user + ":", "  ",
11067                            packageName, true)) {
11068                        dumpState.setTitlePrinted(true);
11069                    }
11070                }
11071            }
11072
11073            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11074                pw.flush();
11075                FileOutputStream fout = new FileOutputStream(fd);
11076                BufferedOutputStream str = new BufferedOutputStream(fout);
11077                XmlSerializer serializer = new FastXmlSerializer();
11078                try {
11079                    serializer.setOutput(str, "utf-8");
11080                    serializer.startDocument(null, true);
11081                    serializer.setFeature(
11082                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11083                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11084                    serializer.endDocument();
11085                    serializer.flush();
11086                } catch (IllegalArgumentException e) {
11087                    pw.println("Failed writing: " + e);
11088                } catch (IllegalStateException e) {
11089                    pw.println("Failed writing: " + e);
11090                } catch (IOException e) {
11091                    pw.println("Failed writing: " + e);
11092                }
11093            }
11094
11095            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11096                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11097            }
11098
11099            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11100                boolean printedSomething = false;
11101                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11102                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11103                        continue;
11104                    }
11105                    if (!printedSomething) {
11106                        if (dumpState.onTitlePrinted())
11107                            pw.println();
11108                        pw.println("Registered ContentProviders:");
11109                        printedSomething = true;
11110                    }
11111                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11112                    pw.print("    "); pw.println(p.toString());
11113                }
11114                printedSomething = false;
11115                for (Map.Entry<String, PackageParser.Provider> entry :
11116                        mProvidersByAuthority.entrySet()) {
11117                    PackageParser.Provider p = entry.getValue();
11118                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11119                        continue;
11120                    }
11121                    if (!printedSomething) {
11122                        if (dumpState.onTitlePrinted())
11123                            pw.println();
11124                        pw.println("ContentProvider Authorities:");
11125                        printedSomething = true;
11126                    }
11127                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11128                    pw.print("    "); pw.println(p.toString());
11129                    if (p.info != null && p.info.applicationInfo != null) {
11130                        final String appInfo = p.info.applicationInfo.toString();
11131                        pw.print("      applicationInfo="); pw.println(appInfo);
11132                    }
11133                }
11134            }
11135
11136            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11137                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11138            }
11139
11140            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11141                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11142            }
11143
11144            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11145                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11146            }
11147
11148            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11149                if (dumpState.onTitlePrinted())
11150                    pw.println();
11151                mSettings.dumpReadMessagesLPr(pw, dumpState);
11152
11153                pw.println();
11154                pw.println("Package warning messages:");
11155                final File fname = getSettingsProblemFile();
11156                FileInputStream in = null;
11157                try {
11158                    in = new FileInputStream(fname);
11159                    final int avail = in.available();
11160                    final byte[] data = new byte[avail];
11161                    in.read(data);
11162                    pw.print(new String(data));
11163                } catch (FileNotFoundException e) {
11164                } catch (IOException e) {
11165                } finally {
11166                    if (in != null) {
11167                        try {
11168                            in.close();
11169                        } catch (IOException e) {
11170                        }
11171                    }
11172                }
11173            }
11174        }
11175    }
11176
11177    // ------- apps on sdcard specific code -------
11178    static final boolean DEBUG_SD_INSTALL = false;
11179
11180    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11181
11182    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11183
11184    private boolean mMediaMounted = false;
11185
11186    private String getEncryptKey() {
11187        try {
11188            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11189                    SD_ENCRYPTION_KEYSTORE_NAME);
11190            if (sdEncKey == null) {
11191                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11192                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11193                if (sdEncKey == null) {
11194                    Slog.e(TAG, "Failed to create encryption keys");
11195                    return null;
11196                }
11197            }
11198            return sdEncKey;
11199        } catch (NoSuchAlgorithmException nsae) {
11200            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11201            return null;
11202        } catch (IOException ioe) {
11203            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11204            return null;
11205        }
11206
11207    }
11208
11209    /* package */static String getTempContainerId() {
11210        int tmpIdx = 1;
11211        String list[] = PackageHelper.getSecureContainerList();
11212        if (list != null) {
11213            for (final String name : list) {
11214                // Ignore null and non-temporary container entries
11215                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11216                    continue;
11217                }
11218
11219                String subStr = name.substring(mTempContainerPrefix.length());
11220                try {
11221                    int cid = Integer.parseInt(subStr);
11222                    if (cid >= tmpIdx) {
11223                        tmpIdx = cid + 1;
11224                    }
11225                } catch (NumberFormatException e) {
11226                }
11227            }
11228        }
11229        return mTempContainerPrefix + tmpIdx;
11230    }
11231
11232    /*
11233     * Update media status on PackageManager.
11234     */
11235    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11236        int callingUid = Binder.getCallingUid();
11237        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11238            throw new SecurityException("Media status can only be updated by the system");
11239        }
11240        // reader; this apparently protects mMediaMounted, but should probably
11241        // be a different lock in that case.
11242        synchronized (mPackages) {
11243            Log.i(TAG, "Updating external media status from "
11244                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11245                    + (mediaStatus ? "mounted" : "unmounted"));
11246            if (DEBUG_SD_INSTALL)
11247                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11248                        + ", mMediaMounted=" + mMediaMounted);
11249            if (mediaStatus == mMediaMounted) {
11250                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11251                        : 0, -1);
11252                mHandler.sendMessage(msg);
11253                return;
11254            }
11255            mMediaMounted = mediaStatus;
11256        }
11257        // Queue up an async operation since the package installation may take a
11258        // little while.
11259        mHandler.post(new Runnable() {
11260            public void run() {
11261                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11262            }
11263        });
11264    }
11265
11266    /**
11267     * Called by MountService when the initial ASECs to scan are available.
11268     * Should block until all the ASEC containers are finished being scanned.
11269     */
11270    public void scanAvailableAsecs() {
11271        updateExternalMediaStatusInner(true, false, false);
11272    }
11273
11274    /*
11275     * Collect information of applications on external media, map them against
11276     * existing containers and update information based on current mount status.
11277     * Please note that we always have to report status if reportStatus has been
11278     * set to true especially when unloading packages.
11279     */
11280    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11281            boolean externalStorage) {
11282        // Collection of uids
11283        int uidArr[] = null;
11284        // Collection of stale containers
11285        HashSet<String> removeCids = new HashSet<String>();
11286        // Collection of packages on external media with valid containers.
11287        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11288        // Get list of secure containers.
11289        final String list[] = PackageHelper.getSecureContainerList();
11290        if (list == null || list.length == 0) {
11291            Log.i(TAG, "No secure containers on sdcard");
11292        } else {
11293            // Process list of secure containers and categorize them
11294            // as active or stale based on their package internal state.
11295            int uidList[] = new int[list.length];
11296            int num = 0;
11297            // reader
11298            synchronized (mPackages) {
11299                for (String cid : list) {
11300                    if (DEBUG_SD_INSTALL)
11301                        Log.i(TAG, "Processing container " + cid);
11302                    String pkgName = getAsecPackageName(cid);
11303                    if (pkgName == null) {
11304                        if (DEBUG_SD_INSTALL)
11305                            Log.i(TAG, "Container : " + cid + " stale");
11306                        removeCids.add(cid);
11307                        continue;
11308                    }
11309                    if (DEBUG_SD_INSTALL)
11310                        Log.i(TAG, "Looking for pkg : " + pkgName);
11311
11312                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11313                    if (ps == null) {
11314                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11315                        removeCids.add(cid);
11316                        continue;
11317                    }
11318
11319                    /*
11320                     * Skip packages that are not external if we're unmounting
11321                     * external storage.
11322                     */
11323                    if (externalStorage && !isMounted && !isExternal(ps)) {
11324                        continue;
11325                    }
11326
11327                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
11328                    // The package status is changed only if the code path
11329                    // matches between settings and the container id.
11330                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11331                        if (DEBUG_SD_INSTALL) {
11332                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11333                                    + " at code path: " + ps.codePathString);
11334                        }
11335
11336                        // We do have a valid package installed on sdcard
11337                        processCids.put(args, ps.codePathString);
11338                        final int uid = ps.appId;
11339                        if (uid != -1) {
11340                            uidList[num++] = uid;
11341                        }
11342                    } else {
11343                        Log.i(TAG, "Deleting stale container for " + cid);
11344                        removeCids.add(cid);
11345                    }
11346                }
11347            }
11348
11349            if (num > 0) {
11350                // Sort uid list
11351                Arrays.sort(uidList, 0, num);
11352                // Throw away duplicates
11353                uidArr = new int[num];
11354                uidArr[0] = uidList[0];
11355                int di = 0;
11356                for (int i = 1; i < num; i++) {
11357                    if (uidList[i - 1] != uidList[i]) {
11358                        uidArr[di++] = uidList[i];
11359                    }
11360                }
11361            }
11362        }
11363        // Process packages with valid entries.
11364        if (isMounted) {
11365            if (DEBUG_SD_INSTALL)
11366                Log.i(TAG, "Loading packages");
11367            loadMediaPackages(processCids, uidArr, removeCids);
11368            startCleaningPackages();
11369        } else {
11370            if (DEBUG_SD_INSTALL)
11371                Log.i(TAG, "Unloading packages");
11372            unloadMediaPackages(processCids, uidArr, reportStatus);
11373        }
11374    }
11375
11376   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11377           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11378        int size = pkgList.size();
11379        if (size > 0) {
11380            // Send broadcasts here
11381            Bundle extras = new Bundle();
11382            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11383                    .toArray(new String[size]));
11384            if (uidArr != null) {
11385                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11386            }
11387            if (replacing) {
11388                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11389            }
11390            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11391                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11392            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11393        }
11394    }
11395
11396   /*
11397     * Look at potentially valid container ids from processCids If package
11398     * information doesn't match the one on record or package scanning fails,
11399     * the cid is added to list of removeCids. We currently don't delete stale
11400     * containers.
11401     */
11402   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11403            HashSet<String> removeCids) {
11404        ArrayList<String> pkgList = new ArrayList<String>();
11405        Set<AsecInstallArgs> keys = processCids.keySet();
11406        boolean doGc = false;
11407        for (AsecInstallArgs args : keys) {
11408            String codePath = processCids.get(args);
11409            if (DEBUG_SD_INSTALL)
11410                Log.i(TAG, "Loading container : " + args.cid);
11411            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11412            try {
11413                // Make sure there are no container errors first.
11414                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11415                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11416                            + " when installing from sdcard");
11417                    continue;
11418                }
11419                // Check code path here.
11420                if (codePath == null || !codePath.equals(args.getCodePath())) {
11421                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11422                            + " does not match one in settings " + codePath);
11423                    continue;
11424                }
11425                // Parse package
11426                int parseFlags = mDefParseFlags;
11427                if (args.isExternal()) {
11428                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11429                }
11430                if (args.isFwdLocked()) {
11431                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11432                }
11433
11434                doGc = true;
11435                synchronized (mInstallLock) {
11436                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11437                            0, 0, null);
11438                    // Scan the package
11439                    if (pkg != null) {
11440                        /*
11441                         * TODO why is the lock being held? doPostInstall is
11442                         * called in other places without the lock. This needs
11443                         * to be straightened out.
11444                         */
11445                        // writer
11446                        synchronized (mPackages) {
11447                            retCode = PackageManager.INSTALL_SUCCEEDED;
11448                            pkgList.add(pkg.packageName);
11449                            // Post process args
11450                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11451                                    pkg.applicationInfo.uid);
11452                        }
11453                    } else {
11454                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11455                    }
11456                }
11457
11458            } finally {
11459                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11460                    // Don't destroy container here. Wait till gc clears things
11461                    // up.
11462                    removeCids.add(args.cid);
11463                }
11464            }
11465        }
11466        // writer
11467        synchronized (mPackages) {
11468            // If the platform SDK has changed since the last time we booted,
11469            // we need to re-grant app permission to catch any new ones that
11470            // appear. This is really a hack, and means that apps can in some
11471            // cases get permissions that the user didn't initially explicitly
11472            // allow... it would be nice to have some better way to handle
11473            // this situation.
11474            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11475            if (regrantPermissions)
11476                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11477                        + mSdkVersion + "; regranting permissions for external storage");
11478            mSettings.mExternalSdkPlatform = mSdkVersion;
11479
11480            // Make sure group IDs have been assigned, and any permission
11481            // changes in other apps are accounted for
11482            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11483                    | (regrantPermissions
11484                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11485                            : 0));
11486            // can downgrade to reader
11487            // Persist settings
11488            mSettings.writeLPr();
11489        }
11490        // Send a broadcast to let everyone know we are done processing
11491        if (pkgList.size() > 0) {
11492            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11493        }
11494        // Force gc to avoid any stale parser references that we might have.
11495        if (doGc) {
11496            Runtime.getRuntime().gc();
11497        }
11498        // List stale containers and destroy stale temporary containers.
11499        if (removeCids != null) {
11500            for (String cid : removeCids) {
11501                if (cid.startsWith(mTempContainerPrefix)) {
11502                    Log.i(TAG, "Destroying stale temporary container " + cid);
11503                    PackageHelper.destroySdDir(cid);
11504                } else {
11505                    Log.w(TAG, "Container " + cid + " is stale");
11506               }
11507           }
11508        }
11509    }
11510
11511   /*
11512     * Utility method to unload a list of specified containers
11513     */
11514    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11515        // Just unmount all valid containers.
11516        for (AsecInstallArgs arg : cidArgs) {
11517            synchronized (mInstallLock) {
11518                arg.doPostDeleteLI(false);
11519           }
11520       }
11521   }
11522
11523    /*
11524     * Unload packages mounted on external media. This involves deleting package
11525     * data from internal structures, sending broadcasts about diabled packages,
11526     * gc'ing to free up references, unmounting all secure containers
11527     * corresponding to packages on external media, and posting a
11528     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11529     * that we always have to post this message if status has been requested no
11530     * matter what.
11531     */
11532    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11533            final boolean reportStatus) {
11534        if (DEBUG_SD_INSTALL)
11535            Log.i(TAG, "unloading media packages");
11536        ArrayList<String> pkgList = new ArrayList<String>();
11537        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11538        final Set<AsecInstallArgs> keys = processCids.keySet();
11539        for (AsecInstallArgs args : keys) {
11540            String pkgName = args.getPackageName();
11541            if (DEBUG_SD_INSTALL)
11542                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11543            // Delete package internally
11544            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11545            synchronized (mInstallLock) {
11546                boolean res = deletePackageLI(pkgName, null, false, null, null,
11547                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11548                if (res) {
11549                    pkgList.add(pkgName);
11550                } else {
11551                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11552                    failedList.add(args);
11553                }
11554            }
11555        }
11556
11557        // reader
11558        synchronized (mPackages) {
11559            // We didn't update the settings after removing each package;
11560            // write them now for all packages.
11561            mSettings.writeLPr();
11562        }
11563
11564        // We have to absolutely send UPDATED_MEDIA_STATUS only
11565        // after confirming that all the receivers processed the ordered
11566        // broadcast when packages get disabled, force a gc to clean things up.
11567        // and unload all the containers.
11568        if (pkgList.size() > 0) {
11569            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11570                    new IIntentReceiver.Stub() {
11571                public void performReceive(Intent intent, int resultCode, String data,
11572                        Bundle extras, boolean ordered, boolean sticky,
11573                        int sendingUser) throws RemoteException {
11574                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11575                            reportStatus ? 1 : 0, 1, keys);
11576                    mHandler.sendMessage(msg);
11577                }
11578            });
11579        } else {
11580            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11581                    keys);
11582            mHandler.sendMessage(msg);
11583        }
11584    }
11585
11586    /** Binder call */
11587    @Override
11588    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11589            final int flags) {
11590        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11591        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11592        int returnCode = PackageManager.MOVE_SUCCEEDED;
11593        int currFlags = 0;
11594        int newFlags = 0;
11595        // reader
11596        synchronized (mPackages) {
11597            PackageParser.Package pkg = mPackages.get(packageName);
11598            if (pkg == null) {
11599                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11600            } else {
11601                // Disable moving fwd locked apps and system packages
11602                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11603                    Slog.w(TAG, "Cannot move system application");
11604                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11605                } else if (pkg.mOperationPending) {
11606                    Slog.w(TAG, "Attempt to move package which has pending operations");
11607                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11608                } else {
11609                    // Find install location first
11610                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11611                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11612                        Slog.w(TAG, "Ambigous flags specified for move location.");
11613                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11614                    } else {
11615                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11616                                : PackageManager.INSTALL_INTERNAL;
11617                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11618                                : PackageManager.INSTALL_INTERNAL;
11619
11620                        if (newFlags == currFlags) {
11621                            Slog.w(TAG, "No move required. Trying to move to same location");
11622                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11623                        } else {
11624                            if (isForwardLocked(pkg)) {
11625                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11626                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11627                            }
11628                        }
11629                    }
11630                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11631                        pkg.mOperationPending = true;
11632                    }
11633                }
11634            }
11635
11636            /*
11637             * TODO this next block probably shouldn't be inside the lock. We
11638             * can't guarantee these won't change after this is fired off
11639             * anyway.
11640             */
11641            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11642                processPendingMove(new MoveParams(null, observer, 0, packageName,
11643                        null, -1, user),
11644                        returnCode);
11645            } else {
11646                Message msg = mHandler.obtainMessage(INIT_COPY);
11647                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
11648                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
11649                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
11650                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
11651                msg.obj = mp;
11652                mHandler.sendMessage(msg);
11653            }
11654        }
11655    }
11656
11657    private void processPendingMove(final MoveParams mp, final int currentStatus) {
11658        // Queue up an async operation since the package deletion may take a
11659        // little while.
11660        mHandler.post(new Runnable() {
11661            public void run() {
11662                // TODO fix this; this does nothing.
11663                mHandler.removeCallbacks(this);
11664                int returnCode = currentStatus;
11665                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
11666                    int uidArr[] = null;
11667                    ArrayList<String> pkgList = null;
11668                    synchronized (mPackages) {
11669                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11670                        if (pkg == null) {
11671                            Slog.w(TAG, " Package " + mp.packageName
11672                                    + " doesn't exist. Aborting move");
11673                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11674                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
11675                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
11676                                    + mp.srcArgs.getCodePath() + " to "
11677                                    + pkg.applicationInfo.sourceDir
11678                                    + " Aborting move and returning error");
11679                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11680                        } else {
11681                            uidArr = new int[] {
11682                                pkg.applicationInfo.uid
11683                            };
11684                            pkgList = new ArrayList<String>();
11685                            pkgList.add(mp.packageName);
11686                        }
11687                    }
11688                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11689                        // Send resources unavailable broadcast
11690                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
11691                        // Update package code and resource paths
11692                        synchronized (mInstallLock) {
11693                            synchronized (mPackages) {
11694                                PackageParser.Package pkg = mPackages.get(mp.packageName);
11695                                // Recheck for package again.
11696                                if (pkg == null) {
11697                                    Slog.w(TAG, " Package " + mp.packageName
11698                                            + " doesn't exist. Aborting move");
11699                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11700                                } else if (!mp.srcArgs.getCodePath().equals(
11701                                        pkg.applicationInfo.sourceDir)) {
11702                                    Slog.w(TAG, "Package " + mp.packageName
11703                                            + " code path changed from " + mp.srcArgs.getCodePath()
11704                                            + " to " + pkg.applicationInfo.sourceDir
11705                                            + " Aborting move and returning error");
11706                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11707                                } else {
11708                                    final String oldCodePath = pkg.mPath;
11709                                    final String newCodePath = mp.targetArgs.getCodePath();
11710                                    final String newResPath = mp.targetArgs.getResourcePath();
11711                                    final String newNativePath = mp.targetArgs
11712                                            .getNativeLibraryPath();
11713
11714                                    final File newNativeDir = new File(newNativePath);
11715
11716                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
11717                                        NativeLibraryHelper.copyNativeBinariesIfNeededLI(
11718                                                new File(newCodePath), newNativeDir);
11719                                    }
11720                                    final int[] users = sUserManager.getUserIds();
11721                                    for (int user : users) {
11722                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
11723                                                newNativePath, user) < 0) {
11724                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11725                                        }
11726                                    }
11727
11728                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11729                                        pkg.mPath = newCodePath;
11730                                        // Move dex files around
11731                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
11732                                            // Moving of dex files failed. Set
11733                                            // error code and abort move.
11734                                            pkg.mPath = pkg.mScanPath;
11735                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11736                                        }
11737                                    }
11738
11739                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11740                                        pkg.mScanPath = newCodePath;
11741                                        pkg.applicationInfo.sourceDir = newCodePath;
11742                                        pkg.applicationInfo.publicSourceDir = newResPath;
11743                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
11744                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
11745                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
11746                                        ps.codePathString = ps.codePath.getPath();
11747                                        ps.resourcePath = new File(
11748                                                pkg.applicationInfo.publicSourceDir);
11749                                        ps.resourcePathString = ps.resourcePath.getPath();
11750                                        ps.nativeLibraryPathString = newNativePath;
11751                                        // Set the application info flag
11752                                        // correctly.
11753                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
11754                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11755                                        } else {
11756                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11757                                        }
11758                                        ps.setFlags(pkg.applicationInfo.flags);
11759                                        mAppDirs.remove(oldCodePath);
11760                                        mAppDirs.put(newCodePath, pkg);
11761                                        // Persist settings
11762                                        mSettings.writeLPr();
11763                                    }
11764                                }
11765                            }
11766                        }
11767                        // Send resources available broadcast
11768                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11769                    }
11770                }
11771                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11772                    // Clean up failed installation
11773                    if (mp.targetArgs != null) {
11774                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
11775                                -1);
11776                    }
11777                } else {
11778                    // Force a gc to clear things up.
11779                    Runtime.getRuntime().gc();
11780                    // Delete older code
11781                    synchronized (mInstallLock) {
11782                        mp.srcArgs.doPostDeleteLI(true);
11783                    }
11784                }
11785
11786                // Allow more operations on this file if we didn't fail because
11787                // an operation was already pending for this package.
11788                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
11789                    synchronized (mPackages) {
11790                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11791                        if (pkg != null) {
11792                            pkg.mOperationPending = false;
11793                       }
11794                   }
11795                }
11796
11797                IPackageMoveObserver observer = mp.observer;
11798                if (observer != null) {
11799                    try {
11800                        observer.packageMoved(mp.packageName, returnCode);
11801                    } catch (RemoteException e) {
11802                        Log.i(TAG, "Observer no longer exists.");
11803                    }
11804                }
11805            }
11806        });
11807    }
11808
11809    public boolean setInstallLocation(int loc) {
11810        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
11811                null);
11812        if (getInstallLocation() == loc) {
11813            return true;
11814        }
11815        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
11816                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
11817            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
11818                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
11819            return true;
11820        }
11821        return false;
11822   }
11823
11824    public int getInstallLocation() {
11825        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11826                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
11827                PackageHelper.APP_INSTALL_AUTO);
11828    }
11829
11830    /** Called by UserManagerService */
11831    void cleanUpUserLILPw(int userHandle) {
11832        mDirtyUsers.remove(userHandle);
11833        mSettings.removeUserLPr(userHandle);
11834        mPendingBroadcasts.remove(userHandle);
11835        if (mInstaller != null) {
11836            // Technically, we shouldn't be doing this with the package lock
11837            // held.  However, this is very rare, and there is already so much
11838            // other disk I/O going on, that we'll let it slide for now.
11839            mInstaller.removeUserDataDirs(userHandle);
11840        }
11841    }
11842
11843    /** Called by UserManagerService */
11844    void createNewUserLILPw(int userHandle, File path) {
11845        if (mInstaller != null) {
11846            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
11847        }
11848    }
11849
11850    @Override
11851    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
11852        mContext.enforceCallingOrSelfPermission(
11853                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11854                "Only package verification agents can read the verifier device identity");
11855
11856        synchronized (mPackages) {
11857            return mSettings.getVerifierDeviceIdentityLPw();
11858        }
11859    }
11860
11861    @Override
11862    public void setPermissionEnforced(String permission, boolean enforced) {
11863        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
11864        if (READ_EXTERNAL_STORAGE.equals(permission)) {
11865            synchronized (mPackages) {
11866                if (mSettings.mReadExternalStorageEnforced == null
11867                        || mSettings.mReadExternalStorageEnforced != enforced) {
11868                    mSettings.mReadExternalStorageEnforced = enforced;
11869                    mSettings.writeLPr();
11870                }
11871            }
11872            // kill any non-foreground processes so we restart them and
11873            // grant/revoke the GID.
11874            final IActivityManager am = ActivityManagerNative.getDefault();
11875            if (am != null) {
11876                final long token = Binder.clearCallingIdentity();
11877                try {
11878                    am.killProcessesBelowForeground("setPermissionEnforcement");
11879                } catch (RemoteException e) {
11880                } finally {
11881                    Binder.restoreCallingIdentity(token);
11882                }
11883            }
11884        } else {
11885            throw new IllegalArgumentException("No selective enforcement for " + permission);
11886        }
11887    }
11888
11889    @Override
11890    @Deprecated
11891    public boolean isPermissionEnforced(String permission) {
11892        return true;
11893    }
11894
11895    @Override
11896    public boolean isStorageLow() {
11897        final long token = Binder.clearCallingIdentity();
11898        try {
11899            final DeviceStorageMonitorInternal
11900                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11901            if (dsm != null) {
11902                return dsm.isMemoryLow();
11903            } else {
11904                return false;
11905            }
11906        } finally {
11907            Binder.restoreCallingIdentity(token);
11908        }
11909    }
11910}
11911