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