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