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