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