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