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