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