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