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