PackageManagerService.java revision aa737c49df79749fe92b89d745eba7442762e2b5
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, true,
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    /**
2550     * Compares two sets of signatures. Returns:
2551     * <br />
2552     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2553     * <br />
2554     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2555     * <br />
2556     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2557     * <br />
2558     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2559     * <br />
2560     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2561     */
2562    static int compareSignatures(Signature[] s1, Signature[] s2) {
2563        if (s1 == null) {
2564            return s2 == null
2565                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2566                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2567        }
2568
2569        if (s2 == null) {
2570            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2571        }
2572
2573        if (s1.length != s2.length) {
2574            return PackageManager.SIGNATURE_NO_MATCH;
2575        }
2576
2577        // Since both signature sets are of size 1, we can compare without HashSets.
2578        if (s1.length == 1) {
2579            return s1[0].equals(s2[0]) ?
2580                    PackageManager.SIGNATURE_MATCH :
2581                    PackageManager.SIGNATURE_NO_MATCH;
2582        }
2583
2584        HashSet<Signature> set1 = new HashSet<Signature>();
2585        for (Signature sig : s1) {
2586            set1.add(sig);
2587        }
2588        HashSet<Signature> set2 = new HashSet<Signature>();
2589        for (Signature sig : s2) {
2590            set2.add(sig);
2591        }
2592        // Make sure s2 contains all signatures in s1.
2593        if (set1.equals(set2)) {
2594            return PackageManager.SIGNATURE_MATCH;
2595        }
2596        return PackageManager.SIGNATURE_NO_MATCH;
2597    }
2598
2599    public String[] getPackagesForUid(int uid) {
2600        uid = UserHandle.getAppId(uid);
2601        // reader
2602        synchronized (mPackages) {
2603            Object obj = mSettings.getUserIdLPr(uid);
2604            if (obj instanceof SharedUserSetting) {
2605                final SharedUserSetting sus = (SharedUserSetting) obj;
2606                final int N = sus.packages.size();
2607                final String[] res = new String[N];
2608                final Iterator<PackageSetting> it = sus.packages.iterator();
2609                int i = 0;
2610                while (it.hasNext()) {
2611                    res[i++] = it.next().name;
2612                }
2613                return res;
2614            } else if (obj instanceof PackageSetting) {
2615                final PackageSetting ps = (PackageSetting) obj;
2616                return new String[] { ps.name };
2617            }
2618        }
2619        return null;
2620    }
2621
2622    public String getNameForUid(int uid) {
2623        // reader
2624        synchronized (mPackages) {
2625            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2626            if (obj instanceof SharedUserSetting) {
2627                final SharedUserSetting sus = (SharedUserSetting) obj;
2628                return sus.name + ":" + sus.userId;
2629            } else if (obj instanceof PackageSetting) {
2630                final PackageSetting ps = (PackageSetting) obj;
2631                return ps.name;
2632            }
2633        }
2634        return null;
2635    }
2636
2637    public int getUidForSharedUser(String sharedUserName) {
2638        if(sharedUserName == null) {
2639            return -1;
2640        }
2641        // reader
2642        synchronized (mPackages) {
2643            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2644            if (suid == null) {
2645                return -1;
2646            }
2647            return suid.userId;
2648        }
2649    }
2650
2651    public int getFlagsForUid(int uid) {
2652        synchronized (mPackages) {
2653            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2654            if (obj instanceof SharedUserSetting) {
2655                final SharedUserSetting sus = (SharedUserSetting) obj;
2656                return sus.pkgFlags;
2657            } else if (obj instanceof PackageSetting) {
2658                final PackageSetting ps = (PackageSetting) obj;
2659                return ps.pkgFlags;
2660            }
2661        }
2662        return 0;
2663    }
2664
2665    @Override
2666    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2667            int flags, int userId) {
2668        if (!sUserManager.exists(userId)) return null;
2669        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2670        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2671        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2672    }
2673
2674    @Override
2675    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2676            IntentFilter filter, int match, ComponentName activity) {
2677        final int userId = UserHandle.getCallingUserId();
2678        if (DEBUG_PREFERRED) {
2679            Log.v(TAG, "setLastChosenActivity intent=" + intent
2680                + " resolvedType=" + resolvedType
2681                + " flags=" + flags
2682                + " filter=" + filter
2683                + " match=" + match
2684                + " activity=" + activity);
2685            filter.dump(new PrintStreamPrinter(System.out), "    ");
2686        }
2687        intent.setComponent(null);
2688        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2689        // Find any earlier preferred or last chosen entries and nuke them
2690        findPreferredActivity(intent, resolvedType,
2691                flags, query, 0, false, true, false, userId);
2692        // Add the new activity as the last chosen for this filter
2693        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2694    }
2695
2696    @Override
2697    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2698        final int userId = UserHandle.getCallingUserId();
2699        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2700        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2701        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2702                false, false, false, userId);
2703    }
2704
2705    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2706            int flags, List<ResolveInfo> query, int userId) {
2707        if (query != null) {
2708            final int N = query.size();
2709            if (N == 1) {
2710                return query.get(0);
2711            } else if (N > 1) {
2712                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2713                // If there is more than one activity with the same priority,
2714                // then let the user decide between them.
2715                ResolveInfo r0 = query.get(0);
2716                ResolveInfo r1 = query.get(1);
2717                if (DEBUG_INTENT_MATCHING || debug) {
2718                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2719                            + r1.activityInfo.name + "=" + r1.priority);
2720                }
2721                // If the first activity has a higher priority, or a different
2722                // default, then it is always desireable to pick it.
2723                if (r0.priority != r1.priority
2724                        || r0.preferredOrder != r1.preferredOrder
2725                        || r0.isDefault != r1.isDefault) {
2726                    return query.get(0);
2727                }
2728                // If we have saved a preference for a preferred activity for
2729                // this Intent, use that.
2730                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2731                        flags, query, r0.priority, true, false, debug, userId);
2732                if (ri != null) {
2733                    return ri;
2734                }
2735                if (userId != 0) {
2736                    ri = new ResolveInfo(mResolveInfo);
2737                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2738                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2739                            ri.activityInfo.applicationInfo);
2740                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2741                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2742                    return ri;
2743                }
2744                return mResolveInfo;
2745            }
2746        }
2747        return null;
2748    }
2749
2750    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
2751            List<ResolveInfo> query, int priority, boolean always,
2752            boolean removeMatches, boolean debug, int userId) {
2753        if (!sUserManager.exists(userId)) return null;
2754        // writer
2755        synchronized (mPackages) {
2756            if (intent.getSelector() != null) {
2757                intent = intent.getSelector();
2758            }
2759            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2760            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2761            // Get the list of preferred activities that handle the intent
2762            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
2763            List<PreferredActivity> prefs = pir != null
2764                    ? pir.queryIntent(intent, resolvedType,
2765                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2766                    : null;
2767            if (prefs != null && prefs.size() > 0) {
2768                // First figure out how good the original match set is.
2769                // We will only allow preferred activities that came
2770                // from the same match quality.
2771                int match = 0;
2772
2773                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
2774
2775                final int N = query.size();
2776                for (int j=0; j<N; j++) {
2777                    final ResolveInfo ri = query.get(j);
2778                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
2779                            + ": 0x" + Integer.toHexString(match));
2780                    if (ri.match > match) {
2781                        match = ri.match;
2782                    }
2783                }
2784
2785                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
2786                        + Integer.toHexString(match));
2787
2788                match &= IntentFilter.MATCH_CATEGORY_MASK;
2789                final int M = prefs.size();
2790                for (int i=0; i<M; i++) {
2791                    final PreferredActivity pa = prefs.get(i);
2792                    if (DEBUG_PREFERRED || debug) {
2793                        Slog.v(TAG, "Checking PreferredActivity ds="
2794                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
2795                                + "\n  component=" + pa.mPref.mComponent);
2796                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2797                    }
2798                    if (pa.mPref.mMatch != match) {
2799                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
2800                                + Integer.toHexString(pa.mPref.mMatch));
2801                        continue;
2802                    }
2803                    // If it's not an "always" type preferred activity and that's what we're
2804                    // looking for, skip it.
2805                    if (always && !pa.mPref.mAlways) {
2806                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
2807                        continue;
2808                    }
2809                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
2810                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2811                    if (DEBUG_PREFERRED || debug) {
2812                        Slog.v(TAG, "Found preferred activity:");
2813                        if (ai != null) {
2814                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2815                        } else {
2816                            Slog.v(TAG, "  null");
2817                        }
2818                    }
2819                    if (ai == null) {
2820                        // This previously registered preferred activity
2821                        // component is no longer known.  Most likely an update
2822                        // to the app was installed and in the new version this
2823                        // component no longer exists.  Clean it up by removing
2824                        // it from the preferred activities list, and skip it.
2825                        Slog.w(TAG, "Removing dangling preferred activity: "
2826                                + pa.mPref.mComponent);
2827                        pir.removeFilter(pa);
2828                        continue;
2829                    }
2830                    for (int j=0; j<N; j++) {
2831                        final ResolveInfo ri = query.get(j);
2832                        if (!ri.activityInfo.applicationInfo.packageName
2833                                .equals(ai.applicationInfo.packageName)) {
2834                            continue;
2835                        }
2836                        if (!ri.activityInfo.name.equals(ai.name)) {
2837                            continue;
2838                        }
2839
2840                        if (removeMatches) {
2841                            pir.removeFilter(pa);
2842                            if (DEBUG_PREFERRED) {
2843                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
2844                            }
2845                            break;
2846                        }
2847
2848                        // Okay we found a previously set preferred or last chosen app.
2849                        // If the result set is different from when this
2850                        // was created, we need to clear it and re-ask the
2851                        // user their preference, if we're looking for an "always" type entry.
2852                        if (always && !pa.mPref.sameSet(query, priority)) {
2853                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
2854                                    + intent + " type " + resolvedType);
2855                            if (DEBUG_PREFERRED) {
2856                                Slog.v(TAG, "Removing preferred activity since set changed "
2857                                        + pa.mPref.mComponent);
2858                            }
2859                            pir.removeFilter(pa);
2860                            // Re-add the filter as a "last chosen" entry (!always)
2861                            PreferredActivity lastChosen = new PreferredActivity(
2862                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
2863                            pir.addFilter(lastChosen);
2864                            mSettings.writePackageRestrictionsLPr(userId);
2865                            return null;
2866                        }
2867
2868                        // Yay! Either the set matched or we're looking for the last chosen
2869                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
2870                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
2871                        mSettings.writePackageRestrictionsLPr(userId);
2872                        return ri;
2873                    }
2874                }
2875            }
2876            mSettings.writePackageRestrictionsLPr(userId);
2877        }
2878        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
2879        return null;
2880    }
2881
2882    @Override
2883    public List<ResolveInfo> queryIntentActivities(Intent intent,
2884            String resolvedType, int flags, int userId) {
2885        if (!sUserManager.exists(userId)) return Collections.emptyList();
2886        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
2887        ComponentName comp = intent.getComponent();
2888        if (comp == null) {
2889            if (intent.getSelector() != null) {
2890                intent = intent.getSelector();
2891                comp = intent.getComponent();
2892            }
2893        }
2894
2895        if (comp != null) {
2896            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2897            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
2898            if (ai != null) {
2899                final ResolveInfo ri = new ResolveInfo();
2900                ri.activityInfo = ai;
2901                list.add(ri);
2902            }
2903            return list;
2904        }
2905
2906        // reader
2907        synchronized (mPackages) {
2908            final String pkgName = intent.getPackage();
2909            if (pkgName == null) {
2910                return mActivities.queryIntent(intent, resolvedType, flags, userId);
2911            }
2912            final PackageParser.Package pkg = mPackages.get(pkgName);
2913            if (pkg != null) {
2914                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
2915                        pkg.activities, userId);
2916            }
2917            return new ArrayList<ResolveInfo>();
2918        }
2919    }
2920
2921    @Override
2922    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2923            Intent[] specifics, String[] specificTypes, Intent intent,
2924            String resolvedType, int flags, int userId) {
2925        if (!sUserManager.exists(userId)) return Collections.emptyList();
2926        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2927                "query intent activity options");
2928        final String resultsAction = intent.getAction();
2929
2930        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
2931                | PackageManager.GET_RESOLVED_FILTER, userId);
2932
2933        if (DEBUG_INTENT_MATCHING) {
2934            Log.v(TAG, "Query " + intent + ": " + results);
2935        }
2936
2937        int specificsPos = 0;
2938        int N;
2939
2940        // todo: note that the algorithm used here is O(N^2).  This
2941        // isn't a problem in our current environment, but if we start running
2942        // into situations where we have more than 5 or 10 matches then this
2943        // should probably be changed to something smarter...
2944
2945        // First we go through and resolve each of the specific items
2946        // that were supplied, taking care of removing any corresponding
2947        // duplicate items in the generic resolve list.
2948        if (specifics != null) {
2949            for (int i=0; i<specifics.length; i++) {
2950                final Intent sintent = specifics[i];
2951                if (sintent == null) {
2952                    continue;
2953                }
2954
2955                if (DEBUG_INTENT_MATCHING) {
2956                    Log.v(TAG, "Specific #" + i + ": " + sintent);
2957                }
2958
2959                String action = sintent.getAction();
2960                if (resultsAction != null && resultsAction.equals(action)) {
2961                    // If this action was explicitly requested, then don't
2962                    // remove things that have it.
2963                    action = null;
2964                }
2965
2966                ResolveInfo ri = null;
2967                ActivityInfo ai = null;
2968
2969                ComponentName comp = sintent.getComponent();
2970                if (comp == null) {
2971                    ri = resolveIntent(
2972                        sintent,
2973                        specificTypes != null ? specificTypes[i] : null,
2974                            flags, userId);
2975                    if (ri == null) {
2976                        continue;
2977                    }
2978                    if (ri == mResolveInfo) {
2979                        // ACK!  Must do something better with this.
2980                    }
2981                    ai = ri.activityInfo;
2982                    comp = new ComponentName(ai.applicationInfo.packageName,
2983                            ai.name);
2984                } else {
2985                    ai = getActivityInfo(comp, flags, userId);
2986                    if (ai == null) {
2987                        continue;
2988                    }
2989                }
2990
2991                // Look for any generic query activities that are duplicates
2992                // of this specific one, and remove them from the results.
2993                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
2994                N = results.size();
2995                int j;
2996                for (j=specificsPos; j<N; j++) {
2997                    ResolveInfo sri = results.get(j);
2998                    if ((sri.activityInfo.name.equals(comp.getClassName())
2999                            && sri.activityInfo.applicationInfo.packageName.equals(
3000                                    comp.getPackageName()))
3001                        || (action != null && sri.filter.matchAction(action))) {
3002                        results.remove(j);
3003                        if (DEBUG_INTENT_MATCHING) Log.v(
3004                            TAG, "Removing duplicate item from " + j
3005                            + " due to specific " + specificsPos);
3006                        if (ri == null) {
3007                            ri = sri;
3008                        }
3009                        j--;
3010                        N--;
3011                    }
3012                }
3013
3014                // Add this specific item to its proper place.
3015                if (ri == null) {
3016                    ri = new ResolveInfo();
3017                    ri.activityInfo = ai;
3018                }
3019                results.add(specificsPos, ri);
3020                ri.specificIndex = i;
3021                specificsPos++;
3022            }
3023        }
3024
3025        // Now we go through the remaining generic results and remove any
3026        // duplicate actions that are found here.
3027        N = results.size();
3028        for (int i=specificsPos; i<N-1; i++) {
3029            final ResolveInfo rii = results.get(i);
3030            if (rii.filter == null) {
3031                continue;
3032            }
3033
3034            // Iterate over all of the actions of this result's intent
3035            // filter...  typically this should be just one.
3036            final Iterator<String> it = rii.filter.actionsIterator();
3037            if (it == null) {
3038                continue;
3039            }
3040            while (it.hasNext()) {
3041                final String action = it.next();
3042                if (resultsAction != null && resultsAction.equals(action)) {
3043                    // If this action was explicitly requested, then don't
3044                    // remove things that have it.
3045                    continue;
3046                }
3047                for (int j=i+1; j<N; j++) {
3048                    final ResolveInfo rij = results.get(j);
3049                    if (rij.filter != null && rij.filter.hasAction(action)) {
3050                        results.remove(j);
3051                        if (DEBUG_INTENT_MATCHING) Log.v(
3052                            TAG, "Removing duplicate item from " + j
3053                            + " due to action " + action + " at " + i);
3054                        j--;
3055                        N--;
3056                    }
3057                }
3058            }
3059
3060            // If the caller didn't request filter information, drop it now
3061            // so we don't have to marshall/unmarshall it.
3062            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3063                rii.filter = null;
3064            }
3065        }
3066
3067        // Filter out the caller activity if so requested.
3068        if (caller != null) {
3069            N = results.size();
3070            for (int i=0; i<N; i++) {
3071                ActivityInfo ainfo = results.get(i).activityInfo;
3072                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3073                        && caller.getClassName().equals(ainfo.name)) {
3074                    results.remove(i);
3075                    break;
3076                }
3077            }
3078        }
3079
3080        // If the caller didn't request filter information,
3081        // drop them now so we don't have to
3082        // marshall/unmarshall it.
3083        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3084            N = results.size();
3085            for (int i=0; i<N; i++) {
3086                results.get(i).filter = null;
3087            }
3088        }
3089
3090        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3091        return results;
3092    }
3093
3094    @Override
3095    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3096            int userId) {
3097        if (!sUserManager.exists(userId)) return Collections.emptyList();
3098        ComponentName comp = intent.getComponent();
3099        if (comp == null) {
3100            if (intent.getSelector() != null) {
3101                intent = intent.getSelector();
3102                comp = intent.getComponent();
3103            }
3104        }
3105        if (comp != null) {
3106            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3107            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3108            if (ai != null) {
3109                ResolveInfo ri = new ResolveInfo();
3110                ri.activityInfo = ai;
3111                list.add(ri);
3112            }
3113            return list;
3114        }
3115
3116        // reader
3117        synchronized (mPackages) {
3118            String pkgName = intent.getPackage();
3119            if (pkgName == null) {
3120                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3121            }
3122            final PackageParser.Package pkg = mPackages.get(pkgName);
3123            if (pkg != null) {
3124                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3125                        userId);
3126            }
3127            return null;
3128        }
3129    }
3130
3131    @Override
3132    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3133        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3134        if (!sUserManager.exists(userId)) return null;
3135        if (query != null) {
3136            if (query.size() >= 1) {
3137                // If there is more than one service with the same priority,
3138                // just arbitrarily pick the first one.
3139                return query.get(0);
3140            }
3141        }
3142        return null;
3143    }
3144
3145    @Override
3146    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3147            int userId) {
3148        if (!sUserManager.exists(userId)) return Collections.emptyList();
3149        ComponentName comp = intent.getComponent();
3150        if (comp == null) {
3151            if (intent.getSelector() != null) {
3152                intent = intent.getSelector();
3153                comp = intent.getComponent();
3154            }
3155        }
3156        if (comp != null) {
3157            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3158            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3159            if (si != null) {
3160                final ResolveInfo ri = new ResolveInfo();
3161                ri.serviceInfo = si;
3162                list.add(ri);
3163            }
3164            return list;
3165        }
3166
3167        // reader
3168        synchronized (mPackages) {
3169            String pkgName = intent.getPackage();
3170            if (pkgName == null) {
3171                return mServices.queryIntent(intent, resolvedType, flags, userId);
3172            }
3173            final PackageParser.Package pkg = mPackages.get(pkgName);
3174            if (pkg != null) {
3175                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3176                        userId);
3177            }
3178            return null;
3179        }
3180    }
3181
3182    @Override
3183    public List<ResolveInfo> queryIntentContentProviders(
3184            Intent intent, String resolvedType, int flags, int userId) {
3185        if (!sUserManager.exists(userId)) return Collections.emptyList();
3186        ComponentName comp = intent.getComponent();
3187        if (comp == null) {
3188            if (intent.getSelector() != null) {
3189                intent = intent.getSelector();
3190                comp = intent.getComponent();
3191            }
3192        }
3193        if (comp != null) {
3194            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3195            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3196            if (pi != null) {
3197                final ResolveInfo ri = new ResolveInfo();
3198                ri.providerInfo = pi;
3199                list.add(ri);
3200            }
3201            return list;
3202        }
3203
3204        // reader
3205        synchronized (mPackages) {
3206            String pkgName = intent.getPackage();
3207            if (pkgName == null) {
3208                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3209            }
3210            final PackageParser.Package pkg = mPackages.get(pkgName);
3211            if (pkg != null) {
3212                return mProviders.queryIntentForPackage(
3213                        intent, resolvedType, flags, pkg.providers, userId);
3214            }
3215            return null;
3216        }
3217    }
3218
3219    @Override
3220    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3221        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3222
3223        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3224
3225        // writer
3226        synchronized (mPackages) {
3227            ArrayList<PackageInfo> list;
3228            if (listUninstalled) {
3229                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3230                for (PackageSetting ps : mSettings.mPackages.values()) {
3231                    PackageInfo pi;
3232                    if (ps.pkg != null) {
3233                        pi = generatePackageInfo(ps.pkg, flags, userId);
3234                    } else {
3235                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3236                    }
3237                    if (pi != null) {
3238                        list.add(pi);
3239                    }
3240                }
3241            } else {
3242                list = new ArrayList<PackageInfo>(mPackages.size());
3243                for (PackageParser.Package p : mPackages.values()) {
3244                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3245                    if (pi != null) {
3246                        list.add(pi);
3247                    }
3248                }
3249            }
3250
3251            return new ParceledListSlice<PackageInfo>(list);
3252        }
3253    }
3254
3255    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3256            String[] permissions, boolean[] tmp, int flags, int userId) {
3257        int numMatch = 0;
3258        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3259        for (int i=0; i<permissions.length; i++) {
3260            if (gp.grantedPermissions.contains(permissions[i])) {
3261                tmp[i] = true;
3262                numMatch++;
3263            } else {
3264                tmp[i] = false;
3265            }
3266        }
3267        if (numMatch == 0) {
3268            return;
3269        }
3270        PackageInfo pi;
3271        if (ps.pkg != null) {
3272            pi = generatePackageInfo(ps.pkg, flags, userId);
3273        } else {
3274            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3275        }
3276        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3277            if (numMatch == permissions.length) {
3278                pi.requestedPermissions = permissions;
3279            } else {
3280                pi.requestedPermissions = new String[numMatch];
3281                numMatch = 0;
3282                for (int i=0; i<permissions.length; i++) {
3283                    if (tmp[i]) {
3284                        pi.requestedPermissions[numMatch] = permissions[i];
3285                        numMatch++;
3286                    }
3287                }
3288            }
3289        }
3290        list.add(pi);
3291    }
3292
3293    @Override
3294    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3295            String[] permissions, int flags, int userId) {
3296        if (!sUserManager.exists(userId)) return null;
3297        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3298
3299        // writer
3300        synchronized (mPackages) {
3301            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3302            boolean[] tmpBools = new boolean[permissions.length];
3303            if (listUninstalled) {
3304                for (PackageSetting ps : mSettings.mPackages.values()) {
3305                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3306                }
3307            } else {
3308                for (PackageParser.Package pkg : mPackages.values()) {
3309                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3310                    if (ps != null) {
3311                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3312                                userId);
3313                    }
3314                }
3315            }
3316
3317            return new ParceledListSlice<PackageInfo>(list);
3318        }
3319    }
3320
3321    @Override
3322    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3323        if (!sUserManager.exists(userId)) return null;
3324        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3325
3326        // writer
3327        synchronized (mPackages) {
3328            ArrayList<ApplicationInfo> list;
3329            if (listUninstalled) {
3330                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3331                for (PackageSetting ps : mSettings.mPackages.values()) {
3332                    ApplicationInfo ai;
3333                    if (ps.pkg != null) {
3334                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3335                                ps.readUserState(userId), userId);
3336                    } else {
3337                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3338                    }
3339                    if (ai != null) {
3340                        list.add(ai);
3341                    }
3342                }
3343            } else {
3344                list = new ArrayList<ApplicationInfo>(mPackages.size());
3345                for (PackageParser.Package p : mPackages.values()) {
3346                    if (p.mExtras != null) {
3347                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3348                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3349                        if (ai != null) {
3350                            list.add(ai);
3351                        }
3352                    }
3353                }
3354            }
3355
3356            return new ParceledListSlice<ApplicationInfo>(list);
3357        }
3358    }
3359
3360    public List<ApplicationInfo> getPersistentApplications(int flags) {
3361        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3362
3363        // reader
3364        synchronized (mPackages) {
3365            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3366            final int userId = UserHandle.getCallingUserId();
3367            while (i.hasNext()) {
3368                final PackageParser.Package p = i.next();
3369                if (p.applicationInfo != null
3370                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3371                        && (!mSafeMode || isSystemApp(p))) {
3372                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3373                    if (ps != null) {
3374                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3375                                ps.readUserState(userId), userId);
3376                        if (ai != null) {
3377                            finalList.add(ai);
3378                        }
3379                    }
3380                }
3381            }
3382        }
3383
3384        return finalList;
3385    }
3386
3387    @Override
3388    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3389        if (!sUserManager.exists(userId)) return null;
3390        // reader
3391        synchronized (mPackages) {
3392            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3393            PackageSetting ps = provider != null
3394                    ? mSettings.mPackages.get(provider.owner.packageName)
3395                    : null;
3396            return ps != null
3397                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3398                    && (!mSafeMode || (provider.info.applicationInfo.flags
3399                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3400                    ? PackageParser.generateProviderInfo(provider, flags,
3401                            ps.readUserState(userId), userId)
3402                    : null;
3403        }
3404    }
3405
3406    /**
3407     * @deprecated
3408     */
3409    @Deprecated
3410    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3411        // reader
3412        synchronized (mPackages) {
3413            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3414                    .entrySet().iterator();
3415            final int userId = UserHandle.getCallingUserId();
3416            while (i.hasNext()) {
3417                Map.Entry<String, PackageParser.Provider> entry = i.next();
3418                PackageParser.Provider p = entry.getValue();
3419                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3420
3421                if (ps != null && p.syncable
3422                        && (!mSafeMode || (p.info.applicationInfo.flags
3423                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3424                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3425                            ps.readUserState(userId), userId);
3426                    if (info != null) {
3427                        outNames.add(entry.getKey());
3428                        outInfo.add(info);
3429                    }
3430                }
3431            }
3432        }
3433    }
3434
3435    public List<ProviderInfo> queryContentProviders(String processName,
3436            int uid, int flags) {
3437        ArrayList<ProviderInfo> finalList = null;
3438        // reader
3439        synchronized (mPackages) {
3440            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3441            final int userId = processName != null ?
3442                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3443            while (i.hasNext()) {
3444                final PackageParser.Provider p = i.next();
3445                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3446                if (ps != null && p.info.authority != null
3447                        && (processName == null
3448                                || (p.info.processName.equals(processName)
3449                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3450                        && mSettings.isEnabledLPr(p.info, flags, userId)
3451                        && (!mSafeMode
3452                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3453                    if (finalList == null) {
3454                        finalList = new ArrayList<ProviderInfo>(3);
3455                    }
3456                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3457                            ps.readUserState(userId), userId);
3458                    if (info != null) {
3459                        finalList.add(info);
3460                    }
3461                }
3462            }
3463        }
3464
3465        if (finalList != null) {
3466            Collections.sort(finalList, mProviderInitOrderSorter);
3467        }
3468
3469        return finalList;
3470    }
3471
3472    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3473            int flags) {
3474        // reader
3475        synchronized (mPackages) {
3476            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3477            return PackageParser.generateInstrumentationInfo(i, flags);
3478        }
3479    }
3480
3481    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3482            int flags) {
3483        ArrayList<InstrumentationInfo> finalList =
3484            new ArrayList<InstrumentationInfo>();
3485
3486        // reader
3487        synchronized (mPackages) {
3488            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3489            while (i.hasNext()) {
3490                final PackageParser.Instrumentation p = i.next();
3491                if (targetPackage == null
3492                        || targetPackage.equals(p.info.targetPackage)) {
3493                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3494                            flags);
3495                    if (ii != null) {
3496                        finalList.add(ii);
3497                    }
3498                }
3499            }
3500        }
3501
3502        return finalList;
3503    }
3504
3505    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3506        String[] files = dir.list();
3507        if (files == null) {
3508            Log.d(TAG, "No files in app dir " + dir);
3509            return;
3510        }
3511
3512        if (DEBUG_PACKAGE_SCANNING) {
3513            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3514                    + " flags=0x" + Integer.toHexString(flags));
3515        }
3516
3517        int i;
3518        for (i=0; i<files.length; i++) {
3519            File file = new File(dir, files[i]);
3520            if (!isPackageFilename(files[i])) {
3521                // Ignore entries which are not apk's
3522                continue;
3523            }
3524            PackageParser.Package pkg = scanPackageLI(file,
3525                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3526            // Don't mess around with apps in system partition.
3527            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3528                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3529                // Delete the apk
3530                Slog.w(TAG, "Cleaning up failed install of " + file);
3531                file.delete();
3532            }
3533        }
3534    }
3535
3536    private static File getSettingsProblemFile() {
3537        File dataDir = Environment.getDataDirectory();
3538        File systemDir = new File(dataDir, "system");
3539        File fname = new File(systemDir, "uiderrors.txt");
3540        return fname;
3541    }
3542
3543    static void reportSettingsProblem(int priority, String msg) {
3544        try {
3545            File fname = getSettingsProblemFile();
3546            FileOutputStream out = new FileOutputStream(fname, true);
3547            PrintWriter pw = new FastPrintWriter(out);
3548            SimpleDateFormat formatter = new SimpleDateFormat();
3549            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3550            pw.println(dateString + ": " + msg);
3551            pw.close();
3552            FileUtils.setPermissions(
3553                    fname.toString(),
3554                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3555                    -1, -1);
3556        } catch (java.io.IOException e) {
3557        }
3558        Slog.println(priority, TAG, msg);
3559    }
3560
3561    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3562            PackageParser.Package pkg, File srcFile, int parseFlags) {
3563        if (GET_CERTIFICATES) {
3564            if (ps != null
3565                    && ps.codePath.equals(srcFile)
3566                    && ps.timeStamp == srcFile.lastModified()) {
3567                if (ps.signatures.mSignatures != null
3568                        && ps.signatures.mSignatures.length != 0) {
3569                    // Optimization: reuse the existing cached certificates
3570                    // if the package appears to be unchanged.
3571                    pkg.mSignatures = ps.signatures.mSignatures;
3572                    return true;
3573                }
3574
3575                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3576            } else {
3577                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3578            }
3579
3580            if (!pp.collectCertificates(pkg, parseFlags)) {
3581                mLastScanError = pp.getParseError();
3582                return false;
3583            }
3584        }
3585        return true;
3586    }
3587
3588    /*
3589     *  Scan a package and return the newly parsed package.
3590     *  Returns null in case of errors and the error code is stored in mLastScanError
3591     */
3592    private PackageParser.Package scanPackageLI(File scanFile,
3593            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3594        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3595        String scanPath = scanFile.getPath();
3596        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3597        parseFlags |= mDefParseFlags;
3598        PackageParser pp = new PackageParser(scanPath);
3599        pp.setSeparateProcesses(mSeparateProcesses);
3600        pp.setOnlyCoreApps(mOnlyCore);
3601        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3602                scanPath, mMetrics, parseFlags);
3603
3604        if (pkg == null) {
3605            mLastScanError = pp.getParseError();
3606            return null;
3607        }
3608
3609        PackageSetting ps = null;
3610        PackageSetting updatedPkg;
3611        // reader
3612        synchronized (mPackages) {
3613            // Look to see if we already know about this package.
3614            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3615            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3616                // This package has been renamed to its original name.  Let's
3617                // use that.
3618                ps = mSettings.peekPackageLPr(oldName);
3619            }
3620            // If there was no original package, see one for the real package name.
3621            if (ps == null) {
3622                ps = mSettings.peekPackageLPr(pkg.packageName);
3623            }
3624            // Check to see if this package could be hiding/updating a system
3625            // package.  Must look for it either under the original or real
3626            // package name depending on our state.
3627            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3628            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3629        }
3630        // First check if this is a system package that may involve an update
3631        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3632            if (ps != null && !ps.codePath.equals(scanFile)) {
3633                // The path has changed from what was last scanned...  check the
3634                // version of the new path against what we have stored to determine
3635                // what to do.
3636                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3637                if (pkg.mVersionCode < ps.versionCode) {
3638                    // The system package has been updated and the code path does not match
3639                    // Ignore entry. Skip it.
3640                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3641                            + " ignored: updated version " + ps.versionCode
3642                            + " better than this " + pkg.mVersionCode);
3643                    if (!updatedPkg.codePath.equals(scanFile)) {
3644                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3645                                + ps.name + " changing from " + updatedPkg.codePathString
3646                                + " to " + scanFile);
3647                        updatedPkg.codePath = scanFile;
3648                        updatedPkg.codePathString = scanFile.toString();
3649                        // This is the point at which we know that the system-disk APK
3650                        // for this package has moved during a reboot (e.g. due to an OTA),
3651                        // so we need to reevaluate it for privilege policy.
3652                        if (locationIsPrivileged(scanFile)) {
3653                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3654                        }
3655                    }
3656                    updatedPkg.pkg = pkg;
3657                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3658                    return null;
3659                } else {
3660                    // The current app on the system partion is better than
3661                    // what we have updated to on the data partition; switch
3662                    // back to the system partition version.
3663                    // At this point, its safely assumed that package installation for
3664                    // apps in system partition will go through. If not there won't be a working
3665                    // version of the app
3666                    // writer
3667                    synchronized (mPackages) {
3668                        // Just remove the loaded entries from package lists.
3669                        mPackages.remove(ps.name);
3670                    }
3671                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3672                            + "reverting from " + ps.codePathString
3673                            + ": new version " + pkg.mVersionCode
3674                            + " better than installed " + ps.versionCode);
3675
3676                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3677                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3678                    synchronized (mInstallLock) {
3679                        args.cleanUpResourcesLI();
3680                    }
3681                    synchronized (mPackages) {
3682                        mSettings.enableSystemPackageLPw(ps.name);
3683                    }
3684                }
3685            }
3686        }
3687
3688        if (updatedPkg != null) {
3689            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3690            // initially
3691            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3692
3693            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
3694            // flag set initially
3695            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3696                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
3697            }
3698        }
3699        // Verify certificates against what was last scanned
3700        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3701            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3702            return null;
3703        }
3704
3705        /*
3706         * A new system app appeared, but we already had a non-system one of the
3707         * same name installed earlier.
3708         */
3709        boolean shouldHideSystemApp = false;
3710        if (updatedPkg == null && ps != null
3711                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3712            /*
3713             * Check to make sure the signatures match first. If they don't,
3714             * wipe the installed application and its data.
3715             */
3716            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3717                    != PackageManager.SIGNATURE_MATCH) {
3718                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
3719                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
3720                ps = null;
3721            } else {
3722                /*
3723                 * If the newly-added system app is an older version than the
3724                 * already installed version, hide it. It will be scanned later
3725                 * and re-added like an update.
3726                 */
3727                if (pkg.mVersionCode < ps.versionCode) {
3728                    shouldHideSystemApp = true;
3729                } else {
3730                    /*
3731                     * The newly found system app is a newer version that the
3732                     * one previously installed. Simply remove the
3733                     * already-installed application and replace it with our own
3734                     * while keeping the application data.
3735                     */
3736                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3737                            + ps.codePathString + ": new version " + pkg.mVersionCode
3738                            + " better than installed " + ps.versionCode);
3739                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3740                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3741                    synchronized (mInstallLock) {
3742                        args.cleanUpResourcesLI();
3743                    }
3744                }
3745            }
3746        }
3747
3748        // The apk is forward locked (not public) if its code and resources
3749        // are kept in different files. (except for app in either system or
3750        // vendor path).
3751        // TODO grab this value from PackageSettings
3752        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3753            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3754                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3755            }
3756        }
3757
3758        String codePath = null;
3759        String resPath = null;
3760        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3761            if (ps != null && ps.resourcePathString != null) {
3762                resPath = ps.resourcePathString;
3763            } else {
3764                // Should not happen at all. Just log an error.
3765                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3766            }
3767        } else {
3768            resPath = pkg.mScanPath;
3769        }
3770
3771        codePath = pkg.mScanPath;
3772        // Set application objects path explicitly.
3773        setApplicationInfoPaths(pkg, codePath, resPath);
3774        // Note that we invoke the following method only if we are about to unpack an application
3775        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3776                | SCAN_UPDATE_SIGNATURE, currentTime, user);
3777
3778        /*
3779         * If the system app should be overridden by a previously installed
3780         * data, hide the system app now and let the /data/app scan pick it up
3781         * again.
3782         */
3783        if (shouldHideSystemApp) {
3784            synchronized (mPackages) {
3785                /*
3786                 * We have to grant systems permissions before we hide, because
3787                 * grantPermissions will assume the package update is trying to
3788                 * expand its permissions.
3789                 */
3790                grantPermissionsLPw(pkg, true);
3791                mSettings.disableSystemPackageLPw(pkg.packageName);
3792            }
3793        }
3794
3795        return scannedPkg;
3796    }
3797
3798    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3799            String destResPath) {
3800        pkg.mPath = pkg.mScanPath = destCodePath;
3801        pkg.applicationInfo.sourceDir = destCodePath;
3802        pkg.applicationInfo.publicSourceDir = destResPath;
3803    }
3804
3805    private static String fixProcessName(String defProcessName,
3806            String processName, int uid) {
3807        if (processName == null) {
3808            return defProcessName;
3809        }
3810        return processName;
3811    }
3812
3813    private boolean verifySignaturesLP(PackageSetting pkgSetting,
3814            PackageParser.Package pkg) {
3815        if (pkgSetting.signatures.mSignatures != null) {
3816            // Already existing package. Make sure signatures match
3817            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
3818                PackageManager.SIGNATURE_MATCH) {
3819                    Slog.e(TAG, "Package " + pkg.packageName
3820                            + " signatures do not match the previously installed version; ignoring!");
3821                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3822                    return false;
3823                }
3824        }
3825        // Check for shared user signatures
3826        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
3827            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3828                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3829                Slog.e(TAG, "Package " + pkg.packageName
3830                        + " has no signatures that match those in shared user "
3831                        + pkgSetting.sharedUser.name + "; ignoring!");
3832                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3833                return false;
3834            }
3835        }
3836        return true;
3837    }
3838
3839    /**
3840     * Enforces that only the system UID or root's UID can call a method exposed
3841     * via Binder.
3842     *
3843     * @param message used as message if SecurityException is thrown
3844     * @throws SecurityException if the caller is not system or root
3845     */
3846    private static final void enforceSystemOrRoot(String message) {
3847        final int uid = Binder.getCallingUid();
3848        if (uid != Process.SYSTEM_UID && uid != 0) {
3849            throw new SecurityException(message);
3850        }
3851    }
3852
3853    public void performBootDexOpt() {
3854        HashSet<PackageParser.Package> pkgs = null;
3855        synchronized (mPackages) {
3856            pkgs = mDeferredDexOpt;
3857            mDeferredDexOpt = null;
3858        }
3859        if (pkgs != null) {
3860            int i = 0;
3861            for (PackageParser.Package pkg : pkgs) {
3862                if (!isFirstBoot()) {
3863                    i++;
3864                    try {
3865                        ActivityManagerNative.getDefault().showBootMessage(
3866                                mContext.getResources().getString(
3867                                        com.android.internal.R.string.android_upgrading_apk,
3868                                        i, pkgs.size()), true);
3869                    } catch (RemoteException e) {
3870                    }
3871                }
3872                PackageParser.Package p = pkg;
3873                synchronized (mInstallLock) {
3874                    if (!p.mDidDexOpt) {
3875                        performDexOptLI(p, false, false, true);
3876                    }
3877                }
3878            }
3879        }
3880    }
3881
3882    public boolean performDexOpt(String packageName) {
3883        enforceSystemOrRoot("Only the system can request dexopt be performed");
3884
3885        if (!mNoDexOpt) {
3886            return false;
3887        }
3888
3889        PackageParser.Package p;
3890        synchronized (mPackages) {
3891            p = mPackages.get(packageName);
3892            if (p == null || p.mDidDexOpt) {
3893                return false;
3894            }
3895        }
3896        synchronized (mInstallLock) {
3897            return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED;
3898        }
3899    }
3900
3901    private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer,
3902            HashSet<String> done) {
3903        for (int i=0; i<libs.size(); i++) {
3904            PackageParser.Package libPkg;
3905            String libName;
3906            synchronized (mPackages) {
3907                libName = libs.get(i);
3908                SharedLibraryEntry lib = mSharedLibraries.get(libName);
3909                if (lib != null && lib.apk != null) {
3910                    libPkg = mPackages.get(lib.apk);
3911                } else {
3912                    libPkg = null;
3913                }
3914            }
3915            if (libPkg != null && !done.contains(libName)) {
3916                performDexOptLI(libPkg, forceDex, defer, done);
3917            }
3918        }
3919    }
3920
3921    static final int DEX_OPT_SKIPPED = 0;
3922    static final int DEX_OPT_PERFORMED = 1;
3923    static final int DEX_OPT_DEFERRED = 2;
3924    static final int DEX_OPT_FAILED = -1;
3925
3926    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
3927            HashSet<String> done) {
3928        boolean performed = false;
3929        if (done != null) {
3930            done.add(pkg.packageName);
3931            if (pkg.usesLibraries != null) {
3932                performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done);
3933            }
3934            if (pkg.usesOptionalLibraries != null) {
3935                performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done);
3936            }
3937        }
3938        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3939            String path = pkg.mScanPath;
3940            int ret = 0;
3941            try {
3942                if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
3943                    if (!forceDex && defer) {
3944                        if (mDeferredDexOpt == null) {
3945                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
3946                        }
3947                        mDeferredDexOpt.add(pkg);
3948                        return DEX_OPT_DEFERRED;
3949                    } else {
3950                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3951                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3952                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
3953                        pkg.mDidDexOpt = true;
3954                        performed = true;
3955                    }
3956                }
3957            } catch (FileNotFoundException e) {
3958                Slog.w(TAG, "Apk not found for dexopt: " + path);
3959                ret = -1;
3960            } catch (IOException e) {
3961                Slog.w(TAG, "IOException reading apk: " + path, e);
3962                ret = -1;
3963            } catch (dalvik.system.StaleDexCacheError e) {
3964                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3965                ret = -1;
3966            } catch (Exception e) {
3967                Slog.w(TAG, "Exception when doing dexopt : ", e);
3968                ret = -1;
3969            }
3970            if (ret < 0) {
3971                //error from installer
3972                return DEX_OPT_FAILED;
3973            }
3974        }
3975
3976        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3977    }
3978
3979    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
3980            boolean inclDependencies) {
3981        HashSet<String> done;
3982        boolean performed = false;
3983        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
3984            done = new HashSet<String>();
3985            done.add(pkg.packageName);
3986        } else {
3987            done = null;
3988        }
3989        return performDexOptLI(pkg, forceDex, defer, done);
3990    }
3991
3992    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
3993        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
3994            Slog.w(TAG, "Unable to update from " + oldPkg.name
3995                    + " to " + newPkg.packageName
3996                    + ": old package not in system partition");
3997            return false;
3998        } else if (mPackages.get(oldPkg.name) != null) {
3999            Slog.w(TAG, "Unable to update from " + oldPkg.name
4000                    + " to " + newPkg.packageName
4001                    + ": old package still exists");
4002            return false;
4003        }
4004        return true;
4005    }
4006
4007    File getDataPathForUser(int userId) {
4008        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4009    }
4010
4011    private File getDataPathForPackage(String packageName, int userId) {
4012        /*
4013         * Until we fully support multiple users, return the directory we
4014         * previously would have. The PackageManagerTests will need to be
4015         * revised when this is changed back..
4016         */
4017        if (userId == 0) {
4018            return new File(mAppDataDir, packageName);
4019        } else {
4020            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4021                + File.separator + packageName);
4022        }
4023    }
4024
4025    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4026        int[] users = sUserManager.getUserIds();
4027        int res = mInstaller.install(packageName, uid, uid, seinfo);
4028        if (res < 0) {
4029            return res;
4030        }
4031        for (int user : users) {
4032            if (user != 0) {
4033                res = mInstaller.createUserData(packageName,
4034                        UserHandle.getUid(user, uid), user, seinfo);
4035                if (res < 0) {
4036                    return res;
4037                }
4038            }
4039        }
4040        return res;
4041    }
4042
4043    private int removeDataDirsLI(String packageName) {
4044        int[] users = sUserManager.getUserIds();
4045        int res = 0;
4046        for (int user : users) {
4047            int resInner = mInstaller.remove(packageName, user);
4048            if (resInner < 0) {
4049                res = resInner;
4050            }
4051        }
4052
4053        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4054        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4055        if (!nativeLibraryFile.delete()) {
4056            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4057        }
4058
4059        return res;
4060    }
4061
4062    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4063            PackageParser.Package changingLib) {
4064        if (file.path != null) {
4065            mTmpSharedLibraries[num] = file.path;
4066            return num+1;
4067        }
4068        PackageParser.Package p = mPackages.get(file.apk);
4069        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4070            // If we are doing this while in the middle of updating a library apk,
4071            // then we need to make sure to use that new apk for determining the
4072            // dependencies here.  (We haven't yet finished committing the new apk
4073            // to the package manager state.)
4074            if (p == null || p.packageName.equals(changingLib.packageName)) {
4075                p = changingLib;
4076            }
4077        }
4078        if (p != null) {
4079            String path = p.mPath;
4080            for (int i=0; i<num; i++) {
4081                if (mTmpSharedLibraries[i].equals(path)) {
4082                    return num;
4083                }
4084            }
4085            mTmpSharedLibraries[num] = p.mPath;
4086            return num+1;
4087        }
4088        return num;
4089    }
4090
4091    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4092            PackageParser.Package changingLib) {
4093        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4094            if (mTmpSharedLibraries == null ||
4095                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4096                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4097            }
4098            int num = 0;
4099            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4100            for (int i=0; i<N; i++) {
4101                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4102                if (file == null) {
4103                    Slog.e(TAG, "Package " + pkg.packageName
4104                            + " requires unavailable shared library "
4105                            + pkg.usesLibraries.get(i) + "; failing!");
4106                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4107                    return false;
4108                }
4109                num = addSharedLibraryLPw(file, num, changingLib);
4110            }
4111            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4112            for (int i=0; i<N; i++) {
4113                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4114                if (file == null) {
4115                    Slog.w(TAG, "Package " + pkg.packageName
4116                            + " desires unavailable shared library "
4117                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4118                } else {
4119                    num = addSharedLibraryLPw(file, num, changingLib);
4120                }
4121            }
4122            if (num > 0) {
4123                pkg.usesLibraryFiles = new String[num];
4124                System.arraycopy(mTmpSharedLibraries, 0,
4125                        pkg.usesLibraryFiles, 0, num);
4126            } else {
4127                pkg.usesLibraryFiles = null;
4128            }
4129        }
4130        return true;
4131    }
4132
4133    private static boolean hasString(List<String> list, List<String> which) {
4134        if (list == null) {
4135            return false;
4136        }
4137        for (int i=list.size()-1; i>=0; i--) {
4138            for (int j=which.size()-1; j>=0; j--) {
4139                if (which.get(j).equals(list.get(i))) {
4140                    return true;
4141                }
4142            }
4143        }
4144        return false;
4145    }
4146
4147    private void updateAllSharedLibrariesLPw() {
4148        for (PackageParser.Package pkg : mPackages.values()) {
4149            updateSharedLibrariesLPw(pkg, null);
4150        }
4151    }
4152
4153    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4154            PackageParser.Package changingPkg) {
4155        ArrayList<PackageParser.Package> res = null;
4156        for (PackageParser.Package pkg : mPackages.values()) {
4157            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4158                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4159                if (res == null) {
4160                    res = new ArrayList<PackageParser.Package>();
4161                }
4162                res.add(pkg);
4163                updateSharedLibrariesLPw(pkg, changingPkg);
4164            }
4165        }
4166        return res;
4167    }
4168
4169    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4170            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4171        File scanFile = new File(pkg.mScanPath);
4172        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4173                pkg.applicationInfo.publicSourceDir == null) {
4174            // Bail out. The resource and code paths haven't been set.
4175            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4176            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4177            return null;
4178        }
4179
4180        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4181            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4182        }
4183
4184        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4185            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4186        }
4187
4188        if (mCustomResolverComponentName != null &&
4189                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4190            setUpCustomResolverActivity(pkg);
4191        }
4192
4193        if (pkg.packageName.equals("android")) {
4194            synchronized (mPackages) {
4195                if (mAndroidApplication != null) {
4196                    Slog.w(TAG, "*************************************************");
4197                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4198                    Slog.w(TAG, " file=" + scanFile);
4199                    Slog.w(TAG, "*************************************************");
4200                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4201                    return null;
4202                }
4203
4204                // Set up information for our fall-back user intent resolution activity.
4205                mPlatformPackage = pkg;
4206                pkg.mVersionCode = mSdkVersion;
4207                mAndroidApplication = pkg.applicationInfo;
4208
4209                if (!mResolverReplaced) {
4210                    mResolveActivity.applicationInfo = mAndroidApplication;
4211                    mResolveActivity.name = ResolverActivity.class.getName();
4212                    mResolveActivity.packageName = mAndroidApplication.packageName;
4213                    mResolveActivity.processName = "system:ui";
4214                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4215                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4216                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4217                    mResolveActivity.exported = true;
4218                    mResolveActivity.enabled = true;
4219                    mResolveInfo.activityInfo = mResolveActivity;
4220                    mResolveInfo.priority = 0;
4221                    mResolveInfo.preferredOrder = 0;
4222                    mResolveInfo.match = 0;
4223                    mResolveComponentName = new ComponentName(
4224                            mAndroidApplication.packageName, mResolveActivity.name);
4225                }
4226            }
4227        }
4228
4229        if (DEBUG_PACKAGE_SCANNING) {
4230            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4231                Log.d(TAG, "Scanning package " + pkg.packageName);
4232        }
4233
4234        if (mPackages.containsKey(pkg.packageName)
4235                || mSharedLibraries.containsKey(pkg.packageName)) {
4236            Slog.w(TAG, "Application package " + pkg.packageName
4237                    + " already installed.  Skipping duplicate.");
4238            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4239            return null;
4240        }
4241
4242        // Initialize package source and resource directories
4243        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4244        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4245
4246        SharedUserSetting suid = null;
4247        PackageSetting pkgSetting = null;
4248
4249        if (!isSystemApp(pkg)) {
4250            // Only system apps can use these features.
4251            pkg.mOriginalPackages = null;
4252            pkg.mRealPackage = null;
4253            pkg.mAdoptPermissions = null;
4254        }
4255
4256        // writer
4257        synchronized (mPackages) {
4258            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4259                // Check all shared libraries and map to their actual file path.
4260                // We only do this here for apps not on a system dir, because those
4261                // are the only ones that can fail an install due to this.  We
4262                // will take care of the system apps by updating all of their
4263                // library paths after the scan is done.
4264                if (!updateSharedLibrariesLPw(pkg, null)) {
4265                    return null;
4266                }
4267            }
4268
4269            if (pkg.mSharedUserId != null) {
4270                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4271                if (suid == null) {
4272                    Slog.w(TAG, "Creating application package " + pkg.packageName
4273                            + " for shared user failed");
4274                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4275                    return null;
4276                }
4277                if (DEBUG_PACKAGE_SCANNING) {
4278                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4279                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4280                                + "): packages=" + suid.packages);
4281                }
4282            }
4283
4284            // Check if we are renaming from an original package name.
4285            PackageSetting origPackage = null;
4286            String realName = null;
4287            if (pkg.mOriginalPackages != null) {
4288                // This package may need to be renamed to a previously
4289                // installed name.  Let's check on that...
4290                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4291                if (pkg.mOriginalPackages.contains(renamed)) {
4292                    // This package had originally been installed as the
4293                    // original name, and we have already taken care of
4294                    // transitioning to the new one.  Just update the new
4295                    // one to continue using the old name.
4296                    realName = pkg.mRealPackage;
4297                    if (!pkg.packageName.equals(renamed)) {
4298                        // Callers into this function may have already taken
4299                        // care of renaming the package; only do it here if
4300                        // it is not already done.
4301                        pkg.setPackageName(renamed);
4302                    }
4303
4304                } else {
4305                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4306                        if ((origPackage = mSettings.peekPackageLPr(
4307                                pkg.mOriginalPackages.get(i))) != null) {
4308                            // We do have the package already installed under its
4309                            // original name...  should we use it?
4310                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4311                                // New package is not compatible with original.
4312                                origPackage = null;
4313                                continue;
4314                            } else if (origPackage.sharedUser != null) {
4315                                // Make sure uid is compatible between packages.
4316                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4317                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4318                                            + " to " + pkg.packageName + ": old uid "
4319                                            + origPackage.sharedUser.name
4320                                            + " differs from " + pkg.mSharedUserId);
4321                                    origPackage = null;
4322                                    continue;
4323                                }
4324                            } else {
4325                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4326                                        + pkg.packageName + " to old name " + origPackage.name);
4327                            }
4328                            break;
4329                        }
4330                    }
4331                }
4332            }
4333
4334            if (mTransferedPackages.contains(pkg.packageName)) {
4335                Slog.w(TAG, "Package " + pkg.packageName
4336                        + " was transferred to another, but its .apk remains");
4337            }
4338
4339            // Just create the setting, don't add it yet. For already existing packages
4340            // the PkgSetting exists already and doesn't have to be created.
4341            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4342                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4343                    pkg.applicationInfo.flags, user, false);
4344            if (pkgSetting == null) {
4345                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4346                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4347                return null;
4348            }
4349
4350            if (pkgSetting.origPackage != null) {
4351                // If we are first transitioning from an original package,
4352                // fix up the new package's name now.  We need to do this after
4353                // looking up the package under its new name, so getPackageLP
4354                // can take care of fiddling things correctly.
4355                pkg.setPackageName(origPackage.name);
4356
4357                // File a report about this.
4358                String msg = "New package " + pkgSetting.realName
4359                        + " renamed to replace old package " + pkgSetting.name;
4360                reportSettingsProblem(Log.WARN, msg);
4361
4362                // Make a note of it.
4363                mTransferedPackages.add(origPackage.name);
4364
4365                // No longer need to retain this.
4366                pkgSetting.origPackage = null;
4367            }
4368
4369            if (realName != null) {
4370                // Make a note of it.
4371                mTransferedPackages.add(pkg.packageName);
4372            }
4373
4374            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4375                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4376            }
4377
4378            if (mFoundPolicyFile) {
4379                SELinuxMMAC.assignSeinfoValue(pkg);
4380            }
4381
4382            pkg.applicationInfo.uid = pkgSetting.appId;
4383            pkg.mExtras = pkgSetting;
4384
4385            if (!verifySignaturesLP(pkgSetting, pkg)) {
4386                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4387                    return null;
4388                }
4389                // The signature has changed, but this package is in the system
4390                // image...  let's recover!
4391                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4392                // However...  if this package is part of a shared user, but it
4393                // doesn't match the signature of the shared user, let's fail.
4394                // What this means is that you can't change the signatures
4395                // associated with an overall shared user, which doesn't seem all
4396                // that unreasonable.
4397                if (pkgSetting.sharedUser != null) {
4398                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4399                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4400                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4401                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4402                        return null;
4403                    }
4404                }
4405                // File a report about this.
4406                String msg = "System package " + pkg.packageName
4407                        + " signature changed; retaining data.";
4408                reportSettingsProblem(Log.WARN, msg);
4409            }
4410
4411            // Verify that this new package doesn't have any content providers
4412            // that conflict with existing packages.  Only do this if the
4413            // package isn't already installed, since we don't want to break
4414            // things that are installed.
4415            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4416                final int N = pkg.providers.size();
4417                int i;
4418                for (i=0; i<N; i++) {
4419                    PackageParser.Provider p = pkg.providers.get(i);
4420                    if (p.info.authority != null) {
4421                        String names[] = p.info.authority.split(";");
4422                        for (int j = 0; j < names.length; j++) {
4423                            if (mProvidersByAuthority.containsKey(names[j])) {
4424                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4425                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4426                                        " (in package " + pkg.applicationInfo.packageName +
4427                                        ") is already used by "
4428                                        + ((other != null && other.getComponentName() != null)
4429                                                ? other.getComponentName().getPackageName() : "?"));
4430                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4431                                return null;
4432                            }
4433                        }
4434                    }
4435                }
4436            }
4437
4438            if (pkg.mAdoptPermissions != null) {
4439                // This package wants to adopt ownership of permissions from
4440                // another package.
4441                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4442                    final String origName = pkg.mAdoptPermissions.get(i);
4443                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4444                    if (orig != null) {
4445                        if (verifyPackageUpdateLPr(orig, pkg)) {
4446                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4447                                    + pkg.packageName);
4448                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4449                        }
4450                    }
4451                }
4452            }
4453        }
4454
4455        final String pkgName = pkg.packageName;
4456
4457        final long scanFileTime = scanFile.lastModified();
4458        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4459        pkg.applicationInfo.processName = fixProcessName(
4460                pkg.applicationInfo.packageName,
4461                pkg.applicationInfo.processName,
4462                pkg.applicationInfo.uid);
4463
4464        File dataPath;
4465        if (mPlatformPackage == pkg) {
4466            // The system package is special.
4467            dataPath = new File (Environment.getDataDirectory(), "system");
4468            pkg.applicationInfo.dataDir = dataPath.getPath();
4469        } else {
4470            // This is a normal package, need to make its data directory.
4471            dataPath = getDataPathForPackage(pkg.packageName, 0);
4472
4473            boolean uidError = false;
4474
4475            if (dataPath.exists()) {
4476                int currentUid = 0;
4477                try {
4478                    StructStat stat = Libcore.os.stat(dataPath.getPath());
4479                    currentUid = stat.st_uid;
4480                } catch (ErrnoException e) {
4481                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4482                }
4483
4484                // If we have mismatched owners for the data path, we have a problem.
4485                if (currentUid != pkg.applicationInfo.uid) {
4486                    boolean recovered = false;
4487                    if (currentUid == 0) {
4488                        // The directory somehow became owned by root.  Wow.
4489                        // This is probably because the system was stopped while
4490                        // installd was in the middle of messing with its libs
4491                        // directory.  Ask installd to fix that.
4492                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4493                                pkg.applicationInfo.uid);
4494                        if (ret >= 0) {
4495                            recovered = true;
4496                            String msg = "Package " + pkg.packageName
4497                                    + " unexpectedly changed to uid 0; recovered to " +
4498                                    + pkg.applicationInfo.uid;
4499                            reportSettingsProblem(Log.WARN, msg);
4500                        }
4501                    }
4502                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4503                            || (scanMode&SCAN_BOOTING) != 0)) {
4504                        // If this is a system app, we can at least delete its
4505                        // current data so the application will still work.
4506                        int ret = removeDataDirsLI(pkgName);
4507                        if (ret >= 0) {
4508                            // TODO: Kill the processes first
4509                            // Old data gone!
4510                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4511                                    ? "System package " : "Third party package ";
4512                            String msg = prefix + pkg.packageName
4513                                    + " has changed from uid: "
4514                                    + currentUid + " to "
4515                                    + pkg.applicationInfo.uid + "; old data erased";
4516                            reportSettingsProblem(Log.WARN, msg);
4517                            recovered = true;
4518
4519                            // And now re-install the app.
4520                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4521                                                   pkg.applicationInfo.seinfo);
4522                            if (ret == -1) {
4523                                // Ack should not happen!
4524                                msg = prefix + pkg.packageName
4525                                        + " could not have data directory re-created after delete.";
4526                                reportSettingsProblem(Log.WARN, msg);
4527                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4528                                return null;
4529                            }
4530                        }
4531                        if (!recovered) {
4532                            mHasSystemUidErrors = true;
4533                        }
4534                    } else if (!recovered) {
4535                        // If we allow this install to proceed, we will be broken.
4536                        // Abort, abort!
4537                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4538                        return null;
4539                    }
4540                    if (!recovered) {
4541                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4542                            + pkg.applicationInfo.uid + "/fs_"
4543                            + currentUid;
4544                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4545                        String msg = "Package " + pkg.packageName
4546                                + " has mismatched uid: "
4547                                + currentUid + " on disk, "
4548                                + pkg.applicationInfo.uid + " in settings";
4549                        // writer
4550                        synchronized (mPackages) {
4551                            mSettings.mReadMessages.append(msg);
4552                            mSettings.mReadMessages.append('\n');
4553                            uidError = true;
4554                            if (!pkgSetting.uidError) {
4555                                reportSettingsProblem(Log.ERROR, msg);
4556                            }
4557                        }
4558                    }
4559                }
4560                pkg.applicationInfo.dataDir = dataPath.getPath();
4561            } else {
4562                if (DEBUG_PACKAGE_SCANNING) {
4563                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4564                        Log.v(TAG, "Want this data dir: " + dataPath);
4565                }
4566                //invoke installer to do the actual installation
4567                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4568                                           pkg.applicationInfo.seinfo);
4569                if (ret < 0) {
4570                    // Error from installer
4571                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4572                    return null;
4573                }
4574
4575                if (dataPath.exists()) {
4576                    pkg.applicationInfo.dataDir = dataPath.getPath();
4577                } else {
4578                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4579                    pkg.applicationInfo.dataDir = null;
4580                }
4581            }
4582
4583            /*
4584             * Set the data dir to the default "/data/data/<package name>/lib"
4585             * if we got here without anyone telling us different (e.g., apps
4586             * stored on SD card have their native libraries stored in the ASEC
4587             * container with the APK).
4588             *
4589             * This happens during an upgrade from a package settings file that
4590             * doesn't have a native library path attribute at all.
4591             */
4592            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4593                if (pkgSetting.nativeLibraryPathString == null) {
4594                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4595                } else {
4596                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4597                }
4598            }
4599
4600            pkgSetting.uidError = uidError;
4601        }
4602
4603        String path = scanFile.getPath();
4604        /* Note: We don't want to unpack the native binaries for
4605         *        system applications, unless they have been updated
4606         *        (the binaries are already under /system/lib).
4607         *        Also, don't unpack libs for apps on the external card
4608         *        since they should have their libraries in the ASEC
4609         *        container already.
4610         *
4611         *        In other words, we're going to unpack the binaries
4612         *        only for non-system apps and system app upgrades.
4613         */
4614        if (pkg.applicationInfo.nativeLibraryDir != null) {
4615            try {
4616                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4617                final String dataPathString = dataPath.getCanonicalPath();
4618
4619                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4620                    /*
4621                     * Upgrading from a previous version of the OS sometimes
4622                     * leaves native libraries in the /data/data/<app>/lib
4623                     * directory for system apps even when they shouldn't be.
4624                     * Recent changes in the JNI library search path
4625                     * necessitates we remove those to match previous behavior.
4626                     */
4627                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4628                        Log.i(TAG, "removed obsolete native libraries for system package "
4629                                + path);
4630                    }
4631                } else {
4632                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4633                        /*
4634                         * Update native library dir if it starts with
4635                         * /data/data
4636                         */
4637                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4638                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
4639                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4640                        }
4641
4642                        try {
4643                            if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4644                                Slog.e(TAG, "Unable to copy native libraries");
4645                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4646                                return null;
4647                            }
4648                        } catch (IOException e) {
4649                            Slog.e(TAG, "Unable to copy native libraries", e);
4650                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4651                            return null;
4652                        }
4653                    }
4654
4655                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4656                    final int[] userIds = sUserManager.getUserIds();
4657                    synchronized (mInstallLock) {
4658                        for (int userId : userIds) {
4659                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4660                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4661                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4662                                        + ")");
4663                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4664                                return null;
4665                            }
4666                        }
4667                    }
4668                }
4669            } catch (IOException ioe) {
4670                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4671            }
4672        }
4673        pkg.mScanPath = path;
4674
4675        if ((scanMode&SCAN_NO_DEX) == 0) {
4676            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4677                    == DEX_OPT_FAILED) {
4678                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4679                    removeDataDirsLI(pkg.packageName);
4680                }
4681
4682                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4683                return null;
4684            }
4685        }
4686
4687        if (mFactoryTest && pkg.requestedPermissions.contains(
4688                android.Manifest.permission.FACTORY_TEST)) {
4689            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4690        }
4691
4692        ArrayList<PackageParser.Package> clientLibPkgs = null;
4693
4694        // writer
4695        synchronized (mPackages) {
4696            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4697                // Only system apps can add new shared libraries.
4698                if (pkg.libraryNames != null) {
4699                    for (int i=0; i<pkg.libraryNames.size(); i++) {
4700                        String name = pkg.libraryNames.get(i);
4701                        boolean allowed = false;
4702                        if (isUpdatedSystemApp(pkg)) {
4703                            // New library entries can only be added through the
4704                            // system image.  This is important to get rid of a lot
4705                            // of nasty edge cases: for example if we allowed a non-
4706                            // system update of the app to add a library, then uninstalling
4707                            // the update would make the library go away, and assumptions
4708                            // we made such as through app install filtering would now
4709                            // have allowed apps on the device which aren't compatible
4710                            // with it.  Better to just have the restriction here, be
4711                            // conservative, and create many fewer cases that can negatively
4712                            // impact the user experience.
4713                            final PackageSetting sysPs = mSettings
4714                                    .getDisabledSystemPkgLPr(pkg.packageName);
4715                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4716                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4717                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4718                                        allowed = true;
4719                                        allowed = true;
4720                                        break;
4721                                    }
4722                                }
4723                            }
4724                        } else {
4725                            allowed = true;
4726                        }
4727                        if (allowed) {
4728                            if (!mSharedLibraries.containsKey(name)) {
4729                                mSharedLibraries.put(name, new SharedLibraryEntry(null,
4730                                        pkg.packageName));
4731                            } else if (!name.equals(pkg.packageName)) {
4732                                Slog.w(TAG, "Package " + pkg.packageName + " library "
4733                                        + name + " already exists; skipping");
4734                            }
4735                        } else {
4736                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4737                                    + name + " that is not declared on system image; skipping");
4738                        }
4739                    }
4740                    if ((scanMode&SCAN_BOOTING) == 0) {
4741                        // If we are not booting, we need to update any applications
4742                        // that are clients of our shared library.  If we are booting,
4743                        // this will all be done once the scan is complete.
4744                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4745                    }
4746                }
4747            }
4748        }
4749
4750        // We also need to dexopt any apps that are dependent on this library.  Note that
4751        // if these fail, we should abort the install since installing the library will
4752        // result in some apps being broken.
4753        if (clientLibPkgs != null) {
4754            if ((scanMode&SCAN_NO_DEX) == 0) {
4755                for (int i=0; i<clientLibPkgs.size(); i++) {
4756                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
4757                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4758                            == DEX_OPT_FAILED) {
4759                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4760                            removeDataDirsLI(pkg.packageName);
4761                        }
4762
4763                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4764                        return null;
4765                    }
4766                }
4767            }
4768        }
4769
4770        // Request the ActivityManager to kill the process(only for existing packages)
4771        // so that we do not end up in a confused state while the user is still using the older
4772        // version of the application while the new one gets installed.
4773        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4774            // If the package lives in an asec, tell everyone that the container is going
4775            // away so they can clean up any references to its resources (which would prevent
4776            // vold from being able to unmount the asec)
4777            if (isForwardLocked(pkg) || isExternal(pkg)) {
4778                if (DEBUG_INSTALL) {
4779                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
4780                }
4781                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
4782                final ArrayList<String> pkgList = new ArrayList<String>(1);
4783                pkgList.add(pkg.applicationInfo.packageName);
4784                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
4785            }
4786
4787            // Post the request that it be killed now that the going-away broadcast is en route
4788            killApplication(pkg.applicationInfo.packageName,
4789                        pkg.applicationInfo.uid, "update pkg");
4790        }
4791
4792        // Also need to kill any apps that are dependent on the library.
4793        if (clientLibPkgs != null) {
4794            for (int i=0; i<clientLibPkgs.size(); i++) {
4795                PackageParser.Package clientPkg = clientLibPkgs.get(i);
4796                killApplication(clientPkg.applicationInfo.packageName,
4797                        clientPkg.applicationInfo.uid, "update lib");
4798            }
4799        }
4800
4801        // writer
4802        synchronized (mPackages) {
4803            // We don't expect installation to fail beyond this point,
4804            if ((scanMode&SCAN_MONITOR) != 0) {
4805                mAppDirs.put(pkg.mPath, pkg);
4806            }
4807            // Add the new setting to mSettings
4808            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
4809            // Add the new setting to mPackages
4810            mPackages.put(pkg.applicationInfo.packageName, pkg);
4811            // Make sure we don't accidentally delete its data.
4812            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4813            while (iter.hasNext()) {
4814                PackageCleanItem item = iter.next();
4815                if (pkgName.equals(item.packageName)) {
4816                    iter.remove();
4817                }
4818            }
4819
4820            // Take care of first install / last update times.
4821            if (currentTime != 0) {
4822                if (pkgSetting.firstInstallTime == 0) {
4823                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4824                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4825                    pkgSetting.lastUpdateTime = currentTime;
4826                }
4827            } else if (pkgSetting.firstInstallTime == 0) {
4828                // We need *something*.  Take time time stamp of the file.
4829                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4830            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4831                if (scanFileTime != pkgSetting.timeStamp) {
4832                    // A package on the system image has changed; consider this
4833                    // to be an update.
4834                    pkgSetting.lastUpdateTime = scanFileTime;
4835                }
4836            }
4837
4838            // Add the package's KeySets to the global KeySetManager
4839            KeySetManager ksm = mSettings.mKeySetManager;
4840            try {
4841                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
4842                if (pkg.mKeySetMapping != null) {
4843                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
4844                        if (entry.getValue() != null) {
4845                            ksm.addDefinedKeySetToPackage(pkg.packageName,
4846                                entry.getValue(), entry.getKey());
4847                        }
4848                    }
4849                }
4850            } catch (NullPointerException e) {
4851                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
4852            } catch (IllegalArgumentException e) {
4853                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
4854            }
4855
4856            int N = pkg.providers.size();
4857            StringBuilder r = null;
4858            int i;
4859            for (i=0; i<N; i++) {
4860                PackageParser.Provider p = pkg.providers.get(i);
4861                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4862                        p.info.processName, pkg.applicationInfo.uid);
4863                mProviders.addProvider(p);
4864                p.syncable = p.info.isSyncable;
4865                if (p.info.authority != null) {
4866                    String names[] = p.info.authority.split(";");
4867                    p.info.authority = null;
4868                    for (int j = 0; j < names.length; j++) {
4869                        if (j == 1 && p.syncable) {
4870                            // We only want the first authority for a provider to possibly be
4871                            // syncable, so if we already added this provider using a different
4872                            // authority clear the syncable flag. We copy the provider before
4873                            // changing it because the mProviders object contains a reference
4874                            // to a provider that we don't want to change.
4875                            // Only do this for the second authority since the resulting provider
4876                            // object can be the same for all future authorities for this provider.
4877                            p = new PackageParser.Provider(p);
4878                            p.syncable = false;
4879                        }
4880                        if (!mProvidersByAuthority.containsKey(names[j])) {
4881                            mProvidersByAuthority.put(names[j], p);
4882                            if (p.info.authority == null) {
4883                                p.info.authority = names[j];
4884                            } else {
4885                                p.info.authority = p.info.authority + ";" + names[j];
4886                            }
4887                            if (DEBUG_PACKAGE_SCANNING) {
4888                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4889                                    Log.d(TAG, "Registered content provider: " + names[j]
4890                                            + ", className = " + p.info.name + ", isSyncable = "
4891                                            + p.info.isSyncable);
4892                            }
4893                        } else {
4894                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4895                            Slog.w(TAG, "Skipping provider name " + names[j] +
4896                                    " (in package " + pkg.applicationInfo.packageName +
4897                                    "): name already used by "
4898                                    + ((other != null && other.getComponentName() != null)
4899                                            ? other.getComponentName().getPackageName() : "?"));
4900                        }
4901                    }
4902                }
4903                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4904                    if (r == null) {
4905                        r = new StringBuilder(256);
4906                    } else {
4907                        r.append(' ');
4908                    }
4909                    r.append(p.info.name);
4910                }
4911            }
4912            if (r != null) {
4913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
4914            }
4915
4916            N = pkg.services.size();
4917            r = null;
4918            for (i=0; i<N; i++) {
4919                PackageParser.Service s = pkg.services.get(i);
4920                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4921                        s.info.processName, pkg.applicationInfo.uid);
4922                mServices.addService(s);
4923                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4924                    if (r == null) {
4925                        r = new StringBuilder(256);
4926                    } else {
4927                        r.append(' ');
4928                    }
4929                    r.append(s.info.name);
4930                }
4931            }
4932            if (r != null) {
4933                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
4934            }
4935
4936            N = pkg.receivers.size();
4937            r = null;
4938            for (i=0; i<N; i++) {
4939                PackageParser.Activity a = pkg.receivers.get(i);
4940                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4941                        a.info.processName, pkg.applicationInfo.uid);
4942                mReceivers.addActivity(a, "receiver");
4943                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4944                    if (r == null) {
4945                        r = new StringBuilder(256);
4946                    } else {
4947                        r.append(' ');
4948                    }
4949                    r.append(a.info.name);
4950                }
4951            }
4952            if (r != null) {
4953                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
4954            }
4955
4956            N = pkg.activities.size();
4957            r = null;
4958            for (i=0; i<N; i++) {
4959                PackageParser.Activity a = pkg.activities.get(i);
4960                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4961                        a.info.processName, pkg.applicationInfo.uid);
4962                mActivities.addActivity(a, "activity");
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(a.info.name);
4970                }
4971            }
4972            if (r != null) {
4973                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
4974            }
4975
4976            N = pkg.permissionGroups.size();
4977            r = null;
4978            for (i=0; i<N; i++) {
4979                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4980                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4981                if (cur == null) {
4982                    mPermissionGroups.put(pg.info.name, pg);
4983                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4984                        if (r == null) {
4985                            r = new StringBuilder(256);
4986                        } else {
4987                            r.append(' ');
4988                        }
4989                        r.append(pg.info.name);
4990                    }
4991                } else {
4992                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
4993                            + pg.info.packageName + " ignored: original from "
4994                            + cur.info.packageName);
4995                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4996                        if (r == null) {
4997                            r = new StringBuilder(256);
4998                        } else {
4999                            r.append(' ');
5000                        }
5001                        r.append("DUP:");
5002                        r.append(pg.info.name);
5003                    }
5004                }
5005            }
5006            if (r != null) {
5007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5008            }
5009
5010            N = pkg.permissions.size();
5011            r = null;
5012            for (i=0; i<N; i++) {
5013                PackageParser.Permission p = pkg.permissions.get(i);
5014                HashMap<String, BasePermission> permissionMap =
5015                        p.tree ? mSettings.mPermissionTrees
5016                        : mSettings.mPermissions;
5017                p.group = mPermissionGroups.get(p.info.group);
5018                if (p.info.group == null || p.group != null) {
5019                    BasePermission bp = permissionMap.get(p.info.name);
5020                    if (bp == null) {
5021                        bp = new BasePermission(p.info.name, p.info.packageName,
5022                                BasePermission.TYPE_NORMAL);
5023                        permissionMap.put(p.info.name, bp);
5024                    }
5025                    if (bp.perm == null) {
5026                        if (bp.sourcePackage != null
5027                                && !bp.sourcePackage.equals(p.info.packageName)) {
5028                            // If this is a permission that was formerly defined by a non-system
5029                            // app, but is now defined by a system app (following an upgrade),
5030                            // discard the previous declaration and consider the system's to be
5031                            // canonical.
5032                            if (isSystemApp(p.owner)) {
5033                                Slog.i(TAG, "New decl " + p.owner + " of permission  "
5034                                        + p.info.name + " is system");
5035                                bp.sourcePackage = null;
5036                            }
5037                        }
5038                        if (bp.sourcePackage == null
5039                                || bp.sourcePackage.equals(p.info.packageName)) {
5040                            BasePermission tree = findPermissionTreeLP(p.info.name);
5041                            if (tree == null
5042                                    || tree.sourcePackage.equals(p.info.packageName)) {
5043                                bp.packageSetting = pkgSetting;
5044                                bp.perm = p;
5045                                bp.uid = pkg.applicationInfo.uid;
5046                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5047                                    if (r == null) {
5048                                        r = new StringBuilder(256);
5049                                    } else {
5050                                        r.append(' ');
5051                                    }
5052                                    r.append(p.info.name);
5053                                }
5054                            } else {
5055                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5056                                        + p.info.packageName + " ignored: base tree "
5057                                        + tree.name + " is from package "
5058                                        + tree.sourcePackage);
5059                            }
5060                        } else {
5061                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5062                                    + p.info.packageName + " ignored: original from "
5063                                    + bp.sourcePackage);
5064                        }
5065                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5066                        if (r == null) {
5067                            r = new StringBuilder(256);
5068                        } else {
5069                            r.append(' ');
5070                        }
5071                        r.append("DUP:");
5072                        r.append(p.info.name);
5073                    }
5074                    if (bp.perm == p) {
5075                        bp.protectionLevel = p.info.protectionLevel;
5076                    }
5077                } else {
5078                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5079                            + p.info.packageName + " ignored: no group "
5080                            + p.group);
5081                }
5082            }
5083            if (r != null) {
5084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5085            }
5086
5087            N = pkg.instrumentation.size();
5088            r = null;
5089            for (i=0; i<N; i++) {
5090                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5091                a.info.packageName = pkg.applicationInfo.packageName;
5092                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5093                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5094                a.info.dataDir = pkg.applicationInfo.dataDir;
5095                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5096                mInstrumentation.put(a.getComponentName(), a);
5097                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5098                    if (r == null) {
5099                        r = new StringBuilder(256);
5100                    } else {
5101                        r.append(' ');
5102                    }
5103                    r.append(a.info.name);
5104                }
5105            }
5106            if (r != null) {
5107                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5108            }
5109
5110            if (pkg.protectedBroadcasts != null) {
5111                N = pkg.protectedBroadcasts.size();
5112                for (i=0; i<N; i++) {
5113                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5114                }
5115            }
5116
5117            pkgSetting.setTimeStamp(scanFileTime);
5118        }
5119
5120        return pkg;
5121    }
5122
5123    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5124        synchronized (mPackages) {
5125            mResolverReplaced = true;
5126            // Set up information for custom user intent resolution activity.
5127            mResolveActivity.applicationInfo = pkg.applicationInfo;
5128            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5129            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5130            mResolveActivity.processName = null;
5131            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5132            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5133                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5134            mResolveActivity.theme = 0;
5135            mResolveActivity.exported = true;
5136            mResolveActivity.enabled = true;
5137            mResolveInfo.activityInfo = mResolveActivity;
5138            mResolveInfo.priority = 0;
5139            mResolveInfo.preferredOrder = 0;
5140            mResolveInfo.match = 0;
5141            mResolveComponentName = mCustomResolverComponentName;
5142            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5143                    mResolveComponentName);
5144        }
5145    }
5146
5147    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5148            PackageSetting pkgSetting) {
5149        final String apkLibPath = getApkName(pkgSetting.codePathString);
5150        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
5151        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5152        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5153    }
5154
5155    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5156            throws IOException {
5157        if (!nativeLibraryDir.isDirectory()) {
5158            nativeLibraryDir.delete();
5159
5160            if (!nativeLibraryDir.mkdir()) {
5161                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5162            }
5163
5164            try {
5165                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
5166                        | S_IXOTH);
5167            } catch (ErrnoException e) {
5168                throw new IOException("Cannot chmod native library directory "
5169                        + nativeLibraryDir.getPath(), e);
5170            }
5171        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5172            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5173        }
5174
5175        /*
5176         * If this is an internal application or our nativeLibraryPath points to
5177         * the app-lib directory, unpack the libraries if necessary.
5178         */
5179        return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
5180    }
5181
5182    private void killApplication(String pkgName, int appId, String reason) {
5183        // Request the ActivityManager to kill the process(only for existing packages)
5184        // so that we do not end up in a confused state while the user is still using the older
5185        // version of the application while the new one gets installed.
5186        IActivityManager am = ActivityManagerNative.getDefault();
5187        if (am != null) {
5188            try {
5189                am.killApplicationWithAppId(pkgName, appId, reason);
5190            } catch (RemoteException e) {
5191            }
5192        }
5193    }
5194
5195    void removePackageLI(PackageSetting ps, boolean chatty) {
5196        if (DEBUG_INSTALL) {
5197            if (chatty)
5198                Log.d(TAG, "Removing package " + ps.name);
5199        }
5200
5201        // writer
5202        synchronized (mPackages) {
5203            mPackages.remove(ps.name);
5204            if (ps.codePathString != null) {
5205                mAppDirs.remove(ps.codePathString);
5206            }
5207
5208            final PackageParser.Package pkg = ps.pkg;
5209            if (pkg != null) {
5210                cleanPackageDataStructuresLILPw(pkg, chatty);
5211            }
5212        }
5213    }
5214
5215    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5216        if (DEBUG_INSTALL) {
5217            if (chatty)
5218                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5219        }
5220
5221        // writer
5222        synchronized (mPackages) {
5223            mPackages.remove(pkg.applicationInfo.packageName);
5224            if (pkg.mPath != null) {
5225                mAppDirs.remove(pkg.mPath);
5226            }
5227            cleanPackageDataStructuresLILPw(pkg, chatty);
5228        }
5229    }
5230
5231    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5232        int N = pkg.providers.size();
5233        StringBuilder r = null;
5234        int i;
5235        for (i=0; i<N; i++) {
5236            PackageParser.Provider p = pkg.providers.get(i);
5237            mProviders.removeProvider(p);
5238            if (p.info.authority == null) {
5239
5240                /* There was another ContentProvider with this authority when
5241                 * this app was installed so this authority is null,
5242                 * Ignore it as we don't have to unregister the provider.
5243                 */
5244                continue;
5245            }
5246            String names[] = p.info.authority.split(";");
5247            for (int j = 0; j < names.length; j++) {
5248                if (mProvidersByAuthority.get(names[j]) == p) {
5249                    mProvidersByAuthority.remove(names[j]);
5250                    if (DEBUG_REMOVE) {
5251                        if (chatty)
5252                            Log.d(TAG, "Unregistered content provider: " + names[j]
5253                                    + ", className = " + p.info.name + ", isSyncable = "
5254                                    + p.info.isSyncable);
5255                    }
5256                }
5257            }
5258            if (DEBUG_REMOVE && chatty) {
5259                if (r == null) {
5260                    r = new StringBuilder(256);
5261                } else {
5262                    r.append(' ');
5263                }
5264                r.append(p.info.name);
5265            }
5266        }
5267        if (r != null) {
5268            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5269        }
5270
5271        N = pkg.services.size();
5272        r = null;
5273        for (i=0; i<N; i++) {
5274            PackageParser.Service s = pkg.services.get(i);
5275            mServices.removeService(s);
5276            if (chatty) {
5277                if (r == null) {
5278                    r = new StringBuilder(256);
5279                } else {
5280                    r.append(' ');
5281                }
5282                r.append(s.info.name);
5283            }
5284        }
5285        if (r != null) {
5286            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5287        }
5288
5289        N = pkg.receivers.size();
5290        r = null;
5291        for (i=0; i<N; i++) {
5292            PackageParser.Activity a = pkg.receivers.get(i);
5293            mReceivers.removeActivity(a, "receiver");
5294            if (DEBUG_REMOVE && chatty) {
5295                if (r == null) {
5296                    r = new StringBuilder(256);
5297                } else {
5298                    r.append(' ');
5299                }
5300                r.append(a.info.name);
5301            }
5302        }
5303        if (r != null) {
5304            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5305        }
5306
5307        N = pkg.activities.size();
5308        r = null;
5309        for (i=0; i<N; i++) {
5310            PackageParser.Activity a = pkg.activities.get(i);
5311            mActivities.removeActivity(a, "activity");
5312            if (DEBUG_REMOVE && chatty) {
5313                if (r == null) {
5314                    r = new StringBuilder(256);
5315                } else {
5316                    r.append(' ');
5317                }
5318                r.append(a.info.name);
5319            }
5320        }
5321        if (r != null) {
5322            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5323        }
5324
5325        N = pkg.permissions.size();
5326        r = null;
5327        for (i=0; i<N; i++) {
5328            PackageParser.Permission p = pkg.permissions.get(i);
5329            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5330            if (bp == null) {
5331                bp = mSettings.mPermissionTrees.get(p.info.name);
5332            }
5333            if (bp != null && bp.perm == p) {
5334                bp.perm = null;
5335                if (DEBUG_REMOVE && chatty) {
5336                    if (r == null) {
5337                        r = new StringBuilder(256);
5338                    } else {
5339                        r.append(' ');
5340                    }
5341                    r.append(p.info.name);
5342                }
5343            }
5344        }
5345        if (r != null) {
5346            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5347        }
5348
5349        N = pkg.instrumentation.size();
5350        r = null;
5351        for (i=0; i<N; i++) {
5352            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5353            mInstrumentation.remove(a.getComponentName());
5354            if (DEBUG_REMOVE && chatty) {
5355                if (r == null) {
5356                    r = new StringBuilder(256);
5357                } else {
5358                    r.append(' ');
5359                }
5360                r.append(a.info.name);
5361            }
5362        }
5363        if (r != null) {
5364            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5365        }
5366
5367        r = null;
5368        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5369            // Only system apps can hold shared libraries.
5370            if (pkg.libraryNames != null) {
5371                for (i=0; i<pkg.libraryNames.size(); i++) {
5372                    String name = pkg.libraryNames.get(i);
5373                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5374                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5375                        mSharedLibraries.remove(name);
5376                        if (DEBUG_REMOVE && chatty) {
5377                            if (r == null) {
5378                                r = new StringBuilder(256);
5379                            } else {
5380                                r.append(' ');
5381                            }
5382                            r.append(name);
5383                        }
5384                    }
5385                }
5386            }
5387        }
5388        if (r != null) {
5389            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5390        }
5391    }
5392
5393    private static final boolean isPackageFilename(String name) {
5394        return name != null && name.endsWith(".apk");
5395    }
5396
5397    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5398        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5399            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5400                return true;
5401            }
5402        }
5403        return false;
5404    }
5405
5406    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5407    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5408    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5409
5410    private void updatePermissionsLPw(String changingPkg,
5411            PackageParser.Package pkgInfo, int flags) {
5412        // Make sure there are no dangling permission trees.
5413        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5414        while (it.hasNext()) {
5415            final BasePermission bp = it.next();
5416            if (bp.packageSetting == null) {
5417                // We may not yet have parsed the package, so just see if
5418                // we still know about its settings.
5419                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5420            }
5421            if (bp.packageSetting == null) {
5422                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5423                        + " from package " + bp.sourcePackage);
5424                it.remove();
5425            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5426                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5427                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5428                            + " from package " + bp.sourcePackage);
5429                    flags |= UPDATE_PERMISSIONS_ALL;
5430                    it.remove();
5431                }
5432            }
5433        }
5434
5435        // Make sure all dynamic permissions have been assigned to a package,
5436        // and make sure there are no dangling permissions.
5437        it = mSettings.mPermissions.values().iterator();
5438        while (it.hasNext()) {
5439            final BasePermission bp = it.next();
5440            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5441                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5442                        + bp.name + " pkg=" + bp.sourcePackage
5443                        + " info=" + bp.pendingInfo);
5444                if (bp.packageSetting == null && bp.pendingInfo != null) {
5445                    final BasePermission tree = findPermissionTreeLP(bp.name);
5446                    if (tree != null && tree.perm != null) {
5447                        bp.packageSetting = tree.packageSetting;
5448                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5449                                new PermissionInfo(bp.pendingInfo));
5450                        bp.perm.info.packageName = tree.perm.info.packageName;
5451                        bp.perm.info.name = bp.name;
5452                        bp.uid = tree.uid;
5453                    }
5454                }
5455            }
5456            if (bp.packageSetting == null) {
5457                // We may not yet have parsed the package, so just see if
5458                // we still know about its settings.
5459                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5460            }
5461            if (bp.packageSetting == null) {
5462                Slog.w(TAG, "Removing dangling permission: " + bp.name
5463                        + " from package " + bp.sourcePackage);
5464                it.remove();
5465            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5466                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5467                    Slog.i(TAG, "Removing old permission: " + bp.name
5468                            + " from package " + bp.sourcePackage);
5469                    flags |= UPDATE_PERMISSIONS_ALL;
5470                    it.remove();
5471                }
5472            }
5473        }
5474
5475        // Now update the permissions for all packages, in particular
5476        // replace the granted permissions of the system packages.
5477        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5478            for (PackageParser.Package pkg : mPackages.values()) {
5479                if (pkg != pkgInfo) {
5480                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5481                }
5482            }
5483        }
5484
5485        if (pkgInfo != null) {
5486            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5487        }
5488    }
5489
5490    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5491        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5492        if (ps == null) {
5493            return;
5494        }
5495        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5496        HashSet<String> origPermissions = gp.grantedPermissions;
5497        boolean changedPermission = false;
5498
5499        if (replace) {
5500            ps.permissionsFixed = false;
5501            if (gp == ps) {
5502                origPermissions = new HashSet<String>(gp.grantedPermissions);
5503                gp.grantedPermissions.clear();
5504                gp.gids = mGlobalGids;
5505            }
5506        }
5507
5508        if (gp.gids == null) {
5509            gp.gids = mGlobalGids;
5510        }
5511
5512        final int N = pkg.requestedPermissions.size();
5513        for (int i=0; i<N; i++) {
5514            final String name = pkg.requestedPermissions.get(i);
5515            final boolean required = pkg.requestedPermissionsRequired.get(i);
5516            final BasePermission bp = mSettings.mPermissions.get(name);
5517            if (DEBUG_INSTALL) {
5518                if (gp != ps) {
5519                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5520                }
5521            }
5522
5523            if (bp == null || bp.packageSetting == null) {
5524                Slog.w(TAG, "Unknown permission " + name
5525                        + " in package " + pkg.packageName);
5526                continue;
5527            }
5528
5529            final String perm = bp.name;
5530            boolean allowed;
5531            boolean allowedSig = false;
5532            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5533            if (level == PermissionInfo.PROTECTION_NORMAL
5534                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5535                // We grant a normal or dangerous permission if any of the following
5536                // are true:
5537                // 1) The permission is required
5538                // 2) The permission is optional, but was granted in the past
5539                // 3) The permission is optional, but was requested by an
5540                //    app in /system (not /data)
5541                //
5542                // Otherwise, reject the permission.
5543                allowed = (required || origPermissions.contains(perm)
5544                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5545            } else if (bp.packageSetting == null) {
5546                // This permission is invalid; skip it.
5547                allowed = false;
5548            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5549                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5550                if (allowed) {
5551                    allowedSig = true;
5552                }
5553            } else {
5554                allowed = false;
5555            }
5556            if (DEBUG_INSTALL) {
5557                if (gp != ps) {
5558                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5559                }
5560            }
5561            if (allowed) {
5562                if (!isSystemApp(ps) && ps.permissionsFixed) {
5563                    // If this is an existing, non-system package, then
5564                    // we can't add any new permissions to it.
5565                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5566                        // Except...  if this is a permission that was added
5567                        // to the platform (note: need to only do this when
5568                        // updating the platform).
5569                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5570                    }
5571                }
5572                if (allowed) {
5573                    if (!gp.grantedPermissions.contains(perm)) {
5574                        changedPermission = true;
5575                        gp.grantedPermissions.add(perm);
5576                        gp.gids = appendInts(gp.gids, bp.gids);
5577                    } else if (!ps.haveGids) {
5578                        gp.gids = appendInts(gp.gids, bp.gids);
5579                    }
5580                } else {
5581                    Slog.w(TAG, "Not granting permission " + perm
5582                            + " to package " + pkg.packageName
5583                            + " because it was previously installed without");
5584                }
5585            } else {
5586                if (gp.grantedPermissions.remove(perm)) {
5587                    changedPermission = true;
5588                    gp.gids = removeInts(gp.gids, bp.gids);
5589                    Slog.i(TAG, "Un-granting permission " + perm
5590                            + " from package " + pkg.packageName
5591                            + " (protectionLevel=" + bp.protectionLevel
5592                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5593                            + ")");
5594                } else {
5595                    Slog.w(TAG, "Not granting permission " + perm
5596                            + " to package " + pkg.packageName
5597                            + " (protectionLevel=" + bp.protectionLevel
5598                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5599                            + ")");
5600                }
5601            }
5602        }
5603
5604        if ((changedPermission || replace) && !ps.permissionsFixed &&
5605                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
5606            // This is the first that we have heard about this package, so the
5607            // permissions we have now selected are fixed until explicitly
5608            // changed.
5609            ps.permissionsFixed = true;
5610        }
5611        ps.haveGids = true;
5612    }
5613
5614    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5615        boolean allowed = false;
5616        final int NP = PackageParser.NEW_PERMISSIONS.length;
5617        for (int ip=0; ip<NP; ip++) {
5618            final PackageParser.NewPermissionInfo npi
5619                    = PackageParser.NEW_PERMISSIONS[ip];
5620            if (npi.name.equals(perm)
5621                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5622                allowed = true;
5623                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5624                        + pkg.packageName);
5625                break;
5626            }
5627        }
5628        return allowed;
5629    }
5630
5631    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
5632                                          BasePermission bp, HashSet<String> origPermissions) {
5633        boolean allowed;
5634        allowed = (compareSignatures(
5635                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5636                        == PackageManager.SIGNATURE_MATCH)
5637                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5638                        == PackageManager.SIGNATURE_MATCH);
5639        if (!allowed && (bp.protectionLevel
5640                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5641            if (isSystemApp(pkg)) {
5642                // For updated system applications, a system permission
5643                // is granted only if it had been defined by the original application.
5644                if (isUpdatedSystemApp(pkg)) {
5645                    final PackageSetting sysPs = mSettings
5646                            .getDisabledSystemPkgLPr(pkg.packageName);
5647                    final GrantedPermissions origGp = sysPs.sharedUser != null
5648                            ? sysPs.sharedUser : sysPs;
5649
5650                    if (origGp.grantedPermissions.contains(perm)) {
5651                        // If the original was granted this permission, we take
5652                        // that grant decision as read and propagate it to the
5653                        // update.
5654                        allowed = true;
5655                    } else {
5656                        // The system apk may have been updated with an older
5657                        // version of the one on the data partition, but which
5658                        // granted a new system permission that it didn't have
5659                        // before.  In this case we do want to allow the app to
5660                        // now get the new permission if the ancestral apk is
5661                        // privileged to get it.
5662                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
5663                            for (int j=0;
5664                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
5665                                if (perm.equals(
5666                                        sysPs.pkg.requestedPermissions.get(j))) {
5667                                    allowed = true;
5668                                    break;
5669                                }
5670                            }
5671                        }
5672                    }
5673                } else {
5674                    allowed = isPrivilegedApp(pkg);
5675                }
5676            }
5677        }
5678        if (!allowed && (bp.protectionLevel
5679                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5680            // For development permissions, a development permission
5681            // is granted only if it was already granted.
5682            allowed = origPermissions.contains(perm);
5683        }
5684        return allowed;
5685    }
5686
5687    final class ActivityIntentResolver
5688            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
5689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5690                boolean defaultOnly, int userId) {
5691            if (!sUserManager.exists(userId)) return null;
5692            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5693            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5694        }
5695
5696        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5697                int userId) {
5698            if (!sUserManager.exists(userId)) return null;
5699            mFlags = flags;
5700            return super.queryIntent(intent, resolvedType,
5701                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5702        }
5703
5704        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5705                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
5706            if (!sUserManager.exists(userId)) return null;
5707            if (packageActivities == null) {
5708                return null;
5709            }
5710            mFlags = flags;
5711            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5712            final int N = packageActivities.size();
5713            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
5714                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
5715
5716            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
5717            for (int i = 0; i < N; ++i) {
5718                intentFilters = packageActivities.get(i).intents;
5719                if (intentFilters != null && intentFilters.size() > 0) {
5720                    PackageParser.ActivityIntentInfo[] array =
5721                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
5722                    intentFilters.toArray(array);
5723                    listCut.add(array);
5724                }
5725            }
5726            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5727        }
5728
5729        public final void addActivity(PackageParser.Activity a, String type) {
5730            final boolean systemApp = isSystemApp(a.info.applicationInfo);
5731            mActivities.put(a.getComponentName(), a);
5732            if (DEBUG_SHOW_INFO)
5733                Log.v(
5734                TAG, "  " + type + " " +
5735                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
5736            if (DEBUG_SHOW_INFO)
5737                Log.v(TAG, "    Class=" + a.info.name);
5738            final int NI = a.intents.size();
5739            for (int j=0; j<NI; j++) {
5740                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5741                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
5742                    intent.setPriority(0);
5743                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5744                            + a.className + " with priority > 0, forcing to 0");
5745                }
5746                if (DEBUG_SHOW_INFO) {
5747                    Log.v(TAG, "    IntentFilter:");
5748                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5749                }
5750                if (!intent.debugCheck()) {
5751                    Log.w(TAG, "==> For Activity " + a.info.name);
5752                }
5753                addFilter(intent);
5754            }
5755        }
5756
5757        public final void removeActivity(PackageParser.Activity a, String type) {
5758            mActivities.remove(a.getComponentName());
5759            if (DEBUG_SHOW_INFO) {
5760                Log.v(TAG, "  " + type + " "
5761                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5762                                : a.info.name) + ":");
5763                Log.v(TAG, "    Class=" + a.info.name);
5764            }
5765            final int NI = a.intents.size();
5766            for (int j=0; j<NI; j++) {
5767                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5768                if (DEBUG_SHOW_INFO) {
5769                    Log.v(TAG, "    IntentFilter:");
5770                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5771                }
5772                removeFilter(intent);
5773            }
5774        }
5775
5776        @Override
5777        protected boolean allowFilterResult(
5778                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5779            ActivityInfo filterAi = filter.activity.info;
5780            for (int i=dest.size()-1; i>=0; i--) {
5781                ActivityInfo destAi = dest.get(i).activityInfo;
5782                if (destAi.name == filterAi.name
5783                        && destAi.packageName == filterAi.packageName) {
5784                    return false;
5785                }
5786            }
5787            return true;
5788        }
5789
5790        @Override
5791        protected ActivityIntentInfo[] newArray(int size) {
5792            return new ActivityIntentInfo[size];
5793        }
5794
5795        @Override
5796        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
5797            if (!sUserManager.exists(userId)) return true;
5798            PackageParser.Package p = filter.activity.owner;
5799            if (p != null) {
5800                PackageSetting ps = (PackageSetting)p.mExtras;
5801                if (ps != null) {
5802                    // System apps are never considered stopped for purposes of
5803                    // filtering, because there may be no way for the user to
5804                    // actually re-launch them.
5805                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5806                            && ps.getStopped(userId);
5807                }
5808            }
5809            return false;
5810        }
5811
5812        @Override
5813        protected boolean isPackageForFilter(String packageName,
5814                PackageParser.ActivityIntentInfo info) {
5815            return packageName.equals(info.activity.owner.packageName);
5816        }
5817
5818        @Override
5819        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
5820                int match, int userId) {
5821            if (!sUserManager.exists(userId)) return null;
5822            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
5823                return null;
5824            }
5825            final PackageParser.Activity activity = info.activity;
5826            if (mSafeMode && (activity.info.applicationInfo.flags
5827                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5828                return null;
5829            }
5830            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
5831            if (ps == null) {
5832                return null;
5833            }
5834            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5835                    ps.readUserState(userId), userId);
5836            if (ai == null) {
5837                return null;
5838            }
5839            final ResolveInfo res = new ResolveInfo();
5840            res.activityInfo = ai;
5841            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5842                res.filter = info;
5843            }
5844            res.priority = info.getPriority();
5845            res.preferredOrder = activity.owner.mPreferredOrder;
5846            //System.out.println("Result: " + res.activityInfo.className +
5847            //                   " = " + res.priority);
5848            res.match = match;
5849            res.isDefault = info.hasDefault;
5850            res.labelRes = info.labelRes;
5851            res.nonLocalizedLabel = info.nonLocalizedLabel;
5852            res.icon = info.icon;
5853            res.system = isSystemApp(res.activityInfo.applicationInfo);
5854            return res;
5855        }
5856
5857        @Override
5858        protected void sortResults(List<ResolveInfo> results) {
5859            Collections.sort(results, mResolvePrioritySorter);
5860        }
5861
5862        @Override
5863        protected void dumpFilter(PrintWriter out, String prefix,
5864                PackageParser.ActivityIntentInfo filter) {
5865            out.print(prefix); out.print(
5866                    Integer.toHexString(System.identityHashCode(filter.activity)));
5867                    out.print(' ');
5868                    filter.activity.printComponentShortName(out);
5869                    out.print(" filter ");
5870                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5871        }
5872
5873//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5874//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5875//            final List<ResolveInfo> retList = Lists.newArrayList();
5876//            while (i.hasNext()) {
5877//                final ResolveInfo resolveInfo = i.next();
5878//                if (isEnabledLP(resolveInfo.activityInfo)) {
5879//                    retList.add(resolveInfo);
5880//                }
5881//            }
5882//            return retList;
5883//        }
5884
5885        // Keys are String (activity class name), values are Activity.
5886        private final HashMap<ComponentName, PackageParser.Activity> mActivities
5887                = new HashMap<ComponentName, PackageParser.Activity>();
5888        private int mFlags;
5889    }
5890
5891    private final class ServiceIntentResolver
5892            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
5893        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5894                boolean defaultOnly, int userId) {
5895            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5896            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5897        }
5898
5899        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5900                int userId) {
5901            if (!sUserManager.exists(userId)) return null;
5902            mFlags = flags;
5903            return super.queryIntent(intent, resolvedType,
5904                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5905        }
5906
5907        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5908                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
5909            if (!sUserManager.exists(userId)) return null;
5910            if (packageServices == null) {
5911                return null;
5912            }
5913            mFlags = flags;
5914            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5915            final int N = packageServices.size();
5916            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5917                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
5918
5919            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5920            for (int i = 0; i < N; ++i) {
5921                intentFilters = packageServices.get(i).intents;
5922                if (intentFilters != null && intentFilters.size() > 0) {
5923                    PackageParser.ServiceIntentInfo[] array =
5924                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
5925                    intentFilters.toArray(array);
5926                    listCut.add(array);
5927                }
5928            }
5929            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5930        }
5931
5932        public final void addService(PackageParser.Service s) {
5933            mServices.put(s.getComponentName(), s);
5934            if (DEBUG_SHOW_INFO) {
5935                Log.v(TAG, "  "
5936                        + (s.info.nonLocalizedLabel != null
5937                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5938                Log.v(TAG, "    Class=" + s.info.name);
5939            }
5940            final int NI = s.intents.size();
5941            int j;
5942            for (j=0; j<NI; j++) {
5943                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5944                if (DEBUG_SHOW_INFO) {
5945                    Log.v(TAG, "    IntentFilter:");
5946                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5947                }
5948                if (!intent.debugCheck()) {
5949                    Log.w(TAG, "==> For Service " + s.info.name);
5950                }
5951                addFilter(intent);
5952            }
5953        }
5954
5955        public final void removeService(PackageParser.Service s) {
5956            mServices.remove(s.getComponentName());
5957            if (DEBUG_SHOW_INFO) {
5958                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
5959                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5960                Log.v(TAG, "    Class=" + s.info.name);
5961            }
5962            final int NI = s.intents.size();
5963            int j;
5964            for (j=0; j<NI; j++) {
5965                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5966                if (DEBUG_SHOW_INFO) {
5967                    Log.v(TAG, "    IntentFilter:");
5968                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5969                }
5970                removeFilter(intent);
5971            }
5972        }
5973
5974        @Override
5975        protected boolean allowFilterResult(
5976                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5977            ServiceInfo filterSi = filter.service.info;
5978            for (int i=dest.size()-1; i>=0; i--) {
5979                ServiceInfo destAi = dest.get(i).serviceInfo;
5980                if (destAi.name == filterSi.name
5981                        && destAi.packageName == filterSi.packageName) {
5982                    return false;
5983                }
5984            }
5985            return true;
5986        }
5987
5988        @Override
5989        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5990            return new PackageParser.ServiceIntentInfo[size];
5991        }
5992
5993        @Override
5994        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
5995            if (!sUserManager.exists(userId)) return true;
5996            PackageParser.Package p = filter.service.owner;
5997            if (p != null) {
5998                PackageSetting ps = (PackageSetting)p.mExtras;
5999                if (ps != null) {
6000                    // System apps are never considered stopped for purposes of
6001                    // filtering, because there may be no way for the user to
6002                    // actually re-launch them.
6003                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6004                            && ps.getStopped(userId);
6005                }
6006            }
6007            return false;
6008        }
6009
6010        @Override
6011        protected boolean isPackageForFilter(String packageName,
6012                PackageParser.ServiceIntentInfo info) {
6013            return packageName.equals(info.service.owner.packageName);
6014        }
6015
6016        @Override
6017        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6018                int match, int userId) {
6019            if (!sUserManager.exists(userId)) return null;
6020            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6021            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6022                return null;
6023            }
6024            final PackageParser.Service service = info.service;
6025            if (mSafeMode && (service.info.applicationInfo.flags
6026                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6027                return null;
6028            }
6029            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6030            if (ps == null) {
6031                return null;
6032            }
6033            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6034                    ps.readUserState(userId), userId);
6035            if (si == null) {
6036                return null;
6037            }
6038            final ResolveInfo res = new ResolveInfo();
6039            res.serviceInfo = si;
6040            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6041                res.filter = filter;
6042            }
6043            res.priority = info.getPriority();
6044            res.preferredOrder = service.owner.mPreferredOrder;
6045            //System.out.println("Result: " + res.activityInfo.className +
6046            //                   " = " + res.priority);
6047            res.match = match;
6048            res.isDefault = info.hasDefault;
6049            res.labelRes = info.labelRes;
6050            res.nonLocalizedLabel = info.nonLocalizedLabel;
6051            res.icon = info.icon;
6052            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6053            return res;
6054        }
6055
6056        @Override
6057        protected void sortResults(List<ResolveInfo> results) {
6058            Collections.sort(results, mResolvePrioritySorter);
6059        }
6060
6061        @Override
6062        protected void dumpFilter(PrintWriter out, String prefix,
6063                PackageParser.ServiceIntentInfo filter) {
6064            out.print(prefix); out.print(
6065                    Integer.toHexString(System.identityHashCode(filter.service)));
6066                    out.print(' ');
6067                    filter.service.printComponentShortName(out);
6068                    out.print(" filter ");
6069                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6070        }
6071
6072//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6073//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6074//            final List<ResolveInfo> retList = Lists.newArrayList();
6075//            while (i.hasNext()) {
6076//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6077//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6078//                    retList.add(resolveInfo);
6079//                }
6080//            }
6081//            return retList;
6082//        }
6083
6084        // Keys are String (activity class name), values are Activity.
6085        private final HashMap<ComponentName, PackageParser.Service> mServices
6086                = new HashMap<ComponentName, PackageParser.Service>();
6087        private int mFlags;
6088    };
6089
6090    private final class ProviderIntentResolver
6091            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6092        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6093                boolean defaultOnly, int userId) {
6094            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6095            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6096        }
6097
6098        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6099                int userId) {
6100            if (!sUserManager.exists(userId))
6101                return null;
6102            mFlags = flags;
6103            return super.queryIntent(intent, resolvedType,
6104                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6105        }
6106
6107        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6108                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6109            if (!sUserManager.exists(userId))
6110                return null;
6111            if (packageProviders == null) {
6112                return null;
6113            }
6114            mFlags = flags;
6115            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6116            final int N = packageProviders.size();
6117            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6118                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6119
6120            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6121            for (int i = 0; i < N; ++i) {
6122                intentFilters = packageProviders.get(i).intents;
6123                if (intentFilters != null && intentFilters.size() > 0) {
6124                    PackageParser.ProviderIntentInfo[] array =
6125                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6126                    intentFilters.toArray(array);
6127                    listCut.add(array);
6128                }
6129            }
6130            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6131        }
6132
6133        public final void addProvider(PackageParser.Provider p) {
6134            mProviders.put(p.getComponentName(), p);
6135            if (DEBUG_SHOW_INFO) {
6136                Log.v(TAG, "  "
6137                        + (p.info.nonLocalizedLabel != null
6138                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6139                Log.v(TAG, "    Class=" + p.info.name);
6140            }
6141            final int NI = p.intents.size();
6142            int j;
6143            for (j = 0; j < NI; j++) {
6144                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6145                if (DEBUG_SHOW_INFO) {
6146                    Log.v(TAG, "    IntentFilter:");
6147                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6148                }
6149                if (!intent.debugCheck()) {
6150                    Log.w(TAG, "==> For Provider " + p.info.name);
6151                }
6152                addFilter(intent);
6153            }
6154        }
6155
6156        public final void removeProvider(PackageParser.Provider p) {
6157            mProviders.remove(p.getComponentName());
6158            if (DEBUG_SHOW_INFO) {
6159                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6160                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6161                Log.v(TAG, "    Class=" + p.info.name);
6162            }
6163            final int NI = p.intents.size();
6164            int j;
6165            for (j = 0; j < NI; j++) {
6166                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6167                if (DEBUG_SHOW_INFO) {
6168                    Log.v(TAG, "    IntentFilter:");
6169                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6170                }
6171                removeFilter(intent);
6172            }
6173        }
6174
6175        @Override
6176        protected boolean allowFilterResult(
6177                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6178            ProviderInfo filterPi = filter.provider.info;
6179            for (int i = dest.size() - 1; i >= 0; i--) {
6180                ProviderInfo destPi = dest.get(i).providerInfo;
6181                if (destPi.name == filterPi.name
6182                        && destPi.packageName == filterPi.packageName) {
6183                    return false;
6184                }
6185            }
6186            return true;
6187        }
6188
6189        @Override
6190        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6191            return new PackageParser.ProviderIntentInfo[size];
6192        }
6193
6194        @Override
6195        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6196            if (!sUserManager.exists(userId))
6197                return true;
6198            PackageParser.Package p = filter.provider.owner;
6199            if (p != null) {
6200                PackageSetting ps = (PackageSetting) p.mExtras;
6201                if (ps != null) {
6202                    // System apps are never considered stopped for purposes of
6203                    // filtering, because there may be no way for the user to
6204                    // actually re-launch them.
6205                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6206                            && ps.getStopped(userId);
6207                }
6208            }
6209            return false;
6210        }
6211
6212        @Override
6213        protected boolean isPackageForFilter(String packageName,
6214                PackageParser.ProviderIntentInfo info) {
6215            return packageName.equals(info.provider.owner.packageName);
6216        }
6217
6218        @Override
6219        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6220                int match, int userId) {
6221            if (!sUserManager.exists(userId))
6222                return null;
6223            final PackageParser.ProviderIntentInfo info = filter;
6224            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6225                return null;
6226            }
6227            final PackageParser.Provider provider = info.provider;
6228            if (mSafeMode && (provider.info.applicationInfo.flags
6229                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6230                return null;
6231            }
6232            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6233            if (ps == null) {
6234                return null;
6235            }
6236            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6237                    ps.readUserState(userId), userId);
6238            if (pi == null) {
6239                return null;
6240            }
6241            final ResolveInfo res = new ResolveInfo();
6242            res.providerInfo = pi;
6243            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6244                res.filter = filter;
6245            }
6246            res.priority = info.getPriority();
6247            res.preferredOrder = provider.owner.mPreferredOrder;
6248            res.match = match;
6249            res.isDefault = info.hasDefault;
6250            res.labelRes = info.labelRes;
6251            res.nonLocalizedLabel = info.nonLocalizedLabel;
6252            res.icon = info.icon;
6253            res.system = isSystemApp(res.providerInfo.applicationInfo);
6254            return res;
6255        }
6256
6257        @Override
6258        protected void sortResults(List<ResolveInfo> results) {
6259            Collections.sort(results, mResolvePrioritySorter);
6260        }
6261
6262        @Override
6263        protected void dumpFilter(PrintWriter out, String prefix,
6264                PackageParser.ProviderIntentInfo filter) {
6265            out.print(prefix);
6266            out.print(
6267                    Integer.toHexString(System.identityHashCode(filter.provider)));
6268            out.print(' ');
6269            filter.provider.printComponentShortName(out);
6270            out.print(" filter ");
6271            out.println(Integer.toHexString(System.identityHashCode(filter)));
6272        }
6273
6274        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6275                = new HashMap<ComponentName, PackageParser.Provider>();
6276        private int mFlags;
6277    };
6278
6279    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6280            new Comparator<ResolveInfo>() {
6281        public int compare(ResolveInfo r1, ResolveInfo r2) {
6282            int v1 = r1.priority;
6283            int v2 = r2.priority;
6284            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6285            if (v1 != v2) {
6286                return (v1 > v2) ? -1 : 1;
6287            }
6288            v1 = r1.preferredOrder;
6289            v2 = r2.preferredOrder;
6290            if (v1 != v2) {
6291                return (v1 > v2) ? -1 : 1;
6292            }
6293            if (r1.isDefault != r2.isDefault) {
6294                return r1.isDefault ? -1 : 1;
6295            }
6296            v1 = r1.match;
6297            v2 = r2.match;
6298            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6299            if (v1 != v2) {
6300                return (v1 > v2) ? -1 : 1;
6301            }
6302            if (r1.system != r2.system) {
6303                return r1.system ? -1 : 1;
6304            }
6305            return 0;
6306        }
6307    };
6308
6309    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6310            new Comparator<ProviderInfo>() {
6311        public int compare(ProviderInfo p1, ProviderInfo p2) {
6312            final int v1 = p1.initOrder;
6313            final int v2 = p2.initOrder;
6314            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6315        }
6316    };
6317
6318    static final void sendPackageBroadcast(String action, String pkg,
6319            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6320            int[] userIds) {
6321        IActivityManager am = ActivityManagerNative.getDefault();
6322        if (am != null) {
6323            try {
6324                if (userIds == null) {
6325                    userIds = am.getRunningUserIds();
6326                }
6327                for (int id : userIds) {
6328                    final Intent intent = new Intent(action,
6329                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6330                    if (extras != null) {
6331                        intent.putExtras(extras);
6332                    }
6333                    if (targetPkg != null) {
6334                        intent.setPackage(targetPkg);
6335                    }
6336                    // Modify the UID when posting to other users
6337                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6338                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6339                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6340                        intent.putExtra(Intent.EXTRA_UID, uid);
6341                    }
6342                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6343                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6344                    if (DEBUG_BROADCASTS) {
6345                        RuntimeException here = new RuntimeException("here");
6346                        here.fillInStackTrace();
6347                        Slog.d(TAG, "Sending to user " + id + ": "
6348                                + intent.toShortString(false, true, false, false)
6349                                + " " + intent.getExtras(), here);
6350                    }
6351                    am.broadcastIntent(null, intent, null, finishedReceiver,
6352                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6353                            finishedReceiver != null, false, id);
6354                }
6355            } catch (RemoteException ex) {
6356            }
6357        }
6358    }
6359
6360    /**
6361     * Check if the external storage media is available. This is true if there
6362     * is a mounted external storage medium or if the external storage is
6363     * emulated.
6364     */
6365    private boolean isExternalMediaAvailable() {
6366        return mMediaMounted || Environment.isExternalStorageEmulated();
6367    }
6368
6369    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6370        // writer
6371        synchronized (mPackages) {
6372            if (!isExternalMediaAvailable()) {
6373                // If the external storage is no longer mounted at this point,
6374                // the caller may not have been able to delete all of this
6375                // packages files and can not delete any more.  Bail.
6376                return null;
6377            }
6378            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6379            if (lastPackage != null) {
6380                pkgs.remove(lastPackage);
6381            }
6382            if (pkgs.size() > 0) {
6383                return pkgs.get(0);
6384            }
6385        }
6386        return null;
6387    }
6388
6389    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6390        if (false) {
6391            RuntimeException here = new RuntimeException("here");
6392            here.fillInStackTrace();
6393            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6394                    + " andCode=" + andCode, here);
6395        }
6396        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6397                userId, andCode ? 1 : 0, packageName));
6398    }
6399
6400    void startCleaningPackages() {
6401        // reader
6402        synchronized (mPackages) {
6403            if (!isExternalMediaAvailable()) {
6404                return;
6405            }
6406            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6407                return;
6408            }
6409        }
6410        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6411        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6412        IActivityManager am = ActivityManagerNative.getDefault();
6413        if (am != null) {
6414            try {
6415                am.startService(null, intent, null, UserHandle.USER_OWNER);
6416            } catch (RemoteException e) {
6417            }
6418        }
6419    }
6420
6421    private final class AppDirObserver extends FileObserver {
6422        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6423            super(path, mask);
6424            mRootDir = path;
6425            mIsRom = isrom;
6426            mIsPrivileged = isPrivileged;
6427        }
6428
6429        public void onEvent(int event, String path) {
6430            String removedPackage = null;
6431            int removedAppId = -1;
6432            int[] removedUsers = null;
6433            String addedPackage = null;
6434            int addedAppId = -1;
6435            int[] addedUsers = null;
6436
6437            // TODO post a message to the handler to obtain serial ordering
6438            synchronized (mInstallLock) {
6439                String fullPathStr = null;
6440                File fullPath = null;
6441                if (path != null) {
6442                    fullPath = new File(mRootDir, path);
6443                    fullPathStr = fullPath.getPath();
6444                }
6445
6446                if (DEBUG_APP_DIR_OBSERVER)
6447                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6448
6449                if (!isPackageFilename(path)) {
6450                    if (DEBUG_APP_DIR_OBSERVER)
6451                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6452                    return;
6453                }
6454
6455                // Ignore packages that are being installed or
6456                // have just been installed.
6457                if (ignoreCodePath(fullPathStr)) {
6458                    return;
6459                }
6460                PackageParser.Package p = null;
6461                PackageSetting ps = null;
6462                // reader
6463                synchronized (mPackages) {
6464                    p = mAppDirs.get(fullPathStr);
6465                    if (p != null) {
6466                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6467                        if (ps != null) {
6468                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6469                        } else {
6470                            removedUsers = sUserManager.getUserIds();
6471                        }
6472                    }
6473                    addedUsers = sUserManager.getUserIds();
6474                }
6475                if ((event&REMOVE_EVENTS) != 0) {
6476                    if (ps != null) {
6477                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6478                        removePackageLI(ps, true);
6479                        removedPackage = ps.name;
6480                        removedAppId = ps.appId;
6481                    }
6482                }
6483
6484                if ((event&ADD_EVENTS) != 0) {
6485                    if (p == null) {
6486                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6487                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6488                        if (mIsRom) {
6489                            flags |= PackageParser.PARSE_IS_SYSTEM
6490                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6491                            if (mIsPrivileged) {
6492                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6493                            }
6494                        }
6495                        p = scanPackageLI(fullPath, flags,
6496                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6497                                System.currentTimeMillis(), UserHandle.ALL);
6498                        if (p != null) {
6499                            /*
6500                             * TODO this seems dangerous as the package may have
6501                             * changed since we last acquired the mPackages
6502                             * lock.
6503                             */
6504                            // writer
6505                            synchronized (mPackages) {
6506                                updatePermissionsLPw(p.packageName, p,
6507                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6508                            }
6509                            addedPackage = p.applicationInfo.packageName;
6510                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6511                        }
6512                    }
6513                }
6514
6515                // reader
6516                synchronized (mPackages) {
6517                    mSettings.writeLPr();
6518                }
6519            }
6520
6521            if (removedPackage != null) {
6522                Bundle extras = new Bundle(1);
6523                extras.putInt(Intent.EXTRA_UID, removedAppId);
6524                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6525                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6526                        extras, null, null, removedUsers);
6527            }
6528            if (addedPackage != null) {
6529                Bundle extras = new Bundle(1);
6530                extras.putInt(Intent.EXTRA_UID, addedAppId);
6531                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6532                        extras, null, null, addedUsers);
6533            }
6534        }
6535
6536        private final String mRootDir;
6537        private final boolean mIsRom;
6538        private final boolean mIsPrivileged;
6539    }
6540
6541    /* Called when a downloaded package installation has been confirmed by the user */
6542    public void installPackage(
6543            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6544        installPackage(packageURI, observer, flags, null);
6545    }
6546
6547    /* Called when a downloaded package installation has been confirmed by the user */
6548    public void installPackage(
6549            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6550            final String installerPackageName) {
6551        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
6552                null, null);
6553    }
6554
6555    @Override
6556    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6557            int flags, String installerPackageName, Uri verificationURI,
6558            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6559        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6560                VerificationParams.NO_UID, manifestDigest);
6561        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
6562                installerPackageName, verificationParams, encryptionParams);
6563    }
6564
6565    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6566            IPackageInstallObserver observer, int flags, String installerPackageName,
6567            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6568        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6569                null);
6570
6571        final int uid = Binder.getCallingUid();
6572        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
6573            try {
6574                observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6575            } catch (RemoteException re) {
6576            }
6577            return;
6578        }
6579
6580        UserHandle user;
6581        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6582            user = UserHandle.ALL;
6583        } else {
6584            user = new UserHandle(UserHandle.getUserId(uid));
6585        }
6586
6587        final int filteredFlags;
6588
6589        if (uid == Process.SHELL_UID || uid == 0) {
6590            if (DEBUG_INSTALL) {
6591                Slog.v(TAG, "Install from ADB");
6592            }
6593            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6594        } else {
6595            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6596        }
6597
6598        verificationParams.setInstallerUid(uid);
6599
6600        final Message msg = mHandler.obtainMessage(INIT_COPY);
6601        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
6602                verificationParams, encryptionParams, user);
6603        mHandler.sendMessage(msg);
6604    }
6605
6606    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
6607        Bundle extras = new Bundle(1);
6608        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6609
6610        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6611                packageName, extras, null, null, new int[] {userId});
6612        try {
6613            IActivityManager am = ActivityManagerNative.getDefault();
6614            final boolean isSystem =
6615                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6616            if (isSystem && am.isUserRunning(userId, false)) {
6617                // The just-installed/enabled app is bundled on the system, so presumed
6618                // to be able to run automatically without needing an explicit launch.
6619                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6620                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6621                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6622                        .setPackage(packageName);
6623                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6624                        android.app.AppOpsManager.OP_NONE, false, false, userId);
6625            }
6626        } catch (RemoteException e) {
6627            // shouldn't happen
6628            Slog.w(TAG, "Unable to bootstrap installed package", e);
6629        }
6630    }
6631
6632    @Override
6633    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
6634            int userId) {
6635        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6636        PackageSetting pkgSetting;
6637        final int uid = Binder.getCallingUid();
6638        if (UserHandle.getUserId(uid) != userId) {
6639            mContext.enforceCallingOrSelfPermission(
6640                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6641                    "setApplicationBlockedSetting for user " + userId);
6642        }
6643
6644        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
6645            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
6646            return false;
6647        }
6648
6649        long callingId = Binder.clearCallingIdentity();
6650        try {
6651            boolean sendAdded = false;
6652            boolean sendRemoved = false;
6653            // writer
6654            synchronized (mPackages) {
6655                pkgSetting = mSettings.mPackages.get(packageName);
6656                if (pkgSetting == null) {
6657                    return false;
6658                }
6659                if (pkgSetting.getBlocked(userId) != blocked) {
6660                    pkgSetting.setBlocked(blocked, userId);
6661                    mSettings.writePackageRestrictionsLPr(userId);
6662                    if (blocked) {
6663                        sendRemoved = true;
6664                    } else {
6665                        sendAdded = true;
6666                    }
6667                }
6668            }
6669            if (sendAdded) {
6670                sendPackageAddedForUser(packageName, pkgSetting, userId);
6671                return true;
6672            }
6673            if (sendRemoved) {
6674                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
6675                        "blocking pkg");
6676                sendPackageBlockedForUser(packageName, pkgSetting, userId);
6677            }
6678        } finally {
6679            Binder.restoreCallingIdentity(callingId);
6680        }
6681        return false;
6682    }
6683
6684    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
6685            int userId) {
6686        final PackageRemovedInfo info = new PackageRemovedInfo();
6687        info.removedPackage = packageName;
6688        info.removedUsers = new int[] {userId};
6689        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
6690        info.sendBroadcast(false, false, false);
6691    }
6692
6693    /**
6694     * Returns true if application is not found or there was an error. Otherwise it returns
6695     * the blocked state of the package for the given user.
6696     */
6697    @Override
6698    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
6699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6700        PackageSetting pkgSetting;
6701        final int uid = Binder.getCallingUid();
6702        if (UserHandle.getUserId(uid) != userId) {
6703            mContext.enforceCallingPermission(
6704                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6705                    "getApplicationBlocked for user " + userId);
6706        }
6707        long callingId = Binder.clearCallingIdentity();
6708        try {
6709            // writer
6710            synchronized (mPackages) {
6711                pkgSetting = mSettings.mPackages.get(packageName);
6712                if (pkgSetting == null) {
6713                    return true;
6714                }
6715                return pkgSetting.getBlocked(userId);
6716            }
6717        } finally {
6718            Binder.restoreCallingIdentity(callingId);
6719        }
6720    }
6721
6722    /**
6723     * @hide
6724     */
6725    @Override
6726    public int installExistingPackageAsUser(String packageName, int userId) {
6727        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6728                null);
6729        PackageSetting pkgSetting;
6730        final int uid = Binder.getCallingUid();
6731        if (UserHandle.getUserId(uid) != userId) {
6732            mContext.enforceCallingPermission(
6733                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6734                    "installExistingPackage for user " + userId);
6735        }
6736        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
6737            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
6738        }
6739
6740        long callingId = Binder.clearCallingIdentity();
6741        try {
6742            boolean sendAdded = false;
6743            Bundle extras = new Bundle(1);
6744
6745            // writer
6746            synchronized (mPackages) {
6747                pkgSetting = mSettings.mPackages.get(packageName);
6748                if (pkgSetting == null) {
6749                    return PackageManager.INSTALL_FAILED_INVALID_URI;
6750                }
6751                if (!pkgSetting.getInstalled(userId)) {
6752                    pkgSetting.setInstalled(true, userId);
6753                    pkgSetting.setBlocked(false, userId);
6754                    mSettings.writePackageRestrictionsLPr(userId);
6755                    sendAdded = true;
6756                }
6757            }
6758
6759            if (sendAdded) {
6760                sendPackageAddedForUser(packageName, pkgSetting, userId);
6761            }
6762        } finally {
6763            Binder.restoreCallingIdentity(callingId);
6764        }
6765
6766        return PackageManager.INSTALL_SUCCEEDED;
6767    }
6768
6769    private boolean isUserRestricted(int userId, String restrictionKey) {
6770        Bundle restrictions = sUserManager.getUserRestrictions(userId);
6771        if (restrictions.getBoolean(restrictionKey, false)) {
6772            Log.w(TAG, "User is restricted: " + restrictionKey);
6773            return true;
6774        }
6775        return false;
6776    }
6777
6778    @Override
6779    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
6780        mContext.enforceCallingOrSelfPermission(
6781                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6782                "Only package verification agents can verify applications");
6783
6784        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
6785        final PackageVerificationResponse response = new PackageVerificationResponse(
6786                verificationCode, Binder.getCallingUid());
6787        msg.arg1 = id;
6788        msg.obj = response;
6789        mHandler.sendMessage(msg);
6790    }
6791
6792    @Override
6793    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
6794            long millisecondsToDelay) {
6795        mContext.enforceCallingOrSelfPermission(
6796                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6797                "Only package verification agents can extend verification timeouts");
6798
6799        final PackageVerificationState state = mPendingVerification.get(id);
6800        final PackageVerificationResponse response = new PackageVerificationResponse(
6801                verificationCodeAtTimeout, Binder.getCallingUid());
6802
6803        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
6804            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
6805        }
6806        if (millisecondsToDelay < 0) {
6807            millisecondsToDelay = 0;
6808        }
6809        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
6810                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
6811            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
6812        }
6813
6814        if ((state != null) && !state.timeoutExtended()) {
6815            state.extendTimeout();
6816
6817            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
6818            msg.arg1 = id;
6819            msg.obj = response;
6820            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
6821        }
6822    }
6823
6824    private void broadcastPackageVerified(int verificationId, Uri packageUri,
6825            int verificationCode, UserHandle user) {
6826        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
6827        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
6828        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6829        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6830        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
6831
6832        mContext.sendBroadcastAsUser(intent, user,
6833                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
6834    }
6835
6836    private ComponentName matchComponentForVerifier(String packageName,
6837            List<ResolveInfo> receivers) {
6838        ActivityInfo targetReceiver = null;
6839
6840        final int NR = receivers.size();
6841        for (int i = 0; i < NR; i++) {
6842            final ResolveInfo info = receivers.get(i);
6843            if (info.activityInfo == null) {
6844                continue;
6845            }
6846
6847            if (packageName.equals(info.activityInfo.packageName)) {
6848                targetReceiver = info.activityInfo;
6849                break;
6850            }
6851        }
6852
6853        if (targetReceiver == null) {
6854            return null;
6855        }
6856
6857        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
6858    }
6859
6860    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
6861            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
6862        if (pkgInfo.verifiers.length == 0) {
6863            return null;
6864        }
6865
6866        final int N = pkgInfo.verifiers.length;
6867        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
6868        for (int i = 0; i < N; i++) {
6869            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
6870
6871            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
6872                    receivers);
6873            if (comp == null) {
6874                continue;
6875            }
6876
6877            final int verifierUid = getUidForVerifier(verifierInfo);
6878            if (verifierUid == -1) {
6879                continue;
6880            }
6881
6882            if (DEBUG_VERIFY) {
6883                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
6884                        + " with the correct signature");
6885            }
6886            sufficientVerifiers.add(comp);
6887            verificationState.addSufficientVerifier(verifierUid);
6888        }
6889
6890        return sufficientVerifiers;
6891    }
6892
6893    private int getUidForVerifier(VerifierInfo verifierInfo) {
6894        synchronized (mPackages) {
6895            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
6896            if (pkg == null) {
6897                return -1;
6898            } else if (pkg.mSignatures.length != 1) {
6899                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
6900                        + " has more than one signature; ignoring");
6901                return -1;
6902            }
6903
6904            /*
6905             * If the public key of the package's signature does not match
6906             * our expected public key, then this is a different package and
6907             * we should skip.
6908             */
6909
6910            final byte[] expectedPublicKey;
6911            try {
6912                final Signature verifierSig = pkg.mSignatures[0];
6913                final PublicKey publicKey = verifierSig.getPublicKey();
6914                expectedPublicKey = publicKey.getEncoded();
6915            } catch (CertificateException e) {
6916                return -1;
6917            }
6918
6919            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
6920
6921            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
6922                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
6923                        + " does not have the expected public key; ignoring");
6924                return -1;
6925            }
6926
6927            return pkg.applicationInfo.uid;
6928        }
6929    }
6930
6931    public void finishPackageInstall(int token) {
6932        enforceSystemOrRoot("Only the system is allowed to finish installs");
6933
6934        if (DEBUG_INSTALL) {
6935            Slog.v(TAG, "BM finishing package install for " + token);
6936        }
6937
6938        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6939        mHandler.sendMessage(msg);
6940    }
6941
6942    /**
6943     * Get the verification agent timeout.
6944     *
6945     * @return verification timeout in milliseconds
6946     */
6947    private long getVerificationTimeout() {
6948        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
6949                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
6950                DEFAULT_VERIFICATION_TIMEOUT);
6951    }
6952
6953    /**
6954     * Get the default verification agent response code.
6955     *
6956     * @return default verification response code
6957     */
6958    private int getDefaultVerificationResponse() {
6959        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6960                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
6961                DEFAULT_VERIFICATION_RESPONSE);
6962    }
6963
6964    /**
6965     * Check whether or not package verification has been enabled.
6966     *
6967     * @return true if verification should be performed
6968     */
6969    private boolean isVerificationEnabled(int flags) {
6970        if (!DEFAULT_VERIFY_ENABLE) {
6971            return false;
6972        }
6973
6974        // Check if installing from ADB
6975        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
6976            // Do not run verification in a test harness environment
6977            if (ActivityManager.isRunningInTestHarness()) {
6978                return false;
6979            }
6980            // Check if the developer does not want package verification for ADB installs
6981            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6982                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
6983                return false;
6984            }
6985        }
6986
6987        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6988                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
6989    }
6990
6991    /**
6992     * Get the "allow unknown sources" setting.
6993     *
6994     * @return the current "allow unknown sources" setting
6995     */
6996    private int getUnknownSourcesSettings() {
6997        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6998                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
6999                -1);
7000    }
7001
7002    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7003        final int uid = Binder.getCallingUid();
7004        // writer
7005        synchronized (mPackages) {
7006            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7007            if (targetPackageSetting == null) {
7008                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7009            }
7010
7011            PackageSetting installerPackageSetting;
7012            if (installerPackageName != null) {
7013                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7014                if (installerPackageSetting == null) {
7015                    throw new IllegalArgumentException("Unknown installer package: "
7016                            + installerPackageName);
7017                }
7018            } else {
7019                installerPackageSetting = null;
7020            }
7021
7022            Signature[] callerSignature;
7023            Object obj = mSettings.getUserIdLPr(uid);
7024            if (obj != null) {
7025                if (obj instanceof SharedUserSetting) {
7026                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7027                } else if (obj instanceof PackageSetting) {
7028                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7029                } else {
7030                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7031                }
7032            } else {
7033                throw new SecurityException("Unknown calling uid " + uid);
7034            }
7035
7036            // Verify: can't set installerPackageName to a package that is
7037            // not signed with the same cert as the caller.
7038            if (installerPackageSetting != null) {
7039                if (compareSignatures(callerSignature,
7040                        installerPackageSetting.signatures.mSignatures)
7041                        != PackageManager.SIGNATURE_MATCH) {
7042                    throw new SecurityException(
7043                            "Caller does not have same cert as new installer package "
7044                            + installerPackageName);
7045                }
7046            }
7047
7048            // Verify: if target already has an installer package, it must
7049            // be signed with the same cert as the caller.
7050            if (targetPackageSetting.installerPackageName != null) {
7051                PackageSetting setting = mSettings.mPackages.get(
7052                        targetPackageSetting.installerPackageName);
7053                // If the currently set package isn't valid, then it's always
7054                // okay to change it.
7055                if (setting != null) {
7056                    if (compareSignatures(callerSignature,
7057                            setting.signatures.mSignatures)
7058                            != PackageManager.SIGNATURE_MATCH) {
7059                        throw new SecurityException(
7060                                "Caller does not have same cert as old installer package "
7061                                + targetPackageSetting.installerPackageName);
7062                    }
7063                }
7064            }
7065
7066            // Okay!
7067            targetPackageSetting.installerPackageName = installerPackageName;
7068            scheduleWriteSettingsLocked();
7069        }
7070    }
7071
7072    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7073        // Queue up an async operation since the package installation may take a little while.
7074        mHandler.post(new Runnable() {
7075            public void run() {
7076                mHandler.removeCallbacks(this);
7077                 // Result object to be returned
7078                PackageInstalledInfo res = new PackageInstalledInfo();
7079                res.returnCode = currentStatus;
7080                res.uid = -1;
7081                res.pkg = null;
7082                res.removedInfo = new PackageRemovedInfo();
7083                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7084                    args.doPreInstall(res.returnCode);
7085                    synchronized (mInstallLock) {
7086                        installPackageLI(args, true, res);
7087                    }
7088                    args.doPostInstall(res.returnCode, res.uid);
7089                }
7090
7091                // A restore should be performed at this point if (a) the install
7092                // succeeded, (b) the operation is not an update, and (c) the new
7093                // package has a backupAgent defined.
7094                final boolean update = res.removedInfo.removedPackage != null;
7095                boolean doRestore = (!update
7096                        && res.pkg != null
7097                        && res.pkg.applicationInfo.backupAgentName != null);
7098
7099                // Set up the post-install work request bookkeeping.  This will be used
7100                // and cleaned up by the post-install event handling regardless of whether
7101                // there's a restore pass performed.  Token values are >= 1.
7102                int token;
7103                if (mNextInstallToken < 0) mNextInstallToken = 1;
7104                token = mNextInstallToken++;
7105
7106                PostInstallData data = new PostInstallData(args, res);
7107                mRunningInstalls.put(token, data);
7108                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7109
7110                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7111                    // Pass responsibility to the Backup Manager.  It will perform a
7112                    // restore if appropriate, then pass responsibility back to the
7113                    // Package Manager to run the post-install observer callbacks
7114                    // and broadcasts.
7115                    IBackupManager bm = IBackupManager.Stub.asInterface(
7116                            ServiceManager.getService(Context.BACKUP_SERVICE));
7117                    if (bm != null) {
7118                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7119                                + " to BM for possible restore");
7120                        try {
7121                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7122                        } catch (RemoteException e) {
7123                            // can't happen; the backup manager is local
7124                        } catch (Exception e) {
7125                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7126                            doRestore = false;
7127                        }
7128                    } else {
7129                        Slog.e(TAG, "Backup Manager not found!");
7130                        doRestore = false;
7131                    }
7132                }
7133
7134                if (!doRestore) {
7135                    // No restore possible, or the Backup Manager was mysteriously not
7136                    // available -- just fire the post-install work request directly.
7137                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7138                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7139                    mHandler.sendMessage(msg);
7140                }
7141            }
7142        });
7143    }
7144
7145    private abstract class HandlerParams {
7146        private static final int MAX_RETRIES = 4;
7147
7148        /**
7149         * Number of times startCopy() has been attempted and had a non-fatal
7150         * error.
7151         */
7152        private int mRetries = 0;
7153
7154        /** User handle for the user requesting the information or installation. */
7155        private final UserHandle mUser;
7156
7157        HandlerParams(UserHandle user) {
7158            mUser = user;
7159        }
7160
7161        UserHandle getUser() {
7162            return mUser;
7163        }
7164
7165        final boolean startCopy() {
7166            boolean res;
7167            try {
7168                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7169
7170                if (++mRetries > MAX_RETRIES) {
7171                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7172                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7173                    handleServiceError();
7174                    return false;
7175                } else {
7176                    handleStartCopy();
7177                    res = true;
7178                }
7179            } catch (RemoteException e) {
7180                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7181                mHandler.sendEmptyMessage(MCS_RECONNECT);
7182                res = false;
7183            }
7184            handleReturnCode();
7185            return res;
7186        }
7187
7188        final void serviceError() {
7189            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7190            handleServiceError();
7191            handleReturnCode();
7192        }
7193
7194        abstract void handleStartCopy() throws RemoteException;
7195        abstract void handleServiceError();
7196        abstract void handleReturnCode();
7197    }
7198
7199    class MeasureParams extends HandlerParams {
7200        private final PackageStats mStats;
7201        private boolean mSuccess;
7202
7203        private final IPackageStatsObserver mObserver;
7204
7205        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7206            super(new UserHandle(stats.userHandle));
7207            mObserver = observer;
7208            mStats = stats;
7209        }
7210
7211        @Override
7212        public String toString() {
7213            return "MeasureParams{"
7214                + Integer.toHexString(System.identityHashCode(this))
7215                + " " + mStats.packageName + "}";
7216        }
7217
7218        @Override
7219        void handleStartCopy() throws RemoteException {
7220            synchronized (mInstallLock) {
7221                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7222            }
7223
7224            final boolean mounted;
7225            if (Environment.isExternalStorageEmulated()) {
7226                mounted = true;
7227            } else {
7228                final String status = Environment.getExternalStorageState();
7229                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7230                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7231            }
7232
7233            if (mounted) {
7234                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7235
7236                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7237                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7238
7239                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7240                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7241
7242                // Always subtract cache size, since it's a subdirectory
7243                mStats.externalDataSize -= mStats.externalCacheSize;
7244
7245                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7246                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7247
7248                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7249                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7250            }
7251        }
7252
7253        @Override
7254        void handleReturnCode() {
7255            if (mObserver != null) {
7256                try {
7257                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7258                } catch (RemoteException e) {
7259                    Slog.i(TAG, "Observer no longer exists.");
7260                }
7261            }
7262        }
7263
7264        @Override
7265        void handleServiceError() {
7266            Slog.e(TAG, "Could not measure application " + mStats.packageName
7267                            + " external storage");
7268        }
7269    }
7270
7271    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7272            throws RemoteException {
7273        long result = 0;
7274        for (File path : paths) {
7275            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7276        }
7277        return result;
7278    }
7279
7280    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7281        for (File path : paths) {
7282            try {
7283                mcs.clearDirectory(path.getAbsolutePath());
7284            } catch (RemoteException e) {
7285            }
7286        }
7287    }
7288
7289    class InstallParams extends HandlerParams {
7290        final IPackageInstallObserver observer;
7291        int flags;
7292
7293        private final Uri mPackageURI;
7294        final String installerPackageName;
7295        final VerificationParams verificationParams;
7296        private InstallArgs mArgs;
7297        private int mRet;
7298        private File mTempPackage;
7299        final ContainerEncryptionParams encryptionParams;
7300
7301        InstallParams(Uri packageURI,
7302                IPackageInstallObserver observer, int flags,
7303                String installerPackageName, VerificationParams verificationParams,
7304                ContainerEncryptionParams encryptionParams, UserHandle user) {
7305            super(user);
7306            this.mPackageURI = packageURI;
7307            this.flags = flags;
7308            this.observer = observer;
7309            this.installerPackageName = installerPackageName;
7310            this.verificationParams = verificationParams;
7311            this.encryptionParams = encryptionParams;
7312        }
7313
7314        @Override
7315        public String toString() {
7316            return "InstallParams{"
7317                + Integer.toHexString(System.identityHashCode(this))
7318                + " " + mPackageURI + "}";
7319        }
7320
7321        public ManifestDigest getManifestDigest() {
7322            if (verificationParams == null) {
7323                return null;
7324            }
7325            return verificationParams.getManifestDigest();
7326        }
7327
7328        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7329            String packageName = pkgLite.packageName;
7330            int installLocation = pkgLite.installLocation;
7331            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7332            // reader
7333            synchronized (mPackages) {
7334                PackageParser.Package pkg = mPackages.get(packageName);
7335                if (pkg != null) {
7336                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7337                        // Check for downgrading.
7338                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7339                            if (pkgLite.versionCode < pkg.mVersionCode) {
7340                                Slog.w(TAG, "Can't install update of " + packageName
7341                                        + " update version " + pkgLite.versionCode
7342                                        + " is older than installed version "
7343                                        + pkg.mVersionCode);
7344                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7345                            }
7346                        }
7347                        // Check for updated system application.
7348                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7349                            if (onSd) {
7350                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7351                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7352                            }
7353                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7354                        } else {
7355                            if (onSd) {
7356                                // Install flag overrides everything.
7357                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7358                            }
7359                            // If current upgrade specifies particular preference
7360                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7361                                // Application explicitly specified internal.
7362                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7363                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7364                                // App explictly prefers external. Let policy decide
7365                            } else {
7366                                // Prefer previous location
7367                                if (isExternal(pkg)) {
7368                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7369                                }
7370                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7371                            }
7372                        }
7373                    } else {
7374                        // Invalid install. Return error code
7375                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7376                    }
7377                }
7378            }
7379            // All the special cases have been taken care of.
7380            // Return result based on recommended install location.
7381            if (onSd) {
7382                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7383            }
7384            return pkgLite.recommendedInstallLocation;
7385        }
7386
7387        private long getMemoryLowThreshold() {
7388            final DeviceStorageMonitorInternal
7389                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7390            if (dsm == null) {
7391                return 0L;
7392            }
7393            return dsm.getMemoryLowThreshold();
7394        }
7395
7396        /*
7397         * Invoke remote method to get package information and install
7398         * location values. Override install location based on default
7399         * policy if needed and then create install arguments based
7400         * on the install location.
7401         */
7402        public void handleStartCopy() throws RemoteException {
7403            int ret = PackageManager.INSTALL_SUCCEEDED;
7404            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7405            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7406            PackageInfoLite pkgLite = null;
7407
7408            if (onInt && onSd) {
7409                // Check if both bits are set.
7410                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7411                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7412            } else {
7413                final long lowThreshold = getMemoryLowThreshold();
7414                if (lowThreshold == 0L) {
7415                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7416                }
7417
7418                try {
7419                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7420                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7421
7422                    final File packageFile;
7423                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7424                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7425                        if (mTempPackage != null) {
7426                            ParcelFileDescriptor out;
7427                            try {
7428                                out = ParcelFileDescriptor.open(mTempPackage,
7429                                        ParcelFileDescriptor.MODE_READ_WRITE);
7430                            } catch (FileNotFoundException e) {
7431                                out = null;
7432                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7433                            }
7434
7435                            // Make a temporary file for decryption.
7436                            ret = mContainerService
7437                                    .copyResource(mPackageURI, encryptionParams, out);
7438                            IoUtils.closeQuietly(out);
7439
7440                            packageFile = mTempPackage;
7441
7442                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7443                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7444                                            | FileUtils.S_IROTH,
7445                                    -1, -1);
7446                        } else {
7447                            packageFile = null;
7448                        }
7449                    } else {
7450                        packageFile = new File(mPackageURI.getPath());
7451                    }
7452
7453                    if (packageFile != null) {
7454                        // Remote call to find out default install location
7455                        final String packageFilePath = packageFile.getAbsolutePath();
7456                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7457                                lowThreshold);
7458
7459                        /*
7460                         * If we have too little free space, try to free cache
7461                         * before giving up.
7462                         */
7463                        if (pkgLite.recommendedInstallLocation
7464                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7465                            final long size = mContainerService.calculateInstalledSize(
7466                                    packageFilePath, isForwardLocked());
7467                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7468                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7469                                        flags, lowThreshold);
7470                            }
7471                            /*
7472                             * The cache free must have deleted the file we
7473                             * downloaded to install.
7474                             *
7475                             * TODO: fix the "freeCache" call to not delete
7476                             *       the file we care about.
7477                             */
7478                            if (pkgLite.recommendedInstallLocation
7479                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7480                                pkgLite.recommendedInstallLocation
7481                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7482                            }
7483                        }
7484                    }
7485                } finally {
7486                    mContext.revokeUriPermission(mPackageURI,
7487                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7488                }
7489            }
7490
7491            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7492                int loc = pkgLite.recommendedInstallLocation;
7493                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7494                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7495                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7496                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7497                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7498                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7499                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7500                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7501                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7502                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7503                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7504                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7505                } else {
7506                    // Override with defaults if needed.
7507                    loc = installLocationPolicy(pkgLite, flags);
7508                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7509                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7510                    } else if (!onSd && !onInt) {
7511                        // Override install location with flags
7512                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7513                            // Set the flag to install on external media.
7514                            flags |= PackageManager.INSTALL_EXTERNAL;
7515                            flags &= ~PackageManager.INSTALL_INTERNAL;
7516                        } else {
7517                            // Make sure the flag for installing on external
7518                            // media is unset
7519                            flags |= PackageManager.INSTALL_INTERNAL;
7520                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7521                        }
7522                    }
7523                }
7524            }
7525
7526            final InstallArgs args = createInstallArgs(this);
7527            mArgs = args;
7528
7529            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7530                 /*
7531                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
7532                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
7533                 */
7534                int userIdentifier = getUser().getIdentifier();
7535                if (userIdentifier == UserHandle.USER_ALL
7536                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
7537                    userIdentifier = UserHandle.USER_OWNER;
7538                }
7539
7540                /*
7541                 * Determine if we have any installed package verifiers. If we
7542                 * do, then we'll defer to them to verify the packages.
7543                 */
7544                final int requiredUid = mRequiredVerifierPackage == null ? -1
7545                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
7546                if (requiredUid != -1 && isVerificationEnabled(flags)) {
7547                    final Intent verification = new Intent(
7548                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
7549                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
7550                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7551
7552                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
7553                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
7554                            0 /* TODO: Which userId? */);
7555
7556                    if (DEBUG_VERIFY) {
7557                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
7558                                + verification.toString() + " with " + pkgLite.verifiers.length
7559                                + " optional verifiers");
7560                    }
7561
7562                    final int verificationId = mPendingVerificationToken++;
7563
7564                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7565
7566                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
7567                            installerPackageName);
7568
7569                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
7570
7571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
7572                            pkgLite.packageName);
7573
7574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
7575                            pkgLite.versionCode);
7576
7577                    if (verificationParams != null) {
7578                        if (verificationParams.getVerificationURI() != null) {
7579                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
7580                                 verificationParams.getVerificationURI());
7581                        }
7582                        if (verificationParams.getOriginatingURI() != null) {
7583                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
7584                                  verificationParams.getOriginatingURI());
7585                        }
7586                        if (verificationParams.getReferrer() != null) {
7587                            verification.putExtra(Intent.EXTRA_REFERRER,
7588                                  verificationParams.getReferrer());
7589                        }
7590                        if (verificationParams.getOriginatingUid() >= 0) {
7591                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
7592                                  verificationParams.getOriginatingUid());
7593                        }
7594                        if (verificationParams.getInstallerUid() >= 0) {
7595                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
7596                                  verificationParams.getInstallerUid());
7597                        }
7598                    }
7599
7600                    final PackageVerificationState verificationState = new PackageVerificationState(
7601                            requiredUid, args);
7602
7603                    mPendingVerification.append(verificationId, verificationState);
7604
7605                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7606                            receivers, verificationState);
7607
7608                    /*
7609                     * If any sufficient verifiers were listed in the package
7610                     * manifest, attempt to ask them.
7611                     */
7612                    if (sufficientVerifiers != null) {
7613                        final int N = sufficientVerifiers.size();
7614                        if (N == 0) {
7615                            Slog.i(TAG, "Additional verifiers required, but none installed.");
7616                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7617                        } else {
7618                            for (int i = 0; i < N; i++) {
7619                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
7620
7621                                final Intent sufficientIntent = new Intent(verification);
7622                                sufficientIntent.setComponent(verifierComponent);
7623
7624                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
7625                            }
7626                        }
7627                    }
7628
7629                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7630                            mRequiredVerifierPackage, receivers);
7631                    if (ret == PackageManager.INSTALL_SUCCEEDED
7632                            && mRequiredVerifierPackage != null) {
7633                        /*
7634                         * Send the intent to the required verification agent,
7635                         * but only start the verification timeout after the
7636                         * target BroadcastReceivers have run.
7637                         */
7638                        verification.setComponent(requiredVerifierComponent);
7639                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
7640                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7641                                new BroadcastReceiver() {
7642                                    @Override
7643                                    public void onReceive(Context context, Intent intent) {
7644                                        final Message msg = mHandler
7645                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
7646                                        msg.arg1 = verificationId;
7647                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7648                                    }
7649                                }, null, 0, null, null);
7650
7651                        /*
7652                         * We don't want the copy to proceed until verification
7653                         * succeeds, so null out this field.
7654                         */
7655                        mArgs = null;
7656                    }
7657                } else {
7658                    /*
7659                     * No package verification is enabled, so immediately start
7660                     * the remote call to initiate copy using temporary file.
7661                     */
7662                    ret = args.copyApk(mContainerService, true);
7663                }
7664            }
7665
7666            mRet = ret;
7667        }
7668
7669        @Override
7670        void handleReturnCode() {
7671            // If mArgs is null, then MCS couldn't be reached. When it
7672            // reconnects, it will try again to install. At that point, this
7673            // will succeed.
7674            if (mArgs != null) {
7675                processPendingInstall(mArgs, mRet);
7676
7677                if (mTempPackage != null) {
7678                    if (!mTempPackage.delete()) {
7679                        Slog.w(TAG, "Couldn't delete temporary file: " +
7680                                mTempPackage.getAbsolutePath());
7681                    }
7682                }
7683            }
7684        }
7685
7686        @Override
7687        void handleServiceError() {
7688            mArgs = createInstallArgs(this);
7689            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
7690        }
7691
7692        public boolean isForwardLocked() {
7693            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7694        }
7695
7696        public Uri getPackageUri() {
7697            if (mTempPackage != null) {
7698                return Uri.fromFile(mTempPackage);
7699            } else {
7700                return mPackageURI;
7701            }
7702        }
7703    }
7704
7705    /*
7706     * Utility class used in movePackage api.
7707     * srcArgs and targetArgs are not set for invalid flags and make
7708     * sure to do null checks when invoking methods on them.
7709     * We probably want to return ErrorPrams for both failed installs
7710     * and moves.
7711     */
7712    class MoveParams extends HandlerParams {
7713        final IPackageMoveObserver observer;
7714        final int flags;
7715        final String packageName;
7716        final InstallArgs srcArgs;
7717        final InstallArgs targetArgs;
7718        int uid;
7719        int mRet;
7720
7721        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
7722                String packageName, String dataDir, int uid, UserHandle user) {
7723            super(user);
7724            this.srcArgs = srcArgs;
7725            this.observer = observer;
7726            this.flags = flags;
7727            this.packageName = packageName;
7728            this.uid = uid;
7729            if (srcArgs != null) {
7730                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
7731                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
7732            } else {
7733                targetArgs = null;
7734            }
7735        }
7736
7737        @Override
7738        public String toString() {
7739            return "MoveParams{"
7740                + Integer.toHexString(System.identityHashCode(this))
7741                + " " + packageName + "}";
7742        }
7743
7744        public void handleStartCopy() throws RemoteException {
7745            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7746            // Check for storage space on target medium
7747            if (!targetArgs.checkFreeStorage(mContainerService)) {
7748                Log.w(TAG, "Insufficient storage to install");
7749                return;
7750            }
7751
7752            mRet = srcArgs.doPreCopy();
7753            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7754                return;
7755            }
7756
7757            mRet = targetArgs.copyApk(mContainerService, false);
7758            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7759                srcArgs.doPostCopy(uid);
7760                return;
7761            }
7762
7763            mRet = srcArgs.doPostCopy(uid);
7764            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7765                return;
7766            }
7767
7768            mRet = targetArgs.doPreInstall(mRet);
7769            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7770                return;
7771            }
7772
7773            if (DEBUG_SD_INSTALL) {
7774                StringBuilder builder = new StringBuilder();
7775                if (srcArgs != null) {
7776                    builder.append("src: ");
7777                    builder.append(srcArgs.getCodePath());
7778                }
7779                if (targetArgs != null) {
7780                    builder.append(" target : ");
7781                    builder.append(targetArgs.getCodePath());
7782                }
7783                Log.i(TAG, builder.toString());
7784            }
7785        }
7786
7787        @Override
7788        void handleReturnCode() {
7789            targetArgs.doPostInstall(mRet, uid);
7790            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
7791            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
7792                currentStatus = PackageManager.MOVE_SUCCEEDED;
7793            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
7794                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
7795            }
7796            processPendingMove(this, currentStatus);
7797        }
7798
7799        @Override
7800        void handleServiceError() {
7801            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
7802        }
7803    }
7804
7805    /**
7806     * Used during creation of InstallArgs
7807     *
7808     * @param flags package installation flags
7809     * @return true if should be installed on external storage
7810     */
7811    private static boolean installOnSd(int flags) {
7812        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
7813            return false;
7814        }
7815        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
7816            return true;
7817        }
7818        return false;
7819    }
7820
7821    /**
7822     * Used during creation of InstallArgs
7823     *
7824     * @param flags package installation flags
7825     * @return true if should be installed as forward locked
7826     */
7827    private static boolean installForwardLocked(int flags) {
7828        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7829    }
7830
7831    private InstallArgs createInstallArgs(InstallParams params) {
7832        if (installOnSd(params.flags) || params.isForwardLocked()) {
7833            return new AsecInstallArgs(params);
7834        } else {
7835            return new FileInstallArgs(params);
7836        }
7837    }
7838
7839    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
7840            String nativeLibraryPath) {
7841        final boolean isInAsec;
7842        if (installOnSd(flags)) {
7843            /* Apps on SD card are always in ASEC containers. */
7844            isInAsec = true;
7845        } else if (installForwardLocked(flags)
7846                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
7847            /*
7848             * Forward-locked apps are only in ASEC containers if they're the
7849             * new style
7850             */
7851            isInAsec = true;
7852        } else {
7853            isInAsec = false;
7854        }
7855
7856        if (isInAsec) {
7857            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
7858                    installOnSd(flags), installForwardLocked(flags));
7859        } else {
7860            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
7861        }
7862    }
7863
7864    // Used by package mover
7865    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
7866        if (installOnSd(flags) || installForwardLocked(flags)) {
7867            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
7868                    + AsecInstallArgs.RES_FILE_NAME);
7869            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
7870                    installForwardLocked(flags));
7871        } else {
7872            return new FileInstallArgs(packageURI, pkgName, dataDir);
7873        }
7874    }
7875
7876    static abstract class InstallArgs {
7877        final IPackageInstallObserver observer;
7878        // Always refers to PackageManager flags only
7879        final int flags;
7880        final Uri packageURI;
7881        final String installerPackageName;
7882        final ManifestDigest manifestDigest;
7883        final UserHandle user;
7884
7885        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
7886                String installerPackageName, ManifestDigest manifestDigest,
7887                UserHandle user) {
7888            this.packageURI = packageURI;
7889            this.flags = flags;
7890            this.observer = observer;
7891            this.installerPackageName = installerPackageName;
7892            this.manifestDigest = manifestDigest;
7893            this.user = user;
7894        }
7895
7896        abstract void createCopyFile();
7897        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
7898        abstract int doPreInstall(int status);
7899        abstract boolean doRename(int status, String pkgName, String oldCodePath);
7900
7901        abstract int doPostInstall(int status, int uid);
7902        abstract String getCodePath();
7903        abstract String getResourcePath();
7904        abstract String getNativeLibraryPath();
7905        // Need installer lock especially for dex file removal.
7906        abstract void cleanUpResourcesLI();
7907        abstract boolean doPostDeleteLI(boolean delete);
7908        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
7909
7910        /**
7911         * Called before the source arguments are copied. This is used mostly
7912         * for MoveParams when it needs to read the source file to put it in the
7913         * destination.
7914         */
7915        int doPreCopy() {
7916            return PackageManager.INSTALL_SUCCEEDED;
7917        }
7918
7919        /**
7920         * Called after the source arguments are copied. This is used mostly for
7921         * MoveParams when it needs to read the source file to put it in the
7922         * destination.
7923         *
7924         * @return
7925         */
7926        int doPostCopy(int uid) {
7927            return PackageManager.INSTALL_SUCCEEDED;
7928        }
7929
7930        protected boolean isFwdLocked() {
7931            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7932        }
7933
7934        UserHandle getUser() {
7935            return user;
7936        }
7937    }
7938
7939    class FileInstallArgs extends InstallArgs {
7940        File installDir;
7941        String codeFileName;
7942        String resourceFileName;
7943        String libraryPath;
7944        boolean created = false;
7945
7946        FileInstallArgs(InstallParams params) {
7947            super(params.getPackageUri(), params.observer, params.flags,
7948                    params.installerPackageName, params.getManifestDigest(),
7949                    params.getUser());
7950        }
7951
7952        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
7953            super(null, null, 0, null, null, null);
7954            File codeFile = new File(fullCodePath);
7955            installDir = codeFile.getParentFile();
7956            codeFileName = fullCodePath;
7957            resourceFileName = fullResourcePath;
7958            libraryPath = nativeLibraryPath;
7959        }
7960
7961        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
7962            super(packageURI, null, 0, null, null, null);
7963            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
7964            String apkName = getNextCodePath(null, pkgName, ".apk");
7965            codeFileName = new File(installDir, apkName + ".apk").getPath();
7966            resourceFileName = getResourcePathFromCodePath();
7967            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
7968        }
7969
7970        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7971            final long lowThreshold;
7972
7973            final DeviceStorageMonitorInternal
7974                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7975            if (dsm == null) {
7976                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7977                lowThreshold = 0L;
7978            } else {
7979                if (dsm.isMemoryLow()) {
7980                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
7981                    return false;
7982                }
7983
7984                lowThreshold = dsm.getMemoryLowThreshold();
7985            }
7986
7987            try {
7988                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7989                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7990                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
7991            } finally {
7992                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7993            }
7994        }
7995
7996        String getCodePath() {
7997            return codeFileName;
7998        }
7999
8000        void createCopyFile() {
8001            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8002            codeFileName = createTempPackageFile(installDir).getPath();
8003            resourceFileName = getResourcePathFromCodePath();
8004            libraryPath = getLibraryPathFromCodePath();
8005            created = true;
8006        }
8007
8008        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8009            if (temp) {
8010                // Generate temp file name
8011                createCopyFile();
8012            }
8013            // Get a ParcelFileDescriptor to write to the output file
8014            File codeFile = new File(codeFileName);
8015            if (!created) {
8016                try {
8017                    codeFile.createNewFile();
8018                    // Set permissions
8019                    if (!setPermissions()) {
8020                        // Failed setting permissions.
8021                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8022                    }
8023                } catch (IOException e) {
8024                   Slog.w(TAG, "Failed to create file " + codeFile);
8025                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8026                }
8027            }
8028            ParcelFileDescriptor out = null;
8029            try {
8030                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8031            } catch (FileNotFoundException e) {
8032                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8033                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8034            }
8035            // Copy the resource now
8036            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8037            try {
8038                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8039                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8040                ret = imcs.copyResource(packageURI, null, out);
8041            } finally {
8042                IoUtils.closeQuietly(out);
8043                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8044            }
8045
8046            if (isFwdLocked()) {
8047                final File destResourceFile = new File(getResourcePath());
8048
8049                // Copy the public files
8050                try {
8051                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8052                } catch (IOException e) {
8053                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8054                            + " forward-locked app.");
8055                    destResourceFile.delete();
8056                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8057                }
8058            }
8059
8060            final File nativeLibraryFile = new File(getNativeLibraryPath());
8061            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8062            if (nativeLibraryFile.exists()) {
8063                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8064                nativeLibraryFile.delete();
8065            }
8066            try {
8067                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8068                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
8069                    return copyRet;
8070                }
8071            } catch (IOException e) {
8072                Slog.e(TAG, "Copying native libraries failed", e);
8073                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8074            }
8075
8076            return ret;
8077        }
8078
8079        int doPreInstall(int status) {
8080            if (status != PackageManager.INSTALL_SUCCEEDED) {
8081                cleanUp();
8082            }
8083            return status;
8084        }
8085
8086        boolean doRename(int status, final String pkgName, String oldCodePath) {
8087            if (status != PackageManager.INSTALL_SUCCEEDED) {
8088                cleanUp();
8089                return false;
8090            } else {
8091                final File oldCodeFile = new File(getCodePath());
8092                final File oldResourceFile = new File(getResourcePath());
8093                final File oldLibraryFile = new File(getNativeLibraryPath());
8094
8095                // Rename APK file based on packageName
8096                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8097                final File newCodeFile = new File(installDir, apkName + ".apk");
8098                if (!oldCodeFile.renameTo(newCodeFile)) {
8099                    return false;
8100                }
8101                codeFileName = newCodeFile.getPath();
8102
8103                // Rename public resource file if it's forward-locked.
8104                final File newResFile = new File(getResourcePathFromCodePath());
8105                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8106                    return false;
8107                }
8108                resourceFileName = newResFile.getPath();
8109
8110                // Rename library path
8111                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8112                if (newLibraryFile.exists()) {
8113                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8114                    newLibraryFile.delete();
8115                }
8116                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8117                    Slog.e(TAG, "Cannot rename native library directory "
8118                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8119                    return false;
8120                }
8121                libraryPath = newLibraryFile.getPath();
8122
8123                // Attempt to set permissions
8124                if (!setPermissions()) {
8125                    return false;
8126                }
8127
8128                if (!SELinux.restorecon(newCodeFile)) {
8129                    return false;
8130                }
8131
8132                return true;
8133            }
8134        }
8135
8136        int doPostInstall(int status, int uid) {
8137            if (status != PackageManager.INSTALL_SUCCEEDED) {
8138                cleanUp();
8139            }
8140            return status;
8141        }
8142
8143        String getResourcePath() {
8144            return resourceFileName;
8145        }
8146
8147        private String getResourcePathFromCodePath() {
8148            final String codePath = getCodePath();
8149            if (isFwdLocked()) {
8150                final StringBuilder sb = new StringBuilder();
8151
8152                sb.append(mAppInstallDir.getPath());
8153                sb.append('/');
8154                sb.append(getApkName(codePath));
8155                sb.append(".zip");
8156
8157                /*
8158                 * If our APK is a temporary file, mark the resource as a
8159                 * temporary file as well so it can be cleaned up after
8160                 * catastrophic failure.
8161                 */
8162                if (codePath.endsWith(".tmp")) {
8163                    sb.append(".tmp");
8164                }
8165
8166                return sb.toString();
8167            } else {
8168                return codePath;
8169            }
8170        }
8171
8172        private String getLibraryPathFromCodePath() {
8173            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8174        }
8175
8176        @Override
8177        String getNativeLibraryPath() {
8178            if (libraryPath == null) {
8179                libraryPath = getLibraryPathFromCodePath();
8180            }
8181            return libraryPath;
8182        }
8183
8184        private boolean cleanUp() {
8185            boolean ret = true;
8186            String sourceDir = getCodePath();
8187            String publicSourceDir = getResourcePath();
8188            if (sourceDir != null) {
8189                File sourceFile = new File(sourceDir);
8190                if (!sourceFile.exists()) {
8191                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8192                    ret = false;
8193                }
8194                // Delete application's code and resources
8195                sourceFile.delete();
8196            }
8197            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8198                final File publicSourceFile = new File(publicSourceDir);
8199                if (!publicSourceFile.exists()) {
8200                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8201                }
8202                if (publicSourceFile.exists()) {
8203                    publicSourceFile.delete();
8204                }
8205            }
8206
8207            if (libraryPath != null) {
8208                File nativeLibraryFile = new File(libraryPath);
8209                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8210                if (!nativeLibraryFile.delete()) {
8211                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8212                }
8213            }
8214
8215            return ret;
8216        }
8217
8218        void cleanUpResourcesLI() {
8219            String sourceDir = getCodePath();
8220            if (cleanUp()) {
8221                int retCode = mInstaller.rmdex(sourceDir);
8222                if (retCode < 0) {
8223                    Slog.w(TAG, "Couldn't remove dex file for package: "
8224                            +  " at location "
8225                            + sourceDir + ", retcode=" + retCode);
8226                    // we don't consider this to be a failure of the core package deletion
8227                }
8228            }
8229        }
8230
8231        private boolean setPermissions() {
8232            // TODO Do this in a more elegant way later on. for now just a hack
8233            if (!isFwdLocked()) {
8234                final int filePermissions =
8235                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8236                    |FileUtils.S_IROTH;
8237                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8238                if (retCode != 0) {
8239                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8240                            getCodePath()
8241                            + ". The return code was: " + retCode);
8242                    // TODO Define new internal error
8243                    return false;
8244                }
8245                return true;
8246            }
8247            return true;
8248        }
8249
8250        boolean doPostDeleteLI(boolean delete) {
8251            // XXX err, shouldn't we respect the delete flag?
8252            cleanUpResourcesLI();
8253            return true;
8254        }
8255    }
8256
8257    private boolean isAsecExternal(String cid) {
8258        final String asecPath = PackageHelper.getSdFilesystem(cid);
8259        return !asecPath.startsWith(mAsecInternalPath);
8260    }
8261
8262    /**
8263     * Extract the MountService "container ID" from the full code path of an
8264     * .apk.
8265     */
8266    static String cidFromCodePath(String fullCodePath) {
8267        int eidx = fullCodePath.lastIndexOf("/");
8268        String subStr1 = fullCodePath.substring(0, eidx);
8269        int sidx = subStr1.lastIndexOf("/");
8270        return subStr1.substring(sidx+1, eidx);
8271    }
8272
8273    class AsecInstallArgs extends InstallArgs {
8274        static final String RES_FILE_NAME = "pkg.apk";
8275        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8276
8277        String cid;
8278        String packagePath;
8279        String resourcePath;
8280        String libraryPath;
8281
8282        AsecInstallArgs(InstallParams params) {
8283            super(params.getPackageUri(), params.observer, params.flags,
8284                    params.installerPackageName, params.getManifestDigest(),
8285                    params.getUser());
8286        }
8287
8288        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8289                boolean isExternal, boolean isForwardLocked) {
8290            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8291                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8292                    null, null, null);
8293            // Extract cid from fullCodePath
8294            int eidx = fullCodePath.lastIndexOf("/");
8295            String subStr1 = fullCodePath.substring(0, eidx);
8296            int sidx = subStr1.lastIndexOf("/");
8297            cid = subStr1.substring(sidx+1, eidx);
8298            setCachePath(subStr1);
8299        }
8300
8301        AsecInstallArgs(String cid, boolean isForwardLocked) {
8302            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8303                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8304                    null, null, null);
8305            this.cid = cid;
8306            setCachePath(PackageHelper.getSdDir(cid));
8307        }
8308
8309        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
8310            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8311                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8312                    null, null, null);
8313            this.cid = cid;
8314        }
8315
8316        void createCopyFile() {
8317            cid = getTempContainerId();
8318        }
8319
8320        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8321            try {
8322                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8323                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8324                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8325            } finally {
8326                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8327            }
8328        }
8329
8330        private final boolean isExternal() {
8331            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8332        }
8333
8334        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8335            if (temp) {
8336                createCopyFile();
8337            } else {
8338                /*
8339                 * Pre-emptively destroy the container since it's destroyed if
8340                 * copying fails due to it existing anyway.
8341                 */
8342                PackageHelper.destroySdDir(cid);
8343            }
8344
8345            final String newCachePath;
8346            try {
8347                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8348                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8349                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8350                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8351            } finally {
8352                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8353            }
8354
8355            if (newCachePath != null) {
8356                setCachePath(newCachePath);
8357                return PackageManager.INSTALL_SUCCEEDED;
8358            } else {
8359                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8360            }
8361        }
8362
8363        @Override
8364        String getCodePath() {
8365            return packagePath;
8366        }
8367
8368        @Override
8369        String getResourcePath() {
8370            return resourcePath;
8371        }
8372
8373        @Override
8374        String getNativeLibraryPath() {
8375            return libraryPath;
8376        }
8377
8378        int doPreInstall(int status) {
8379            if (status != PackageManager.INSTALL_SUCCEEDED) {
8380                // Destroy container
8381                PackageHelper.destroySdDir(cid);
8382            } else {
8383                boolean mounted = PackageHelper.isContainerMounted(cid);
8384                if (!mounted) {
8385                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8386                            Process.SYSTEM_UID);
8387                    if (newCachePath != null) {
8388                        setCachePath(newCachePath);
8389                    } else {
8390                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8391                    }
8392                }
8393            }
8394            return status;
8395        }
8396
8397        boolean doRename(int status, final String pkgName,
8398                String oldCodePath) {
8399            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8400            String newCachePath = null;
8401            if (PackageHelper.isContainerMounted(cid)) {
8402                // Unmount the container
8403                if (!PackageHelper.unMountSdDir(cid)) {
8404                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8405                    return false;
8406                }
8407            }
8408            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8409                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8410                        " which might be stale. Will try to clean up.");
8411                // Clean up the stale container and proceed to recreate.
8412                if (!PackageHelper.destroySdDir(newCacheId)) {
8413                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8414                    return false;
8415                }
8416                // Successfully cleaned up stale container. Try to rename again.
8417                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8418                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8419                            + " inspite of cleaning it up.");
8420                    return false;
8421                }
8422            }
8423            if (!PackageHelper.isContainerMounted(newCacheId)) {
8424                Slog.w(TAG, "Mounting container " + newCacheId);
8425                newCachePath = PackageHelper.mountSdDir(newCacheId,
8426                        getEncryptKey(), Process.SYSTEM_UID);
8427            } else {
8428                newCachePath = PackageHelper.getSdDir(newCacheId);
8429            }
8430            if (newCachePath == null) {
8431                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8432                return false;
8433            }
8434            Log.i(TAG, "Succesfully renamed " + cid +
8435                    " to " + newCacheId +
8436                    " at new path: " + newCachePath);
8437            cid = newCacheId;
8438            setCachePath(newCachePath);
8439            return true;
8440        }
8441
8442        private void setCachePath(String newCachePath) {
8443            File cachePath = new File(newCachePath);
8444            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8445            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8446
8447            if (isFwdLocked()) {
8448                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8449            } else {
8450                resourcePath = packagePath;
8451            }
8452        }
8453
8454        int doPostInstall(int status, int uid) {
8455            if (status != PackageManager.INSTALL_SUCCEEDED) {
8456                cleanUp();
8457            } else {
8458                final int groupOwner;
8459                final String protectedFile;
8460                if (isFwdLocked()) {
8461                    groupOwner = UserHandle.getSharedAppGid(uid);
8462                    protectedFile = RES_FILE_NAME;
8463                } else {
8464                    groupOwner = -1;
8465                    protectedFile = null;
8466                }
8467
8468                if (uid < Process.FIRST_APPLICATION_UID
8469                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8470                    Slog.e(TAG, "Failed to finalize " + cid);
8471                    PackageHelper.destroySdDir(cid);
8472                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8473                }
8474
8475                boolean mounted = PackageHelper.isContainerMounted(cid);
8476                if (!mounted) {
8477                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8478                }
8479            }
8480            return status;
8481        }
8482
8483        private void cleanUp() {
8484            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8485
8486            // Destroy secure container
8487            PackageHelper.destroySdDir(cid);
8488        }
8489
8490        void cleanUpResourcesLI() {
8491            String sourceFile = getCodePath();
8492            // Remove dex file
8493            int retCode = mInstaller.rmdex(sourceFile);
8494            if (retCode < 0) {
8495                Slog.w(TAG, "Couldn't remove dex file for package: "
8496                        + " at location "
8497                        + sourceFile.toString() + ", retcode=" + retCode);
8498                // we don't consider this to be a failure of the core package deletion
8499            }
8500            cleanUp();
8501        }
8502
8503        boolean matchContainer(String app) {
8504            if (cid.startsWith(app)) {
8505                return true;
8506            }
8507            return false;
8508        }
8509
8510        String getPackageName() {
8511            return getAsecPackageName(cid);
8512        }
8513
8514        boolean doPostDeleteLI(boolean delete) {
8515            boolean ret = false;
8516            boolean mounted = PackageHelper.isContainerMounted(cid);
8517            if (mounted) {
8518                // Unmount first
8519                ret = PackageHelper.unMountSdDir(cid);
8520            }
8521            if (ret && delete) {
8522                cleanUpResourcesLI();
8523            }
8524            return ret;
8525        }
8526
8527        @Override
8528        int doPreCopy() {
8529            if (isFwdLocked()) {
8530                if (!PackageHelper.fixSdPermissions(cid,
8531                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
8532                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8533                }
8534            }
8535
8536            return PackageManager.INSTALL_SUCCEEDED;
8537        }
8538
8539        @Override
8540        int doPostCopy(int uid) {
8541            if (isFwdLocked()) {
8542                if (uid < Process.FIRST_APPLICATION_UID
8543                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
8544                                RES_FILE_NAME)) {
8545                    Slog.e(TAG, "Failed to finalize " + cid);
8546                    PackageHelper.destroySdDir(cid);
8547                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8548                }
8549            }
8550
8551            return PackageManager.INSTALL_SUCCEEDED;
8552        }
8553    };
8554
8555    static String getAsecPackageName(String packageCid) {
8556        int idx = packageCid.lastIndexOf("-");
8557        if (idx == -1) {
8558            return packageCid;
8559        }
8560        return packageCid.substring(0, idx);
8561    }
8562
8563    // Utility method used to create code paths based on package name and available index.
8564    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
8565        String idxStr = "";
8566        int idx = 1;
8567        // Fall back to default value of idx=1 if prefix is not
8568        // part of oldCodePath
8569        if (oldCodePath != null) {
8570            String subStr = oldCodePath;
8571            // Drop the suffix right away
8572            if (subStr.endsWith(suffix)) {
8573                subStr = subStr.substring(0, subStr.length() - suffix.length());
8574            }
8575            // If oldCodePath already contains prefix find out the
8576            // ending index to either increment or decrement.
8577            int sidx = subStr.lastIndexOf(prefix);
8578            if (sidx != -1) {
8579                subStr = subStr.substring(sidx + prefix.length());
8580                if (subStr != null) {
8581                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
8582                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
8583                    }
8584                    try {
8585                        idx = Integer.parseInt(subStr);
8586                        if (idx <= 1) {
8587                            idx++;
8588                        } else {
8589                            idx--;
8590                        }
8591                    } catch(NumberFormatException e) {
8592                    }
8593                }
8594            }
8595        }
8596        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
8597        return prefix + idxStr;
8598    }
8599
8600    // Utility method used to ignore ADD/REMOVE events
8601    // by directory observer.
8602    private static boolean ignoreCodePath(String fullPathStr) {
8603        String apkName = getApkName(fullPathStr);
8604        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8605        if (idx != -1 && ((idx+1) < apkName.length())) {
8606            // Make sure the package ends with a numeral
8607            String version = apkName.substring(idx+1);
8608            try {
8609                Integer.parseInt(version);
8610                return true;
8611            } catch (NumberFormatException e) {}
8612        }
8613        return false;
8614    }
8615
8616    // Utility method that returns the relative package path with respect
8617    // to the installation directory. Like say for /data/data/com.test-1.apk
8618    // string com.test-1 is returned.
8619    static String getApkName(String codePath) {
8620        if (codePath == null) {
8621            return null;
8622        }
8623        int sidx = codePath.lastIndexOf("/");
8624        int eidx = codePath.lastIndexOf(".");
8625        if (eidx == -1) {
8626            eidx = codePath.length();
8627        } else if (eidx == 0) {
8628            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
8629            return null;
8630        }
8631        return codePath.substring(sidx+1, eidx);
8632    }
8633
8634    class PackageInstalledInfo {
8635        String name;
8636        int uid;
8637        // The set of users that originally had this package installed.
8638        int[] origUsers;
8639        // The set of users that now have this package installed.
8640        int[] newUsers;
8641        PackageParser.Package pkg;
8642        int returnCode;
8643        PackageRemovedInfo removedInfo;
8644    }
8645
8646    /*
8647     * Install a non-existing package.
8648     */
8649    private void installNewPackageLI(PackageParser.Package pkg,
8650            int parseFlags, int scanMode, UserHandle user,
8651            String installerPackageName, PackageInstalledInfo res) {
8652        // Remember this for later, in case we need to rollback this install
8653        String pkgName = pkg.packageName;
8654
8655        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
8656        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
8657        synchronized(mPackages) {
8658            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8659                // A package with the same name is already installed, though
8660                // it has been renamed to an older name.  The package we
8661                // are trying to install should be installed as an update to
8662                // the existing one, but that has not been requested, so bail.
8663                Slog.w(TAG, "Attempt to re-install " + pkgName
8664                        + " without first uninstalling package running as "
8665                        + mSettings.mRenamedPackages.get(pkgName));
8666                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8667                return;
8668            }
8669            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
8670                // Don't allow installation over an existing package with the same name.
8671                Slog.w(TAG, "Attempt to re-install " + pkgName
8672                        + " without first uninstalling.");
8673                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8674                return;
8675            }
8676        }
8677        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8678        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
8679                System.currentTimeMillis(), user);
8680        if (newPackage == null) {
8681            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
8682            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8683                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8684            }
8685        } else {
8686            updateSettingsLI(newPackage,
8687                    installerPackageName,
8688                    null, null,
8689                    res);
8690            // delete the partially installed application. the data directory will have to be
8691            // restored if it was already existing
8692            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8693                // remove package from internal structures.  Note that we want deletePackageX to
8694                // delete the package data and cache directories that it created in
8695                // scanPackageLocked, unless those directories existed before we even tried to
8696                // install.
8697                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
8698                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
8699                                res.removedInfo, true);
8700            }
8701        }
8702    }
8703
8704    private void replacePackageLI(PackageParser.Package pkg,
8705            int parseFlags, int scanMode, UserHandle user,
8706            String installerPackageName, PackageInstalledInfo res) {
8707
8708        PackageParser.Package oldPackage;
8709        String pkgName = pkg.packageName;
8710        int[] allUsers;
8711        boolean[] perUserInstalled;
8712
8713        // First find the old package info and check signatures
8714        synchronized(mPackages) {
8715            oldPackage = mPackages.get(pkgName);
8716            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
8717            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
8718                    != PackageManager.SIGNATURE_MATCH) {
8719                Slog.w(TAG, "New package has a different signature: " + pkgName);
8720                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
8721                return;
8722            }
8723
8724            // In case of rollback, remember per-user/profile install state
8725            PackageSetting ps = mSettings.mPackages.get(pkgName);
8726            allUsers = sUserManager.getUserIds();
8727            perUserInstalled = new boolean[allUsers.length];
8728            for (int i = 0; i < allUsers.length; i++) {
8729                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
8730            }
8731        }
8732        boolean sysPkg = (isSystemApp(oldPackage));
8733        if (sysPkg) {
8734            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
8735                    user, allUsers, perUserInstalled, installerPackageName, res);
8736        } else {
8737            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
8738                    user, allUsers, perUserInstalled, installerPackageName, res);
8739        }
8740    }
8741
8742    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
8743            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
8744            int[] allUsers, boolean[] perUserInstalled,
8745            String installerPackageName, PackageInstalledInfo res) {
8746        PackageParser.Package newPackage = null;
8747        String pkgName = deletedPackage.packageName;
8748        boolean deletedPkg = true;
8749        boolean updatedSettings = false;
8750
8751        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
8752                + deletedPackage);
8753        long origUpdateTime;
8754        if (pkg.mExtras != null) {
8755            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
8756        } else {
8757            origUpdateTime = 0;
8758        }
8759
8760        // First delete the existing package while retaining the data directory
8761        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
8762                res.removedInfo, true)) {
8763            // If the existing package wasn't successfully deleted
8764            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
8765            deletedPkg = false;
8766        } else {
8767            // Successfully deleted the old package. Now proceed with re-installation
8768            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8769            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
8770                    System.currentTimeMillis(), user);
8771            if (newPackage == null) {
8772                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
8773                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8774                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8775                }
8776            } else {
8777                updateSettingsLI(newPackage,
8778                        installerPackageName,
8779                        allUsers, perUserInstalled,
8780                        res);
8781                updatedSettings = true;
8782            }
8783        }
8784
8785        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8786            // remove package from internal structures.  Note that we want deletePackageX to
8787            // delete the package data and cache directories that it created in
8788            // scanPackageLocked, unless those directories existed before we even tried to
8789            // install.
8790            if(updatedSettings) {
8791                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
8792                deletePackageLI(
8793                        pkgName, null, true, allUsers, perUserInstalled,
8794                        PackageManager.DELETE_KEEP_DATA,
8795                                res.removedInfo, true);
8796            }
8797            // Since we failed to install the new package we need to restore the old
8798            // package that we deleted.
8799            if(deletedPkg) {
8800                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
8801                File restoreFile = new File(deletedPackage.mPath);
8802                // Parse old package
8803                boolean oldOnSd = isExternal(deletedPackage);
8804                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
8805                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
8806                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
8807                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
8808                        | SCAN_UPDATE_TIME;
8809                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
8810                        origUpdateTime, null) == null) {
8811                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
8812                    return;
8813                }
8814                // Restore of old package succeeded. Update permissions.
8815                // writer
8816                synchronized (mPackages) {
8817                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
8818                            UPDATE_PERMISSIONS_ALL);
8819                    // can downgrade to reader
8820                    mSettings.writeLPr();
8821                }
8822                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
8823            }
8824        }
8825    }
8826
8827    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
8828            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
8829            int[] allUsers, boolean[] perUserInstalled,
8830            String installerPackageName, PackageInstalledInfo res) {
8831        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
8832                + ", old=" + deletedPackage);
8833        PackageParser.Package newPackage = null;
8834        boolean updatedSettings = false;
8835        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
8836                PackageParser.PARSE_IS_SYSTEM;
8837        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
8838            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8839        }
8840        String packageName = deletedPackage.packageName;
8841        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
8842        if (packageName == null) {
8843            Slog.w(TAG, "Attempt to delete null packageName.");
8844            return;
8845        }
8846        PackageParser.Package oldPkg;
8847        PackageSetting oldPkgSetting;
8848        // reader
8849        synchronized (mPackages) {
8850            oldPkg = mPackages.get(packageName);
8851            oldPkgSetting = mSettings.mPackages.get(packageName);
8852            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
8853                    (oldPkgSetting == null)) {
8854                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
8855                return;
8856            }
8857        }
8858
8859        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
8860
8861        res.removedInfo.uid = oldPkg.applicationInfo.uid;
8862        res.removedInfo.removedPackage = packageName;
8863        // Remove existing system package
8864        removePackageLI(oldPkgSetting, true);
8865        // writer
8866        synchronized (mPackages) {
8867            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
8868                // We didn't need to disable the .apk as a current system package,
8869                // which means we are replacing another update that is already
8870                // installed.  We need to make sure to delete the older one's .apk.
8871                res.removedInfo.args = createInstallArgs(0,
8872                        deletedPackage.applicationInfo.sourceDir,
8873                        deletedPackage.applicationInfo.publicSourceDir,
8874                        deletedPackage.applicationInfo.nativeLibraryDir);
8875            } else {
8876                res.removedInfo.args = null;
8877            }
8878        }
8879
8880        // Successfully disabled the old package. Now proceed with re-installation
8881        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8882        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8883        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
8884        if (newPackage == null) {
8885            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
8886            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8887                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8888            }
8889        } else {
8890            if (newPackage.mExtras != null) {
8891                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
8892                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
8893                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
8894            }
8895            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
8896            updatedSettings = true;
8897        }
8898
8899        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8900            // Re installation failed. Restore old information
8901            // Remove new pkg information
8902            if (newPackage != null) {
8903                removeInstalledPackageLI(newPackage, true);
8904            }
8905            // Add back the old system package
8906            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
8907            // Restore the old system information in Settings
8908            synchronized(mPackages) {
8909                if (updatedSettings) {
8910                    mSettings.enableSystemPackageLPw(packageName);
8911                    mSettings.setInstallerPackageName(packageName,
8912                            oldPkgSetting.installerPackageName);
8913                }
8914                mSettings.writeLPr();
8915            }
8916        }
8917    }
8918
8919    // Utility method used to move dex files during install.
8920    private int moveDexFilesLI(PackageParser.Package newPackage) {
8921        int retCode;
8922        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
8923            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
8924            if (retCode != 0) {
8925                if (mNoDexOpt) {
8926                    /*
8927                     * If we're in an engineering build, programs are lazily run
8928                     * through dexopt. If the .dex file doesn't exist yet, it
8929                     * will be created when the program is run next.
8930                     */
8931                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
8932                } else {
8933                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
8934                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8935                }
8936            }
8937        }
8938        return PackageManager.INSTALL_SUCCEEDED;
8939    }
8940
8941    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
8942            int[] allUsers, boolean[] perUserInstalled,
8943            PackageInstalledInfo res) {
8944        String pkgName = newPackage.packageName;
8945        synchronized (mPackages) {
8946            //write settings. the installStatus will be incomplete at this stage.
8947            //note that the new package setting would have already been
8948            //added to mPackages. It hasn't been persisted yet.
8949            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
8950            mSettings.writeLPr();
8951        }
8952
8953        if ((res.returnCode = moveDexFilesLI(newPackage))
8954                != PackageManager.INSTALL_SUCCEEDED) {
8955            // Discontinue if moving dex files failed.
8956            return;
8957        }
8958
8959        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
8960
8961        synchronized (mPackages) {
8962            updatePermissionsLPw(newPackage.packageName, newPackage,
8963                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
8964                            ? UPDATE_PERMISSIONS_ALL : 0));
8965            // For system-bundled packages, we assume that installing an upgraded version
8966            // of the package implies that the user actually wants to run that new code,
8967            // so we enable the package.
8968            if (isSystemApp(newPackage)) {
8969                // NB: implicit assumption that system package upgrades apply to all users
8970                if (DEBUG_INSTALL) {
8971                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
8972                }
8973                PackageSetting ps = mSettings.mPackages.get(pkgName);
8974                if (ps != null) {
8975                    if (res.origUsers != null) {
8976                        for (int userHandle : res.origUsers) {
8977                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
8978                                    userHandle, installerPackageName);
8979                        }
8980                    }
8981                    // Also convey the prior install/uninstall state
8982                    if (allUsers != null && perUserInstalled != null) {
8983                        for (int i = 0; i < allUsers.length; i++) {
8984                            if (DEBUG_INSTALL) {
8985                                Slog.d(TAG, "    user " + allUsers[i]
8986                                        + " => " + perUserInstalled[i]);
8987                            }
8988                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
8989                        }
8990                        // these install state changes will be persisted in the
8991                        // upcoming call to mSettings.writeLPr().
8992                    }
8993                }
8994            }
8995            res.name = pkgName;
8996            res.uid = newPackage.applicationInfo.uid;
8997            res.pkg = newPackage;
8998            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
8999            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9000            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9001            //to update install status
9002            mSettings.writeLPr();
9003        }
9004    }
9005
9006    private void installPackageLI(InstallArgs args,
9007            boolean newInstall, PackageInstalledInfo res) {
9008        int pFlags = args.flags;
9009        String installerPackageName = args.installerPackageName;
9010        File tmpPackageFile = new File(args.getCodePath());
9011        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9012        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9013        boolean replace = false;
9014        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9015                | (newInstall ? SCAN_NEW_INSTALL : 0);
9016        // Result object to be returned
9017        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9018
9019        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9020        // Retrieve PackageSettings and parse package
9021        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9022                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9023                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9024        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9025        pp.setSeparateProcesses(mSeparateProcesses);
9026        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9027                null, mMetrics, parseFlags);
9028        if (pkg == null) {
9029            res.returnCode = pp.getParseError();
9030            return;
9031        }
9032        String pkgName = res.name = pkg.packageName;
9033        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9034            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9035                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9036                return;
9037            }
9038        }
9039        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9040            res.returnCode = pp.getParseError();
9041            return;
9042        }
9043
9044        /* If the installer passed in a manifest digest, compare it now. */
9045        if (args.manifestDigest != null) {
9046            if (DEBUG_INSTALL) {
9047                final String parsedManifest = pkg.manifestDigest == null ? "null"
9048                        : pkg.manifestDigest.toString();
9049                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9050                        + parsedManifest);
9051            }
9052
9053            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9054                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9055                return;
9056            }
9057        } else if (DEBUG_INSTALL) {
9058            final String parsedManifest = pkg.manifestDigest == null
9059                    ? "null" : pkg.manifestDigest.toString();
9060            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9061        }
9062
9063        // Get rid of all references to package scan path via parser.
9064        pp = null;
9065        String oldCodePath = null;
9066        boolean systemApp = false;
9067        synchronized (mPackages) {
9068            // Check if installing already existing package
9069            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9070                String oldName = mSettings.mRenamedPackages.get(pkgName);
9071                if (pkg.mOriginalPackages != null
9072                        && pkg.mOriginalPackages.contains(oldName)
9073                        && mPackages.containsKey(oldName)) {
9074                    // This package is derived from an original package,
9075                    // and this device has been updating from that original
9076                    // name.  We must continue using the original name, so
9077                    // rename the new package here.
9078                    pkg.setPackageName(oldName);
9079                    pkgName = pkg.packageName;
9080                    replace = true;
9081                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9082                            + oldName + " pkgName=" + pkgName);
9083                } else if (mPackages.containsKey(pkgName)) {
9084                    // This package, under its official name, already exists
9085                    // on the device; we should replace it.
9086                    replace = true;
9087                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9088                }
9089            }
9090            PackageSetting ps = mSettings.mPackages.get(pkgName);
9091            if (ps != null) {
9092                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9093                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9094                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9095                    systemApp = (ps.pkg.applicationInfo.flags &
9096                            ApplicationInfo.FLAG_SYSTEM) != 0;
9097                }
9098                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9099            }
9100        }
9101
9102        if (systemApp && onSd) {
9103            // Disable updates to system apps on sdcard
9104            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9105            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9106            return;
9107        }
9108
9109        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9110            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9111            return;
9112        }
9113        // Set application objects path explicitly after the rename
9114        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9115        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9116        if (replace) {
9117            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9118                    installerPackageName, res);
9119        } else {
9120            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9121                    installerPackageName, res);
9122        }
9123        synchronized (mPackages) {
9124            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9125            if (ps != null) {
9126                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9127            }
9128        }
9129    }
9130
9131    private static boolean isForwardLocked(PackageParser.Package pkg) {
9132        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9133    }
9134
9135
9136    private boolean isForwardLocked(PackageSetting ps) {
9137        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9138    }
9139
9140    private static boolean isExternal(PackageParser.Package pkg) {
9141        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9142    }
9143
9144    private static boolean isExternal(PackageSetting ps) {
9145        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9146    }
9147
9148    private static boolean isSystemApp(PackageParser.Package pkg) {
9149        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9150    }
9151
9152    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9153        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9154    }
9155
9156    private static boolean isSystemApp(ApplicationInfo info) {
9157        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9158    }
9159
9160    private static boolean isSystemApp(PackageSetting ps) {
9161        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9162    }
9163
9164    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9165        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9166    }
9167
9168    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9169        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9170    }
9171
9172    private int packageFlagsToInstallFlags(PackageSetting ps) {
9173        int installFlags = 0;
9174        if (isExternal(ps)) {
9175            installFlags |= PackageManager.INSTALL_EXTERNAL;
9176        }
9177        if (isForwardLocked(ps)) {
9178            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9179        }
9180        return installFlags;
9181    }
9182
9183    private void deleteTempPackageFiles() {
9184        final FilenameFilter filter = new FilenameFilter() {
9185            public boolean accept(File dir, String name) {
9186                return name.startsWith("vmdl") && name.endsWith(".tmp");
9187            }
9188        };
9189        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9190        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9191    }
9192
9193    private static final void deleteTempPackageFilesInDirectory(File directory,
9194            FilenameFilter filter) {
9195        final String[] tmpFilesList = directory.list(filter);
9196        if (tmpFilesList == null) {
9197            return;
9198        }
9199        for (int i = 0; i < tmpFilesList.length; i++) {
9200            final File tmpFile = new File(directory, tmpFilesList[i]);
9201            tmpFile.delete();
9202        }
9203    }
9204
9205    private File createTempPackageFile(File installDir) {
9206        File tmpPackageFile;
9207        try {
9208            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9209        } catch (IOException e) {
9210            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9211            return null;
9212        }
9213        try {
9214            FileUtils.setPermissions(
9215                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9216                    -1, -1);
9217            if (!SELinux.restorecon(tmpPackageFile)) {
9218                return null;
9219            }
9220        } catch (IOException e) {
9221            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9222            return null;
9223        }
9224        return tmpPackageFile;
9225    }
9226
9227    @Override
9228    public void deletePackageAsUser(final String packageName,
9229                                    final IPackageDeleteObserver observer,
9230                                    final int userId, final int flags) {
9231        mContext.enforceCallingOrSelfPermission(
9232                android.Manifest.permission.DELETE_PACKAGES, null);
9233        final int uid = Binder.getCallingUid();
9234        if (UserHandle.getUserId(uid) != userId) {
9235            mContext.enforceCallingPermission(
9236                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9237                    "deletePackage for user " + userId);
9238        }
9239        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9240            try {
9241                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9242            } catch (RemoteException re) {
9243            }
9244            return;
9245        }
9246
9247        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9248        // Queue up an async operation since the package deletion may take a little while.
9249        mHandler.post(new Runnable() {
9250            public void run() {
9251                mHandler.removeCallbacks(this);
9252                final int returnCode = deletePackageX(packageName, userId, flags);
9253                if (observer != null) {
9254                    try {
9255                        observer.packageDeleted(packageName, returnCode);
9256                    } catch (RemoteException e) {
9257                        Log.i(TAG, "Observer no longer exists.");
9258                    } //end catch
9259                } //end if
9260            } //end run
9261        });
9262    }
9263
9264    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9265        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9266                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9267        try {
9268            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9269                    || dpm.isDeviceOwner(packageName))) {
9270                return true;
9271            }
9272        } catch (RemoteException e) {
9273        }
9274        return false;
9275    }
9276
9277    /**
9278     *  This method is an internal method that could be get invoked either
9279     *  to delete an installed package or to clean up a failed installation.
9280     *  After deleting an installed package, a broadcast is sent to notify any
9281     *  listeners that the package has been installed. For cleaning up a failed
9282     *  installation, the broadcast is not necessary since the package's
9283     *  installation wouldn't have sent the initial broadcast either
9284     *  The key steps in deleting a package are
9285     *  deleting the package information in internal structures like mPackages,
9286     *  deleting the packages base directories through installd
9287     *  updating mSettings to reflect current status
9288     *  persisting settings for later use
9289     *  sending a broadcast if necessary
9290     */
9291    private int deletePackageX(String packageName, int userId, int flags) {
9292        final PackageRemovedInfo info = new PackageRemovedInfo();
9293        final boolean res;
9294
9295        if (isPackageDeviceAdmin(packageName, userId)) {
9296            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9297            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9298        }
9299
9300        boolean removedForAllUsers = false;
9301        boolean systemUpdate = false;
9302
9303        // for the uninstall-updates case and restricted profiles, remember the per-
9304        // userhandle installed state
9305        int[] allUsers;
9306        boolean[] perUserInstalled;
9307        synchronized (mPackages) {
9308            PackageSetting ps = mSettings.mPackages.get(packageName);
9309            allUsers = sUserManager.getUserIds();
9310            perUserInstalled = new boolean[allUsers.length];
9311            for (int i = 0; i < allUsers.length; i++) {
9312                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9313            }
9314        }
9315
9316        synchronized (mInstallLock) {
9317            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9318            res = deletePackageLI(packageName,
9319                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9320                            ? UserHandle.ALL : new UserHandle(userId),
9321                    true, allUsers, perUserInstalled,
9322                    flags | REMOVE_CHATTY, info, true);
9323            systemUpdate = info.isRemovedPackageSystemUpdate;
9324            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9325                removedForAllUsers = true;
9326            }
9327            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9328                    + " removedForAllUsers=" + removedForAllUsers);
9329        }
9330
9331        if (res) {
9332            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9333
9334            // If the removed package was a system update, the old system package
9335            // was re-enabled; we need to broadcast this information
9336            if (systemUpdate) {
9337                Bundle extras = new Bundle(1);
9338                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9339                        ? info.removedAppId : info.uid);
9340                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9341
9342                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9343                        extras, null, null, null);
9344                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9345                        extras, null, null, null);
9346                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9347                        null, packageName, null, null);
9348            }
9349        }
9350        // Force a gc here.
9351        Runtime.getRuntime().gc();
9352        // Delete the resources here after sending the broadcast to let
9353        // other processes clean up before deleting resources.
9354        if (info.args != null) {
9355            synchronized (mInstallLock) {
9356                info.args.doPostDeleteLI(true);
9357            }
9358        }
9359
9360        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9361    }
9362
9363    static class PackageRemovedInfo {
9364        String removedPackage;
9365        int uid = -1;
9366        int removedAppId = -1;
9367        int[] removedUsers = null;
9368        boolean isRemovedPackageSystemUpdate = false;
9369        // Clean up resources deleted packages.
9370        InstallArgs args = null;
9371
9372        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9373            Bundle extras = new Bundle(1);
9374            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9375            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9376            if (replacing) {
9377                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9378            }
9379            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9380            if (removedPackage != null) {
9381                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9382                        extras, null, null, removedUsers);
9383                if (fullRemove && !replacing) {
9384                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9385                            extras, null, null, removedUsers);
9386                }
9387            }
9388            if (removedAppId >= 0) {
9389                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9390                        removedUsers);
9391            }
9392        }
9393    }
9394
9395    /*
9396     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9397     * flag is not set, the data directory is removed as well.
9398     * make sure this flag is set for partially installed apps. If not its meaningless to
9399     * delete a partially installed application.
9400     */
9401    private void removePackageDataLI(PackageSetting ps,
9402            int[] allUserHandles, boolean[] perUserInstalled,
9403            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9404        String packageName = ps.name;
9405        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9406        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9407        // Retrieve object to delete permissions for shared user later on
9408        final PackageSetting deletedPs;
9409        // reader
9410        synchronized (mPackages) {
9411            deletedPs = mSettings.mPackages.get(packageName);
9412            if (outInfo != null) {
9413                outInfo.removedPackage = packageName;
9414                outInfo.removedUsers = deletedPs != null
9415                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9416                        : null;
9417            }
9418        }
9419        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9420            removeDataDirsLI(packageName);
9421            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9422        }
9423        // writer
9424        synchronized (mPackages) {
9425            if (deletedPs != null) {
9426                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9427                    if (outInfo != null) {
9428                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9429                    }
9430                    if (deletedPs != null) {
9431                        updatePermissionsLPw(deletedPs.name, null, 0);
9432                        if (deletedPs.sharedUser != null) {
9433                            // remove permissions associated with package
9434                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9435                        }
9436                    }
9437                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9438                }
9439                // make sure to preserve per-user disabled state if this removal was just
9440                // a downgrade of a system app to the factory package
9441                if (allUserHandles != null && perUserInstalled != null) {
9442                    if (DEBUG_REMOVE) {
9443                        Slog.d(TAG, "Propagating install state across downgrade");
9444                    }
9445                    for (int i = 0; i < allUserHandles.length; i++) {
9446                        if (DEBUG_REMOVE) {
9447                            Slog.d(TAG, "    user " + allUserHandles[i]
9448                                    + " => " + perUserInstalled[i]);
9449                        }
9450                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9451                    }
9452                }
9453            }
9454            // can downgrade to reader
9455            if (writeSettings) {
9456                // Save settings now
9457                mSettings.writeLPr();
9458            }
9459        }
9460        if (outInfo != null) {
9461            // A user ID was deleted here. Go through all users and remove it
9462            // from KeyStore.
9463            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9464        }
9465    }
9466
9467    static boolean locationIsPrivileged(File path) {
9468        try {
9469            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9470                    .getCanonicalPath();
9471            return path.getCanonicalPath().startsWith(privilegedAppDir);
9472        } catch (IOException e) {
9473            Slog.e(TAG, "Unable to access code path " + path);
9474        }
9475        return false;
9476    }
9477
9478    /*
9479     * Tries to delete system package.
9480     */
9481    private boolean deleteSystemPackageLI(PackageSetting newPs,
9482            int[] allUserHandles, boolean[] perUserInstalled,
9483            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
9484        final boolean applyUserRestrictions
9485                = (allUserHandles != null) && (perUserInstalled != null);
9486        PackageSetting disabledPs = null;
9487        // Confirm if the system package has been updated
9488        // An updated system app can be deleted. This will also have to restore
9489        // the system pkg from system partition
9490        // reader
9491        synchronized (mPackages) {
9492            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
9493        }
9494        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
9495                + " disabledPs=" + disabledPs);
9496        if (disabledPs == null) {
9497            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
9498            return false;
9499        } else if (DEBUG_REMOVE) {
9500            Slog.d(TAG, "Deleting system pkg from data partition");
9501        }
9502        if (DEBUG_REMOVE) {
9503            if (applyUserRestrictions) {
9504                Slog.d(TAG, "Remembering install states:");
9505                for (int i = 0; i < allUserHandles.length; i++) {
9506                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
9507                }
9508            }
9509        }
9510        // Delete the updated package
9511        outInfo.isRemovedPackageSystemUpdate = true;
9512        if (disabledPs.versionCode < newPs.versionCode) {
9513            // Delete data for downgrades
9514            flags &= ~PackageManager.DELETE_KEEP_DATA;
9515        } else {
9516            // Preserve data by setting flag
9517            flags |= PackageManager.DELETE_KEEP_DATA;
9518        }
9519        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
9520                allUserHandles, perUserInstalled, outInfo, writeSettings);
9521        if (!ret) {
9522            return false;
9523        }
9524        // writer
9525        synchronized (mPackages) {
9526            // Reinstate the old system package
9527            mSettings.enableSystemPackageLPw(newPs.name);
9528            // Remove any native libraries from the upgraded package.
9529            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
9530        }
9531        // Install the system package
9532        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
9533        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
9534        if (locationIsPrivileged(disabledPs.codePath)) {
9535            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9536        }
9537        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
9538                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
9539
9540        if (newPkg == null) {
9541            Slog.w(TAG, "Failed to restore system package:" + newPs.name
9542                    + " with error:" + mLastScanError);
9543            return false;
9544        }
9545        // writer
9546        synchronized (mPackages) {
9547            updatePermissionsLPw(newPkg.packageName, newPkg,
9548                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
9549            if (applyUserRestrictions) {
9550                if (DEBUG_REMOVE) {
9551                    Slog.d(TAG, "Propagating install state across reinstall");
9552                }
9553                PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
9554                for (int i = 0; i < allUserHandles.length; i++) {
9555                    if (DEBUG_REMOVE) {
9556                        Slog.d(TAG, "    user " + allUserHandles[i]
9557                                + " => " + perUserInstalled[i]);
9558                    }
9559                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9560                }
9561                // Regardless of writeSettings we need to ensure that this restriction
9562                // state propagation is persisted
9563                mSettings.writeAllUsersPackageRestrictionsLPr();
9564            }
9565            // can downgrade to reader here
9566            if (writeSettings) {
9567                mSettings.writeLPr();
9568            }
9569        }
9570        return true;
9571    }
9572
9573    private boolean deleteInstalledPackageLI(PackageSetting ps,
9574            boolean deleteCodeAndResources, int flags,
9575            int[] allUserHandles, boolean[] perUserInstalled,
9576            PackageRemovedInfo outInfo, boolean writeSettings) {
9577        if (outInfo != null) {
9578            outInfo.uid = ps.appId;
9579        }
9580
9581        // Delete package data from internal structures and also remove data if flag is set
9582        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
9583
9584        // Delete application code and resources
9585        if (deleteCodeAndResources && (outInfo != null)) {
9586            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
9587                    ps.resourcePathString, ps.nativeLibraryPathString);
9588        }
9589        return true;
9590    }
9591
9592    /*
9593     * This method handles package deletion in general
9594     */
9595    private boolean deletePackageLI(String packageName, UserHandle user,
9596            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
9597            int flags, PackageRemovedInfo outInfo,
9598            boolean writeSettings) {
9599        if (packageName == null) {
9600            Slog.w(TAG, "Attempt to delete null packageName.");
9601            return false;
9602        }
9603        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
9604        PackageSetting ps;
9605        boolean dataOnly = false;
9606        int removeUser = -1;
9607        int appId = -1;
9608        synchronized (mPackages) {
9609            ps = mSettings.mPackages.get(packageName);
9610            if (ps == null) {
9611                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9612                return false;
9613            }
9614            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
9615                    && user.getIdentifier() != UserHandle.USER_ALL) {
9616                // The caller is asking that the package only be deleted for a single
9617                // user.  To do this, we just mark its uninstalled state and delete
9618                // its data.  If this is a system app, we only allow this to happen if
9619                // they have set the special DELETE_SYSTEM_APP which requests different
9620                // semantics than normal for uninstalling system apps.
9621                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
9622                ps.setUserState(user.getIdentifier(),
9623                        COMPONENT_ENABLED_STATE_DEFAULT,
9624                        false, //installed
9625                        true,  //stopped
9626                        true,  //notLaunched
9627                        false, //blocked
9628                        null, null, null);
9629                if (!isSystemApp(ps)) {
9630                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
9631                        // Other user still have this package installed, so all
9632                        // we need to do is clear this user's data and save that
9633                        // it is uninstalled.
9634                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
9635                        removeUser = user.getIdentifier();
9636                        appId = ps.appId;
9637                        mSettings.writePackageRestrictionsLPr(removeUser);
9638                    } else {
9639                        // We need to set it back to 'installed' so the uninstall
9640                        // broadcasts will be sent correctly.
9641                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
9642                        ps.setInstalled(true, user.getIdentifier());
9643                    }
9644                } else {
9645                    // This is a system app, so we assume that the
9646                    // other users still have this package installed, so all
9647                    // we need to do is clear this user's data and save that
9648                    // it is uninstalled.
9649                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
9650                    removeUser = user.getIdentifier();
9651                    appId = ps.appId;
9652                    mSettings.writePackageRestrictionsLPr(removeUser);
9653                }
9654            }
9655        }
9656
9657        if (removeUser >= 0) {
9658            // From above, we determined that we are deleting this only
9659            // for a single user.  Continue the work here.
9660            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
9661            if (outInfo != null) {
9662                outInfo.removedPackage = packageName;
9663                outInfo.removedAppId = appId;
9664                outInfo.removedUsers = new int[] {removeUser};
9665            }
9666            mInstaller.clearUserData(packageName, removeUser);
9667            removeKeystoreDataIfNeeded(removeUser, appId);
9668            schedulePackageCleaning(packageName, removeUser, false);
9669            return true;
9670        }
9671
9672        if (dataOnly) {
9673            // Delete application data first
9674            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
9675            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
9676            return true;
9677        }
9678
9679        boolean ret = false;
9680        mSettings.mKeySetManager.removeAppKeySetData(packageName);
9681        if (isSystemApp(ps)) {
9682            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
9683            // When an updated system application is deleted we delete the existing resources as well and
9684            // fall back to existing code in system partition
9685            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
9686                    flags, outInfo, writeSettings);
9687        } else {
9688            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
9689            // Kill application pre-emptively especially for apps on sd.
9690            killApplication(packageName, ps.appId, "uninstall pkg");
9691            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
9692                    allUserHandles, perUserInstalled,
9693                    outInfo, writeSettings);
9694        }
9695
9696        return ret;
9697    }
9698
9699    private final class ClearStorageConnection implements ServiceConnection {
9700        IMediaContainerService mContainerService;
9701
9702        @Override
9703        public void onServiceConnected(ComponentName name, IBinder service) {
9704            synchronized (this) {
9705                mContainerService = IMediaContainerService.Stub.asInterface(service);
9706                notifyAll();
9707            }
9708        }
9709
9710        @Override
9711        public void onServiceDisconnected(ComponentName name) {
9712        }
9713    }
9714
9715    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
9716        final boolean mounted;
9717        if (Environment.isExternalStorageEmulated()) {
9718            mounted = true;
9719        } else {
9720            final String status = Environment.getExternalStorageState();
9721
9722            mounted = status.equals(Environment.MEDIA_MOUNTED)
9723                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
9724        }
9725
9726        if (!mounted) {
9727            return;
9728        }
9729
9730        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
9731        int[] users;
9732        if (userId == UserHandle.USER_ALL) {
9733            users = sUserManager.getUserIds();
9734        } else {
9735            users = new int[] { userId };
9736        }
9737        final ClearStorageConnection conn = new ClearStorageConnection();
9738        if (mContext.bindServiceAsUser(
9739                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
9740            try {
9741                for (int curUser : users) {
9742                    long timeout = SystemClock.uptimeMillis() + 5000;
9743                    synchronized (conn) {
9744                        long now = SystemClock.uptimeMillis();
9745                        while (conn.mContainerService == null && now < timeout) {
9746                            try {
9747                                conn.wait(timeout - now);
9748                            } catch (InterruptedException e) {
9749                            }
9750                        }
9751                    }
9752                    if (conn.mContainerService == null) {
9753                        return;
9754                    }
9755
9756                    final UserEnvironment userEnv = new UserEnvironment(curUser);
9757                    clearDirectory(conn.mContainerService,
9758                            userEnv.buildExternalStorageAppCacheDirs(packageName));
9759                    if (allData) {
9760                        clearDirectory(conn.mContainerService,
9761                                userEnv.buildExternalStorageAppDataDirs(packageName));
9762                        clearDirectory(conn.mContainerService,
9763                                userEnv.buildExternalStorageAppMediaDirs(packageName));
9764                    }
9765                }
9766            } finally {
9767                mContext.unbindService(conn);
9768            }
9769        }
9770    }
9771
9772    @Override
9773    public void clearApplicationUserData(final String packageName,
9774            final IPackageDataObserver observer, final int userId) {
9775        mContext.enforceCallingOrSelfPermission(
9776                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
9777        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
9778        // Queue up an async operation since the package deletion may take a little while.
9779        mHandler.post(new Runnable() {
9780            public void run() {
9781                mHandler.removeCallbacks(this);
9782                final boolean succeeded;
9783                synchronized (mInstallLock) {
9784                    succeeded = clearApplicationUserDataLI(packageName, userId);
9785                }
9786                clearExternalStorageDataSync(packageName, userId, true);
9787                if (succeeded) {
9788                    // invoke DeviceStorageMonitor's update method to clear any notifications
9789                    DeviceStorageMonitorInternal
9790                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9791                    if (dsm != null) {
9792                        dsm.checkMemory();
9793                    }
9794                }
9795                if(observer != null) {
9796                    try {
9797                        observer.onRemoveCompleted(packageName, succeeded);
9798                    } catch (RemoteException e) {
9799                        Log.i(TAG, "Observer no longer exists.");
9800                    }
9801                } //end if observer
9802            } //end run
9803        });
9804    }
9805
9806    private boolean clearApplicationUserDataLI(String packageName, int userId) {
9807        if (packageName == null) {
9808            Slog.w(TAG, "Attempt to delete null packageName.");
9809            return false;
9810        }
9811        PackageParser.Package p;
9812        boolean dataOnly = false;
9813        final int appId;
9814        synchronized (mPackages) {
9815            p = mPackages.get(packageName);
9816            if (p == null) {
9817                dataOnly = true;
9818                PackageSetting ps = mSettings.mPackages.get(packageName);
9819                if ((ps == null) || (ps.pkg == null)) {
9820                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9821                    return false;
9822                }
9823                p = ps.pkg;
9824            }
9825            if (!dataOnly) {
9826                // need to check this only for fully installed applications
9827                if (p == null) {
9828                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9829                    return false;
9830                }
9831                final ApplicationInfo applicationInfo = p.applicationInfo;
9832                if (applicationInfo == null) {
9833                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
9834                    return false;
9835                }
9836            }
9837            if (p != null && p.applicationInfo != null) {
9838                appId = p.applicationInfo.uid;
9839            } else {
9840                appId = -1;
9841            }
9842        }
9843        int retCode = mInstaller.clearUserData(packageName, userId);
9844        if (retCode < 0) {
9845            Slog.w(TAG, "Couldn't remove cache files for package: "
9846                    + packageName);
9847            return false;
9848        }
9849        removeKeystoreDataIfNeeded(userId, appId);
9850        return true;
9851    }
9852
9853    /**
9854     * Remove entries from the keystore daemon. Will only remove it if the
9855     * {@code appId} is valid.
9856     */
9857    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
9858        if (appId < 0) {
9859            return;
9860        }
9861
9862        final KeyStore keyStore = KeyStore.getInstance();
9863        if (keyStore != null) {
9864            if (userId == UserHandle.USER_ALL) {
9865                for (final int individual : sUserManager.getUserIds()) {
9866                    keyStore.clearUid(UserHandle.getUid(individual, appId));
9867                }
9868            } else {
9869                keyStore.clearUid(UserHandle.getUid(userId, appId));
9870            }
9871        } else {
9872            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
9873        }
9874    }
9875
9876    public void deleteApplicationCacheFiles(final String packageName,
9877            final IPackageDataObserver observer) {
9878        mContext.enforceCallingOrSelfPermission(
9879                android.Manifest.permission.DELETE_CACHE_FILES, null);
9880        // Queue up an async operation since the package deletion may take a little while.
9881        final int userId = UserHandle.getCallingUserId();
9882        mHandler.post(new Runnable() {
9883            public void run() {
9884                mHandler.removeCallbacks(this);
9885                final boolean succeded;
9886                synchronized (mInstallLock) {
9887                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
9888                }
9889                clearExternalStorageDataSync(packageName, userId, false);
9890                if(observer != null) {
9891                    try {
9892                        observer.onRemoveCompleted(packageName, succeded);
9893                    } catch (RemoteException e) {
9894                        Log.i(TAG, "Observer no longer exists.");
9895                    }
9896                } //end if observer
9897            } //end run
9898        });
9899    }
9900
9901    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
9902        if (packageName == null) {
9903            Slog.w(TAG, "Attempt to delete null packageName.");
9904            return false;
9905        }
9906        PackageParser.Package p;
9907        synchronized (mPackages) {
9908            p = mPackages.get(packageName);
9909        }
9910        if (p == null) {
9911            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
9912            return false;
9913        }
9914        final ApplicationInfo applicationInfo = p.applicationInfo;
9915        if (applicationInfo == null) {
9916            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
9917            return false;
9918        }
9919        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
9920        if (retCode < 0) {
9921            Slog.w(TAG, "Couldn't remove cache files for package: "
9922                       + packageName + " u" + userId);
9923            return false;
9924        }
9925        return true;
9926    }
9927
9928    public void getPackageSizeInfo(final String packageName, int userHandle,
9929            final IPackageStatsObserver observer) {
9930        mContext.enforceCallingOrSelfPermission(
9931                android.Manifest.permission.GET_PACKAGE_SIZE, null);
9932
9933        PackageStats stats = new PackageStats(packageName, userHandle);
9934
9935        /*
9936         * Queue up an async operation since the package measurement may take a
9937         * little while.
9938         */
9939        Message msg = mHandler.obtainMessage(INIT_COPY);
9940        msg.obj = new MeasureParams(stats, observer);
9941        mHandler.sendMessage(msg);
9942    }
9943
9944    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
9945            PackageStats pStats) {
9946        if (packageName == null) {
9947            Slog.w(TAG, "Attempt to get size of null packageName.");
9948            return false;
9949        }
9950        PackageParser.Package p;
9951        boolean dataOnly = false;
9952        String libDirPath = null;
9953        String asecPath = null;
9954        synchronized (mPackages) {
9955            p = mPackages.get(packageName);
9956            PackageSetting ps = mSettings.mPackages.get(packageName);
9957            if(p == null) {
9958                dataOnly = true;
9959                if((ps == null) || (ps.pkg == null)) {
9960                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
9961                    return false;
9962                }
9963                p = ps.pkg;
9964            }
9965            if (ps != null) {
9966                libDirPath = ps.nativeLibraryPathString;
9967            }
9968            if (p != null && (isExternal(p) || isForwardLocked(p))) {
9969                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
9970                if (secureContainerId != null) {
9971                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
9972                }
9973            }
9974        }
9975        String publicSrcDir = null;
9976        if(!dataOnly) {
9977            final ApplicationInfo applicationInfo = p.applicationInfo;
9978            if (applicationInfo == null) {
9979                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
9980                return false;
9981            }
9982            if (isForwardLocked(p)) {
9983                publicSrcDir = applicationInfo.publicSourceDir;
9984            }
9985        }
9986        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
9987                publicSrcDir, asecPath, pStats);
9988        if (res < 0) {
9989            return false;
9990        }
9991
9992        // Fix-up for forward-locked applications in ASEC containers.
9993        if (!isExternal(p)) {
9994            pStats.codeSize += pStats.externalCodeSize;
9995            pStats.externalCodeSize = 0L;
9996        }
9997
9998        return true;
9999    }
10000
10001
10002    public void addPackageToPreferred(String packageName) {
10003        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10004    }
10005
10006    public void removePackageFromPreferred(String packageName) {
10007        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10008    }
10009
10010    public List<PackageInfo> getPreferredPackages(int flags) {
10011        return new ArrayList<PackageInfo>();
10012    }
10013
10014    private int getUidTargetSdkVersionLockedLPr(int uid) {
10015        Object obj = mSettings.getUserIdLPr(uid);
10016        if (obj instanceof SharedUserSetting) {
10017            final SharedUserSetting sus = (SharedUserSetting) obj;
10018            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10019            final Iterator<PackageSetting> it = sus.packages.iterator();
10020            while (it.hasNext()) {
10021                final PackageSetting ps = it.next();
10022                if (ps.pkg != null) {
10023                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10024                    if (v < vers) vers = v;
10025                }
10026            }
10027            return vers;
10028        } else if (obj instanceof PackageSetting) {
10029            final PackageSetting ps = (PackageSetting) obj;
10030            if (ps.pkg != null) {
10031                return ps.pkg.applicationInfo.targetSdkVersion;
10032            }
10033        }
10034        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10035    }
10036
10037    public void addPreferredActivity(IntentFilter filter, int match,
10038            ComponentName[] set, ComponentName activity, int userId) {
10039        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10040    }
10041
10042    private void addPreferredActivityInternal(IntentFilter filter, int match,
10043            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10044        // writer
10045        int callingUid = Binder.getCallingUid();
10046        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10047        if (filter.countActions() == 0) {
10048            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10049            return;
10050        }
10051        synchronized (mPackages) {
10052            if (mContext.checkCallingOrSelfPermission(
10053                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10054                    != PackageManager.PERMISSION_GRANTED) {
10055                if (getUidTargetSdkVersionLockedLPr(callingUid)
10056                        < Build.VERSION_CODES.FROYO) {
10057                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10058                            + callingUid);
10059                    return;
10060                }
10061                mContext.enforceCallingOrSelfPermission(
10062                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10063            }
10064
10065            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10066            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10067            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10068                    new PreferredActivity(filter, match, set, activity, always));
10069            mSettings.writePackageRestrictionsLPr(userId);
10070        }
10071    }
10072
10073    public void replacePreferredActivity(IntentFilter filter, int match,
10074            ComponentName[] set, ComponentName activity) {
10075        if (filter.countActions() != 1) {
10076            throw new IllegalArgumentException(
10077                    "replacePreferredActivity expects filter to have only 1 action.");
10078        }
10079        if (filter.countDataAuthorities() != 0
10080                || filter.countDataPaths() != 0
10081                || filter.countDataSchemes() > 1
10082                || filter.countDataTypes() != 0) {
10083            throw new IllegalArgumentException(
10084                    "replacePreferredActivity expects filter to have no data authorities, " +
10085                    "paths, or types; and at most one scheme.");
10086        }
10087        synchronized (mPackages) {
10088            if (mContext.checkCallingOrSelfPermission(
10089                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10090                    != PackageManager.PERMISSION_GRANTED) {
10091                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10092                        < Build.VERSION_CODES.FROYO) {
10093                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10094                            + Binder.getCallingUid());
10095                    return;
10096                }
10097                mContext.enforceCallingOrSelfPermission(
10098                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10099            }
10100
10101            final int callingUserId = UserHandle.getCallingUserId();
10102            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10103            if (pir != null) {
10104                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10105                if (filter.countDataSchemes() == 1) {
10106                    Uri.Builder builder = new Uri.Builder();
10107                    builder.scheme(filter.getDataScheme(0));
10108                    intent.setData(builder.build());
10109                }
10110                List<PreferredActivity> matches = pir.queryIntent(
10111                        intent, null, true, callingUserId);
10112                if (DEBUG_PREFERRED) {
10113                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10114                }
10115                for (int i = 0; i < matches.size(); i++) {
10116                    PreferredActivity pa = matches.get(i);
10117                    if (DEBUG_PREFERRED) {
10118                        Slog.i(TAG, "Removing preferred activity "
10119                                + pa.mPref.mComponent + ":");
10120                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10121                    }
10122                    pir.removeFilter(pa);
10123                }
10124            }
10125            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10126        }
10127    }
10128
10129    public void clearPackagePreferredActivities(String packageName) {
10130        final int uid = Binder.getCallingUid();
10131        // writer
10132        synchronized (mPackages) {
10133            PackageParser.Package pkg = mPackages.get(packageName);
10134            if (pkg == null || pkg.applicationInfo.uid != uid) {
10135                if (mContext.checkCallingOrSelfPermission(
10136                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10137                        != PackageManager.PERMISSION_GRANTED) {
10138                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10139                            < Build.VERSION_CODES.FROYO) {
10140                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10141                                + Binder.getCallingUid());
10142                        return;
10143                    }
10144                    mContext.enforceCallingOrSelfPermission(
10145                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10146                }
10147            }
10148
10149            int user = UserHandle.getCallingUserId();
10150            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10151                mSettings.writePackageRestrictionsLPr(user);
10152                scheduleWriteSettingsLocked();
10153            }
10154        }
10155    }
10156
10157    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10158    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10159        ArrayList<PreferredActivity> removed = null;
10160        boolean changed = false;
10161        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10162            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10163            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10164            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10165                continue;
10166            }
10167            Iterator<PreferredActivity> it = pir.filterIterator();
10168            while (it.hasNext()) {
10169                PreferredActivity pa = it.next();
10170                // Mark entry for removal only if it matches the package name
10171                // and the entry is of type "always".
10172                if (packageName == null ||
10173                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10174                                && pa.mPref.mAlways)) {
10175                    if (removed == null) {
10176                        removed = new ArrayList<PreferredActivity>();
10177                    }
10178                    removed.add(pa);
10179                }
10180            }
10181            if (removed != null) {
10182                for (int j=0; j<removed.size(); j++) {
10183                    PreferredActivity pa = removed.get(j);
10184                    pir.removeFilter(pa);
10185                }
10186                changed = true;
10187            }
10188        }
10189        return changed;
10190    }
10191
10192    public void resetPreferredActivities(int userId) {
10193        mContext.enforceCallingOrSelfPermission(
10194                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10195        // writer
10196        synchronized (mPackages) {
10197            int user = UserHandle.getCallingUserId();
10198            clearPackagePreferredActivitiesLPw(null, user);
10199            mSettings.readDefaultPreferredAppsLPw(this, user);
10200            mSettings.writePackageRestrictionsLPr(user);
10201            scheduleWriteSettingsLocked();
10202        }
10203    }
10204
10205    public int getPreferredActivities(List<IntentFilter> outFilters,
10206            List<ComponentName> outActivities, String packageName) {
10207
10208        int num = 0;
10209        final int userId = UserHandle.getCallingUserId();
10210        // reader
10211        synchronized (mPackages) {
10212            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10213            if (pir != null) {
10214                final Iterator<PreferredActivity> it = pir.filterIterator();
10215                while (it.hasNext()) {
10216                    final PreferredActivity pa = it.next();
10217                    if (packageName == null
10218                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10219                                    && pa.mPref.mAlways)) {
10220                        if (outFilters != null) {
10221                            outFilters.add(new IntentFilter(pa));
10222                        }
10223                        if (outActivities != null) {
10224                            outActivities.add(pa.mPref.mComponent);
10225                        }
10226                    }
10227                }
10228            }
10229        }
10230
10231        return num;
10232    }
10233
10234    @Override
10235    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10236        Intent intent = new Intent(Intent.ACTION_MAIN);
10237        intent.addCategory(Intent.CATEGORY_HOME);
10238
10239        final int callingUserId = UserHandle.getCallingUserId();
10240        List<ResolveInfo> list = queryIntentActivities(intent, null,
10241                PackageManager.GET_META_DATA, callingUserId);
10242        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10243                true, false, false, callingUserId);
10244
10245        allHomeCandidates.clear();
10246        if (list != null) {
10247            for (ResolveInfo ri : list) {
10248                allHomeCandidates.add(ri);
10249            }
10250        }
10251        return (preferred == null || preferred.activityInfo == null)
10252                ? null
10253                : new ComponentName(preferred.activityInfo.packageName,
10254                        preferred.activityInfo.name);
10255    }
10256
10257    @Override
10258    public void setApplicationEnabledSetting(String appPackageName,
10259            int newState, int flags, int userId, String callingPackage) {
10260        if (!sUserManager.exists(userId)) return;
10261        if (callingPackage == null) {
10262            callingPackage = Integer.toString(Binder.getCallingUid());
10263        }
10264        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10265    }
10266
10267    @Override
10268    public void setComponentEnabledSetting(ComponentName componentName,
10269            int newState, int flags, int userId) {
10270        if (!sUserManager.exists(userId)) return;
10271        setEnabledSetting(componentName.getPackageName(),
10272                componentName.getClassName(), newState, flags, userId, null);
10273    }
10274
10275    private void setEnabledSetting(final String packageName, String className, int newState,
10276            final int flags, int userId, String callingPackage) {
10277        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10278              || newState == COMPONENT_ENABLED_STATE_ENABLED
10279              || newState == COMPONENT_ENABLED_STATE_DISABLED
10280              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10281              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10282            throw new IllegalArgumentException("Invalid new component state: "
10283                    + newState);
10284        }
10285        PackageSetting pkgSetting;
10286        final int uid = Binder.getCallingUid();
10287        final int permission = mContext.checkCallingOrSelfPermission(
10288                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10289        enforceCrossUserPermission(uid, userId, false, "set enabled");
10290        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10291        boolean sendNow = false;
10292        boolean isApp = (className == null);
10293        String componentName = isApp ? packageName : className;
10294        int packageUid = -1;
10295        ArrayList<String> components;
10296
10297        // writer
10298        synchronized (mPackages) {
10299            pkgSetting = mSettings.mPackages.get(packageName);
10300            if (pkgSetting == null) {
10301                if (className == null) {
10302                    throw new IllegalArgumentException(
10303                            "Unknown package: " + packageName);
10304                }
10305                throw new IllegalArgumentException(
10306                        "Unknown component: " + packageName
10307                        + "/" + className);
10308            }
10309            // Allow root and verify that userId is not being specified by a different user
10310            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10311                throw new SecurityException(
10312                        "Permission Denial: attempt to change component state from pid="
10313                        + Binder.getCallingPid()
10314                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10315            }
10316            if (className == null) {
10317                // We're dealing with an application/package level state change
10318                if (pkgSetting.getEnabled(userId) == newState) {
10319                    // Nothing to do
10320                    return;
10321                }
10322                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10323                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10324                    // Don't care about who enables an app.
10325                    callingPackage = null;
10326                }
10327                pkgSetting.setEnabled(newState, userId, callingPackage);
10328                // pkgSetting.pkg.mSetEnabled = newState;
10329            } else {
10330                // We're dealing with a component level state change
10331                // First, verify that this is a valid class name.
10332                PackageParser.Package pkg = pkgSetting.pkg;
10333                if (pkg == null || !pkg.hasComponentClassName(className)) {
10334                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10335                        throw new IllegalArgumentException("Component class " + className
10336                                + " does not exist in " + packageName);
10337                    } else {
10338                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10339                                + className + " does not exist in " + packageName);
10340                    }
10341                }
10342                switch (newState) {
10343                case COMPONENT_ENABLED_STATE_ENABLED:
10344                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10345                        return;
10346                    }
10347                    break;
10348                case COMPONENT_ENABLED_STATE_DISABLED:
10349                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10350                        return;
10351                    }
10352                    break;
10353                case COMPONENT_ENABLED_STATE_DEFAULT:
10354                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10355                        return;
10356                    }
10357                    break;
10358                default:
10359                    Slog.e(TAG, "Invalid new component state: " + newState);
10360                    return;
10361                }
10362            }
10363            mSettings.writePackageRestrictionsLPr(userId);
10364            components = mPendingBroadcasts.get(userId, packageName);
10365            final boolean newPackage = components == null;
10366            if (newPackage) {
10367                components = new ArrayList<String>();
10368            }
10369            if (!components.contains(componentName)) {
10370                components.add(componentName);
10371            }
10372            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10373                sendNow = true;
10374                // Purge entry from pending broadcast list if another one exists already
10375                // since we are sending one right away.
10376                mPendingBroadcasts.remove(userId, packageName);
10377            } else {
10378                if (newPackage) {
10379                    mPendingBroadcasts.put(userId, packageName, components);
10380                }
10381                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10382                    // Schedule a message
10383                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10384                }
10385            }
10386        }
10387
10388        long callingId = Binder.clearCallingIdentity();
10389        try {
10390            if (sendNow) {
10391                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10392                sendPackageChangedBroadcast(packageName,
10393                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10394            }
10395        } finally {
10396            Binder.restoreCallingIdentity(callingId);
10397        }
10398    }
10399
10400    private void sendPackageChangedBroadcast(String packageName,
10401            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10402        if (DEBUG_INSTALL)
10403            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10404                    + componentNames);
10405        Bundle extras = new Bundle(4);
10406        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10407        String nameList[] = new String[componentNames.size()];
10408        componentNames.toArray(nameList);
10409        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10410        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10411        extras.putInt(Intent.EXTRA_UID, packageUid);
10412        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10413                new int[] {UserHandle.getUserId(packageUid)});
10414    }
10415
10416    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
10417        if (!sUserManager.exists(userId)) return;
10418        final int uid = Binder.getCallingUid();
10419        final int permission = mContext.checkCallingOrSelfPermission(
10420                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10421        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10422        enforceCrossUserPermission(uid, userId, true, "stop package");
10423        // writer
10424        synchronized (mPackages) {
10425            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
10426                    uid, userId)) {
10427                scheduleWritePackageRestrictionsLocked(userId);
10428            }
10429        }
10430    }
10431
10432    public String getInstallerPackageName(String packageName) {
10433        // reader
10434        synchronized (mPackages) {
10435            return mSettings.getInstallerPackageNameLPr(packageName);
10436        }
10437    }
10438
10439    @Override
10440    public int getApplicationEnabledSetting(String packageName, int userId) {
10441        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10442        int uid = Binder.getCallingUid();
10443        enforceCrossUserPermission(uid, userId, false, "get enabled");
10444        // reader
10445        synchronized (mPackages) {
10446            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
10447        }
10448    }
10449
10450    @Override
10451    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
10452        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10453        int uid = Binder.getCallingUid();
10454        enforceCrossUserPermission(uid, userId, false, "get component enabled");
10455        // reader
10456        synchronized (mPackages) {
10457            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
10458        }
10459    }
10460
10461    public void enterSafeMode() {
10462        enforceSystemOrRoot("Only the system can request entering safe mode");
10463
10464        if (!mSystemReady) {
10465            mSafeMode = true;
10466        }
10467    }
10468
10469    public void systemReady() {
10470        mSystemReady = true;
10471
10472        // Read the compatibilty setting when the system is ready.
10473        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
10474                mContext.getContentResolver(),
10475                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
10476        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
10477        if (DEBUG_SETTINGS) {
10478            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
10479        }
10480
10481        synchronized (mPackages) {
10482            // Verify that all of the preferred activity components actually
10483            // exist.  It is possible for applications to be updated and at
10484            // that point remove a previously declared activity component that
10485            // had been set as a preferred activity.  We try to clean this up
10486            // the next time we encounter that preferred activity, but it is
10487            // possible for the user flow to never be able to return to that
10488            // situation so here we do a sanity check to make sure we haven't
10489            // left any junk around.
10490            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
10491            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10492                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10493                removed.clear();
10494                for (PreferredActivity pa : pir.filterSet()) {
10495                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
10496                        removed.add(pa);
10497                    }
10498                }
10499                if (removed.size() > 0) {
10500                    for (int j=0; j<removed.size(); j++) {
10501                        PreferredActivity pa = removed.get(i);
10502                        Slog.w(TAG, "Removing dangling preferred activity: "
10503                                + pa.mPref.mComponent);
10504                        pir.removeFilter(pa);
10505                    }
10506                    mSettings.writePackageRestrictionsLPr(
10507                            mSettings.mPreferredActivities.keyAt(i));
10508                }
10509            }
10510        }
10511        sUserManager.systemReady();
10512    }
10513
10514    public boolean isSafeMode() {
10515        return mSafeMode;
10516    }
10517
10518    public boolean hasSystemUidErrors() {
10519        return mHasSystemUidErrors;
10520    }
10521
10522    static String arrayToString(int[] array) {
10523        StringBuffer buf = new StringBuffer(128);
10524        buf.append('[');
10525        if (array != null) {
10526            for (int i=0; i<array.length; i++) {
10527                if (i > 0) buf.append(", ");
10528                buf.append(array[i]);
10529            }
10530        }
10531        buf.append(']');
10532        return buf.toString();
10533    }
10534
10535    static class DumpState {
10536        public static final int DUMP_LIBS = 1 << 0;
10537
10538        public static final int DUMP_FEATURES = 1 << 1;
10539
10540        public static final int DUMP_RESOLVERS = 1 << 2;
10541
10542        public static final int DUMP_PERMISSIONS = 1 << 3;
10543
10544        public static final int DUMP_PACKAGES = 1 << 4;
10545
10546        public static final int DUMP_SHARED_USERS = 1 << 5;
10547
10548        public static final int DUMP_MESSAGES = 1 << 6;
10549
10550        public static final int DUMP_PROVIDERS = 1 << 7;
10551
10552        public static final int DUMP_VERIFIERS = 1 << 8;
10553
10554        public static final int DUMP_PREFERRED = 1 << 9;
10555
10556        public static final int DUMP_PREFERRED_XML = 1 << 10;
10557
10558        public static final int DUMP_KEYSETS = 1 << 11;
10559
10560        public static final int OPTION_SHOW_FILTERS = 1 << 0;
10561
10562        private int mTypes;
10563
10564        private int mOptions;
10565
10566        private boolean mTitlePrinted;
10567
10568        private SharedUserSetting mSharedUser;
10569
10570        public boolean isDumping(int type) {
10571            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
10572                return true;
10573            }
10574
10575            return (mTypes & type) != 0;
10576        }
10577
10578        public void setDump(int type) {
10579            mTypes |= type;
10580        }
10581
10582        public boolean isOptionEnabled(int option) {
10583            return (mOptions & option) != 0;
10584        }
10585
10586        public void setOptionEnabled(int option) {
10587            mOptions |= option;
10588        }
10589
10590        public boolean onTitlePrinted() {
10591            final boolean printed = mTitlePrinted;
10592            mTitlePrinted = true;
10593            return printed;
10594        }
10595
10596        public boolean getTitlePrinted() {
10597            return mTitlePrinted;
10598        }
10599
10600        public void setTitlePrinted(boolean enabled) {
10601            mTitlePrinted = enabled;
10602        }
10603
10604        public SharedUserSetting getSharedUser() {
10605            return mSharedUser;
10606        }
10607
10608        public void setSharedUser(SharedUserSetting user) {
10609            mSharedUser = user;
10610        }
10611    }
10612
10613    @Override
10614    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
10615        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
10616                != PackageManager.PERMISSION_GRANTED) {
10617            pw.println("Permission Denial: can't dump ActivityManager from from pid="
10618                    + Binder.getCallingPid()
10619                    + ", uid=" + Binder.getCallingUid()
10620                    + " without permission "
10621                    + android.Manifest.permission.DUMP);
10622            return;
10623        }
10624
10625        DumpState dumpState = new DumpState();
10626        boolean fullPreferred = false;
10627        boolean checkin = false;
10628
10629        String packageName = null;
10630
10631        int opti = 0;
10632        while (opti < args.length) {
10633            String opt = args[opti];
10634            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10635                break;
10636            }
10637            opti++;
10638            if ("-a".equals(opt)) {
10639                // Right now we only know how to print all.
10640            } else if ("-h".equals(opt)) {
10641                pw.println("Package manager dump options:");
10642                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
10643                pw.println("    --checkin: dump for a checkin");
10644                pw.println("    -f: print details of intent filters");
10645                pw.println("    -h: print this help");
10646                pw.println("  cmd may be one of:");
10647                pw.println("    l[ibraries]: list known shared libraries");
10648                pw.println("    f[ibraries]: list device features");
10649                pw.println("    r[esolvers]: dump intent resolvers");
10650                pw.println("    perm[issions]: dump permissions");
10651                pw.println("    pref[erred]: print preferred package settings");
10652                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
10653                pw.println("    prov[iders]: dump content providers");
10654                pw.println("    p[ackages]: dump installed packages");
10655                pw.println("    s[hared-users]: dump shared user IDs");
10656                pw.println("    m[essages]: print collected runtime messages");
10657                pw.println("    v[erifiers]: print package verifier info");
10658                pw.println("    <package.name>: info about given package");
10659                pw.println("    k[eysets]: print known keysets");
10660                return;
10661            } else if ("--checkin".equals(opt)) {
10662                checkin = true;
10663            } else if ("-f".equals(opt)) {
10664                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
10665            } else {
10666                pw.println("Unknown argument: " + opt + "; use -h for help");
10667            }
10668        }
10669
10670        // Is the caller requesting to dump a particular piece of data?
10671        if (opti < args.length) {
10672            String cmd = args[opti];
10673            opti++;
10674            // Is this a package name?
10675            if ("android".equals(cmd) || cmd.contains(".")) {
10676                packageName = cmd;
10677                // When dumping a single package, we always dump all of its
10678                // filter information since the amount of data will be reasonable.
10679                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
10680            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
10681                dumpState.setDump(DumpState.DUMP_LIBS);
10682            } else if ("f".equals(cmd) || "features".equals(cmd)) {
10683                dumpState.setDump(DumpState.DUMP_FEATURES);
10684            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
10685                dumpState.setDump(DumpState.DUMP_RESOLVERS);
10686            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
10687                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
10688            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
10689                dumpState.setDump(DumpState.DUMP_PREFERRED);
10690            } else if ("preferred-xml".equals(cmd)) {
10691                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
10692                if (opti < args.length && "--full".equals(args[opti])) {
10693                    fullPreferred = true;
10694                    opti++;
10695                }
10696            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
10697                dumpState.setDump(DumpState.DUMP_PACKAGES);
10698            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
10699                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
10700            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
10701                dumpState.setDump(DumpState.DUMP_PROVIDERS);
10702            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
10703                dumpState.setDump(DumpState.DUMP_MESSAGES);
10704            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
10705                dumpState.setDump(DumpState.DUMP_VERIFIERS);
10706            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
10707                dumpState.setDump(DumpState.DUMP_KEYSETS);
10708            }
10709        }
10710
10711        if (checkin) {
10712            pw.println("vers,1");
10713        }
10714
10715        // reader
10716        synchronized (mPackages) {
10717            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
10718                if (!checkin) {
10719                    if (dumpState.onTitlePrinted())
10720                        pw.println();
10721                    pw.println("Verifiers:");
10722                    pw.print("  Required: ");
10723                    pw.print(mRequiredVerifierPackage);
10724                    pw.print(" (uid=");
10725                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
10726                    pw.println(")");
10727                } else if (mRequiredVerifierPackage != null) {
10728                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
10729                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
10730                }
10731            }
10732
10733            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
10734                boolean printedHeader = false;
10735                final Iterator<String> it = mSharedLibraries.keySet().iterator();
10736                while (it.hasNext()) {
10737                    String name = it.next();
10738                    SharedLibraryEntry ent = mSharedLibraries.get(name);
10739                    if (!checkin) {
10740                        if (!printedHeader) {
10741                            if (dumpState.onTitlePrinted())
10742                                pw.println();
10743                            pw.println("Libraries:");
10744                            printedHeader = true;
10745                        }
10746                        pw.print("  ");
10747                    } else {
10748                        pw.print("lib,");
10749                    }
10750                    pw.print(name);
10751                    if (!checkin) {
10752                        pw.print(" -> ");
10753                    }
10754                    if (ent.path != null) {
10755                        if (!checkin) {
10756                            pw.print("(jar) ");
10757                            pw.print(ent.path);
10758                        } else {
10759                            pw.print(",jar,");
10760                            pw.print(ent.path);
10761                        }
10762                    } else {
10763                        if (!checkin) {
10764                            pw.print("(apk) ");
10765                            pw.print(ent.apk);
10766                        } else {
10767                            pw.print(",apk,");
10768                            pw.print(ent.apk);
10769                        }
10770                    }
10771                    pw.println();
10772                }
10773            }
10774
10775            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
10776                if (dumpState.onTitlePrinted())
10777                    pw.println();
10778                if (!checkin) {
10779                    pw.println("Features:");
10780                }
10781                Iterator<String> it = mAvailableFeatures.keySet().iterator();
10782                while (it.hasNext()) {
10783                    String name = it.next();
10784                    if (!checkin) {
10785                        pw.print("  ");
10786                    } else {
10787                        pw.print("feat,");
10788                    }
10789                    pw.println(name);
10790                }
10791            }
10792
10793            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
10794                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
10795                        : "Activity Resolver Table:", "  ", packageName,
10796                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10797                    dumpState.setTitlePrinted(true);
10798                }
10799                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
10800                        : "Receiver Resolver Table:", "  ", packageName,
10801                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10802                    dumpState.setTitlePrinted(true);
10803                }
10804                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
10805                        : "Service Resolver Table:", "  ", packageName,
10806                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10807                    dumpState.setTitlePrinted(true);
10808                }
10809                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
10810                        : "Provider Resolver Table:", "  ", packageName,
10811                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10812                    dumpState.setTitlePrinted(true);
10813                }
10814            }
10815
10816            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
10817                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10818                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10819                    int user = mSettings.mPreferredActivities.keyAt(i);
10820                    if (pir.dump(pw,
10821                            dumpState.getTitlePrinted()
10822                                ? "\nPreferred Activities User " + user + ":"
10823                                : "Preferred Activities User " + user + ":", "  ",
10824                            packageName, true)) {
10825                        dumpState.setTitlePrinted(true);
10826                    }
10827                }
10828            }
10829
10830            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
10831                pw.flush();
10832                FileOutputStream fout = new FileOutputStream(fd);
10833                BufferedOutputStream str = new BufferedOutputStream(fout);
10834                XmlSerializer serializer = new FastXmlSerializer();
10835                try {
10836                    serializer.setOutput(str, "utf-8");
10837                    serializer.startDocument(null, true);
10838                    serializer.setFeature(
10839                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
10840                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
10841                    serializer.endDocument();
10842                    serializer.flush();
10843                } catch (IllegalArgumentException e) {
10844                    pw.println("Failed writing: " + e);
10845                } catch (IllegalStateException e) {
10846                    pw.println("Failed writing: " + e);
10847                } catch (IOException e) {
10848                    pw.println("Failed writing: " + e);
10849                }
10850            }
10851
10852            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
10853                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
10854            }
10855
10856            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
10857                boolean printedSomething = false;
10858                for (PackageParser.Provider p : mProviders.mProviders.values()) {
10859                    if (packageName != null && !packageName.equals(p.info.packageName)) {
10860                        continue;
10861                    }
10862                    if (!printedSomething) {
10863                        if (dumpState.onTitlePrinted())
10864                            pw.println();
10865                        pw.println("Registered ContentProviders:");
10866                        printedSomething = true;
10867                    }
10868                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
10869                    pw.print("    "); pw.println(p.toString());
10870                }
10871                printedSomething = false;
10872                for (Map.Entry<String, PackageParser.Provider> entry :
10873                        mProvidersByAuthority.entrySet()) {
10874                    PackageParser.Provider p = entry.getValue();
10875                    if (packageName != null && !packageName.equals(p.info.packageName)) {
10876                        continue;
10877                    }
10878                    if (!printedSomething) {
10879                        if (dumpState.onTitlePrinted())
10880                            pw.println();
10881                        pw.println("ContentProvider Authorities:");
10882                        printedSomething = true;
10883                    }
10884                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
10885                    pw.print("    "); pw.println(p.toString());
10886                    if (p.info != null && p.info.applicationInfo != null) {
10887                        final String appInfo = p.info.applicationInfo.toString();
10888                        pw.print("      applicationInfo="); pw.println(appInfo);
10889                    }
10890                }
10891            }
10892
10893            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
10894                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
10895            }
10896
10897            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
10898                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
10899            }
10900
10901            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
10902                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
10903            }
10904
10905            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
10906                if (dumpState.onTitlePrinted())
10907                    pw.println();
10908                mSettings.dumpReadMessagesLPr(pw, dumpState);
10909
10910                pw.println();
10911                pw.println("Package warning messages:");
10912                final File fname = getSettingsProblemFile();
10913                FileInputStream in = null;
10914                try {
10915                    in = new FileInputStream(fname);
10916                    final int avail = in.available();
10917                    final byte[] data = new byte[avail];
10918                    in.read(data);
10919                    pw.print(new String(data));
10920                } catch (FileNotFoundException e) {
10921                } catch (IOException e) {
10922                } finally {
10923                    if (in != null) {
10924                        try {
10925                            in.close();
10926                        } catch (IOException e) {
10927                        }
10928                    }
10929                }
10930            }
10931        }
10932    }
10933
10934    // ------- apps on sdcard specific code -------
10935    static final boolean DEBUG_SD_INSTALL = false;
10936
10937    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
10938
10939    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
10940
10941    private boolean mMediaMounted = false;
10942
10943    private String getEncryptKey() {
10944        try {
10945            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
10946                    SD_ENCRYPTION_KEYSTORE_NAME);
10947            if (sdEncKey == null) {
10948                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
10949                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
10950                if (sdEncKey == null) {
10951                    Slog.e(TAG, "Failed to create encryption keys");
10952                    return null;
10953                }
10954            }
10955            return sdEncKey;
10956        } catch (NoSuchAlgorithmException nsae) {
10957            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
10958            return null;
10959        } catch (IOException ioe) {
10960            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
10961            return null;
10962        }
10963
10964    }
10965
10966    /* package */static String getTempContainerId() {
10967        int tmpIdx = 1;
10968        String list[] = PackageHelper.getSecureContainerList();
10969        if (list != null) {
10970            for (final String name : list) {
10971                // Ignore null and non-temporary container entries
10972                if (name == null || !name.startsWith(mTempContainerPrefix)) {
10973                    continue;
10974                }
10975
10976                String subStr = name.substring(mTempContainerPrefix.length());
10977                try {
10978                    int cid = Integer.parseInt(subStr);
10979                    if (cid >= tmpIdx) {
10980                        tmpIdx = cid + 1;
10981                    }
10982                } catch (NumberFormatException e) {
10983                }
10984            }
10985        }
10986        return mTempContainerPrefix + tmpIdx;
10987    }
10988
10989    /*
10990     * Update media status on PackageManager.
10991     */
10992    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
10993        int callingUid = Binder.getCallingUid();
10994        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10995            throw new SecurityException("Media status can only be updated by the system");
10996        }
10997        // reader; this apparently protects mMediaMounted, but should probably
10998        // be a different lock in that case.
10999        synchronized (mPackages) {
11000            Log.i(TAG, "Updating external media status from "
11001                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11002                    + (mediaStatus ? "mounted" : "unmounted"));
11003            if (DEBUG_SD_INSTALL)
11004                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11005                        + ", mMediaMounted=" + mMediaMounted);
11006            if (mediaStatus == mMediaMounted) {
11007                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11008                        : 0, -1);
11009                mHandler.sendMessage(msg);
11010                return;
11011            }
11012            mMediaMounted = mediaStatus;
11013        }
11014        // Queue up an async operation since the package installation may take a
11015        // little while.
11016        mHandler.post(new Runnable() {
11017            public void run() {
11018                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11019            }
11020        });
11021    }
11022
11023    /**
11024     * Called by MountService when the initial ASECs to scan are available.
11025     * Should block until all the ASEC containers are finished being scanned.
11026     */
11027    public void scanAvailableAsecs() {
11028        updateExternalMediaStatusInner(true, false, false);
11029    }
11030
11031    /*
11032     * Collect information of applications on external media, map them against
11033     * existing containers and update information based on current mount status.
11034     * Please note that we always have to report status if reportStatus has been
11035     * set to true especially when unloading packages.
11036     */
11037    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11038            boolean externalStorage) {
11039        // Collection of uids
11040        int uidArr[] = null;
11041        // Collection of stale containers
11042        HashSet<String> removeCids = new HashSet<String>();
11043        // Collection of packages on external media with valid containers.
11044        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11045        // Get list of secure containers.
11046        final String list[] = PackageHelper.getSecureContainerList();
11047        if (list == null || list.length == 0) {
11048            Log.i(TAG, "No secure containers on sdcard");
11049        } else {
11050            // Process list of secure containers and categorize them
11051            // as active or stale based on their package internal state.
11052            int uidList[] = new int[list.length];
11053            int num = 0;
11054            // reader
11055            synchronized (mPackages) {
11056                for (String cid : list) {
11057                    if (DEBUG_SD_INSTALL)
11058                        Log.i(TAG, "Processing container " + cid);
11059                    String pkgName = getAsecPackageName(cid);
11060                    if (pkgName == null) {
11061                        if (DEBUG_SD_INSTALL)
11062                            Log.i(TAG, "Container : " + cid + " stale");
11063                        removeCids.add(cid);
11064                        continue;
11065                    }
11066                    if (DEBUG_SD_INSTALL)
11067                        Log.i(TAG, "Looking for pkg : " + pkgName);
11068
11069                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11070                    if (ps == null) {
11071                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11072                        removeCids.add(cid);
11073                        continue;
11074                    }
11075
11076                    /*
11077                     * Skip packages that are not external if we're unmounting
11078                     * external storage.
11079                     */
11080                    if (externalStorage && !isMounted && !isExternal(ps)) {
11081                        continue;
11082                    }
11083
11084                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
11085                    // The package status is changed only if the code path
11086                    // matches between settings and the container id.
11087                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11088                        if (DEBUG_SD_INSTALL) {
11089                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11090                                    + " at code path: " + ps.codePathString);
11091                        }
11092
11093                        // We do have a valid package installed on sdcard
11094                        processCids.put(args, ps.codePathString);
11095                        final int uid = ps.appId;
11096                        if (uid != -1) {
11097                            uidList[num++] = uid;
11098                        }
11099                    } else {
11100                        Log.i(TAG, "Deleting stale container for " + cid);
11101                        removeCids.add(cid);
11102                    }
11103                }
11104            }
11105
11106            if (num > 0) {
11107                // Sort uid list
11108                Arrays.sort(uidList, 0, num);
11109                // Throw away duplicates
11110                uidArr = new int[num];
11111                uidArr[0] = uidList[0];
11112                int di = 0;
11113                for (int i = 1; i < num; i++) {
11114                    if (uidList[i - 1] != uidList[i]) {
11115                        uidArr[di++] = uidList[i];
11116                    }
11117                }
11118            }
11119        }
11120        // Process packages with valid entries.
11121        if (isMounted) {
11122            if (DEBUG_SD_INSTALL)
11123                Log.i(TAG, "Loading packages");
11124            loadMediaPackages(processCids, uidArr, removeCids);
11125            startCleaningPackages();
11126        } else {
11127            if (DEBUG_SD_INSTALL)
11128                Log.i(TAG, "Unloading packages");
11129            unloadMediaPackages(processCids, uidArr, reportStatus);
11130        }
11131    }
11132
11133   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11134           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11135        int size = pkgList.size();
11136        if (size > 0) {
11137            // Send broadcasts here
11138            Bundle extras = new Bundle();
11139            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11140                    .toArray(new String[size]));
11141            if (uidArr != null) {
11142                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11143            }
11144            if (replacing) {
11145                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11146            }
11147            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11148                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11149            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11150        }
11151    }
11152
11153   /*
11154     * Look at potentially valid container ids from processCids If package
11155     * information doesn't match the one on record or package scanning fails,
11156     * the cid is added to list of removeCids. We currently don't delete stale
11157     * containers.
11158     */
11159   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11160            HashSet<String> removeCids) {
11161        ArrayList<String> pkgList = new ArrayList<String>();
11162        Set<AsecInstallArgs> keys = processCids.keySet();
11163        boolean doGc = false;
11164        for (AsecInstallArgs args : keys) {
11165            String codePath = processCids.get(args);
11166            if (DEBUG_SD_INSTALL)
11167                Log.i(TAG, "Loading container : " + args.cid);
11168            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11169            try {
11170                // Make sure there are no container errors first.
11171                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11172                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11173                            + " when installing from sdcard");
11174                    continue;
11175                }
11176                // Check code path here.
11177                if (codePath == null || !codePath.equals(args.getCodePath())) {
11178                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11179                            + " does not match one in settings " + codePath);
11180                    continue;
11181                }
11182                // Parse package
11183                int parseFlags = mDefParseFlags;
11184                if (args.isExternal()) {
11185                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11186                }
11187                if (args.isFwdLocked()) {
11188                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11189                }
11190
11191                doGc = true;
11192                synchronized (mInstallLock) {
11193                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11194                            0, 0, null);
11195                    // Scan the package
11196                    if (pkg != null) {
11197                        /*
11198                         * TODO why is the lock being held? doPostInstall is
11199                         * called in other places without the lock. This needs
11200                         * to be straightened out.
11201                         */
11202                        // writer
11203                        synchronized (mPackages) {
11204                            retCode = PackageManager.INSTALL_SUCCEEDED;
11205                            pkgList.add(pkg.packageName);
11206                            // Post process args
11207                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11208                                    pkg.applicationInfo.uid);
11209                        }
11210                    } else {
11211                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11212                    }
11213                }
11214
11215            } finally {
11216                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11217                    // Don't destroy container here. Wait till gc clears things
11218                    // up.
11219                    removeCids.add(args.cid);
11220                }
11221            }
11222        }
11223        // writer
11224        synchronized (mPackages) {
11225            // If the platform SDK has changed since the last time we booted,
11226            // we need to re-grant app permission to catch any new ones that
11227            // appear. This is really a hack, and means that apps can in some
11228            // cases get permissions that the user didn't initially explicitly
11229            // allow... it would be nice to have some better way to handle
11230            // this situation.
11231            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11232            if (regrantPermissions)
11233                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11234                        + mSdkVersion + "; regranting permissions for external storage");
11235            mSettings.mExternalSdkPlatform = mSdkVersion;
11236
11237            // Make sure group IDs have been assigned, and any permission
11238            // changes in other apps are accounted for
11239            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11240                    | (regrantPermissions
11241                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11242                            : 0));
11243            // can downgrade to reader
11244            // Persist settings
11245            mSettings.writeLPr();
11246        }
11247        // Send a broadcast to let everyone know we are done processing
11248        if (pkgList.size() > 0) {
11249            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11250        }
11251        // Force gc to avoid any stale parser references that we might have.
11252        if (doGc) {
11253            Runtime.getRuntime().gc();
11254        }
11255        // List stale containers and destroy stale temporary containers.
11256        if (removeCids != null) {
11257            for (String cid : removeCids) {
11258                if (cid.startsWith(mTempContainerPrefix)) {
11259                    Log.i(TAG, "Destroying stale temporary container " + cid);
11260                    PackageHelper.destroySdDir(cid);
11261                } else {
11262                    Log.w(TAG, "Container " + cid + " is stale");
11263               }
11264           }
11265        }
11266    }
11267
11268   /*
11269     * Utility method to unload a list of specified containers
11270     */
11271    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11272        // Just unmount all valid containers.
11273        for (AsecInstallArgs arg : cidArgs) {
11274            synchronized (mInstallLock) {
11275                arg.doPostDeleteLI(false);
11276           }
11277       }
11278   }
11279
11280    /*
11281     * Unload packages mounted on external media. This involves deleting package
11282     * data from internal structures, sending broadcasts about diabled packages,
11283     * gc'ing to free up references, unmounting all secure containers
11284     * corresponding to packages on external media, and posting a
11285     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11286     * that we always have to post this message if status has been requested no
11287     * matter what.
11288     */
11289    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11290            final boolean reportStatus) {
11291        if (DEBUG_SD_INSTALL)
11292            Log.i(TAG, "unloading media packages");
11293        ArrayList<String> pkgList = new ArrayList<String>();
11294        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11295        final Set<AsecInstallArgs> keys = processCids.keySet();
11296        for (AsecInstallArgs args : keys) {
11297            String pkgName = args.getPackageName();
11298            if (DEBUG_SD_INSTALL)
11299                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11300            // Delete package internally
11301            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11302            synchronized (mInstallLock) {
11303                boolean res = deletePackageLI(pkgName, null, false, null, null,
11304                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11305                if (res) {
11306                    pkgList.add(pkgName);
11307                } else {
11308                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11309                    failedList.add(args);
11310                }
11311            }
11312        }
11313
11314        // reader
11315        synchronized (mPackages) {
11316            // We didn't update the settings after removing each package;
11317            // write them now for all packages.
11318            mSettings.writeLPr();
11319        }
11320
11321        // We have to absolutely send UPDATED_MEDIA_STATUS only
11322        // after confirming that all the receivers processed the ordered
11323        // broadcast when packages get disabled, force a gc to clean things up.
11324        // and unload all the containers.
11325        if (pkgList.size() > 0) {
11326            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11327                    new IIntentReceiver.Stub() {
11328                public void performReceive(Intent intent, int resultCode, String data,
11329                        Bundle extras, boolean ordered, boolean sticky,
11330                        int sendingUser) throws RemoteException {
11331                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11332                            reportStatus ? 1 : 0, 1, keys);
11333                    mHandler.sendMessage(msg);
11334                }
11335            });
11336        } else {
11337            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11338                    keys);
11339            mHandler.sendMessage(msg);
11340        }
11341    }
11342
11343    /** Binder call */
11344    @Override
11345    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11346            final int flags) {
11347        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11348        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11349        int returnCode = PackageManager.MOVE_SUCCEEDED;
11350        int currFlags = 0;
11351        int newFlags = 0;
11352        // reader
11353        synchronized (mPackages) {
11354            PackageParser.Package pkg = mPackages.get(packageName);
11355            if (pkg == null) {
11356                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11357            } else {
11358                // Disable moving fwd locked apps and system packages
11359                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11360                    Slog.w(TAG, "Cannot move system application");
11361                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11362                } else if (pkg.mOperationPending) {
11363                    Slog.w(TAG, "Attempt to move package which has pending operations");
11364                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11365                } else {
11366                    // Find install location first
11367                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11368                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11369                        Slog.w(TAG, "Ambigous flags specified for move location.");
11370                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11371                    } else {
11372                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11373                                : PackageManager.INSTALL_INTERNAL;
11374                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11375                                : PackageManager.INSTALL_INTERNAL;
11376
11377                        if (newFlags == currFlags) {
11378                            Slog.w(TAG, "No move required. Trying to move to same location");
11379                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11380                        } else {
11381                            if (isForwardLocked(pkg)) {
11382                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11383                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11384                            }
11385                        }
11386                    }
11387                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11388                        pkg.mOperationPending = true;
11389                    }
11390                }
11391            }
11392
11393            /*
11394             * TODO this next block probably shouldn't be inside the lock. We
11395             * can't guarantee these won't change after this is fired off
11396             * anyway.
11397             */
11398            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11399                processPendingMove(new MoveParams(null, observer, 0, packageName,
11400                        null, -1, user),
11401                        returnCode);
11402            } else {
11403                Message msg = mHandler.obtainMessage(INIT_COPY);
11404                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
11405                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
11406                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
11407                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
11408                msg.obj = mp;
11409                mHandler.sendMessage(msg);
11410            }
11411        }
11412    }
11413
11414    private void processPendingMove(final MoveParams mp, final int currentStatus) {
11415        // Queue up an async operation since the package deletion may take a
11416        // little while.
11417        mHandler.post(new Runnable() {
11418            public void run() {
11419                // TODO fix this; this does nothing.
11420                mHandler.removeCallbacks(this);
11421                int returnCode = currentStatus;
11422                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
11423                    int uidArr[] = null;
11424                    ArrayList<String> pkgList = null;
11425                    synchronized (mPackages) {
11426                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11427                        if (pkg == null) {
11428                            Slog.w(TAG, " Package " + mp.packageName
11429                                    + " doesn't exist. Aborting move");
11430                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11431                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
11432                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
11433                                    + mp.srcArgs.getCodePath() + " to "
11434                                    + pkg.applicationInfo.sourceDir
11435                                    + " Aborting move and returning error");
11436                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11437                        } else {
11438                            uidArr = new int[] {
11439                                pkg.applicationInfo.uid
11440                            };
11441                            pkgList = new ArrayList<String>();
11442                            pkgList.add(mp.packageName);
11443                        }
11444                    }
11445                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11446                        // Send resources unavailable broadcast
11447                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
11448                        // Update package code and resource paths
11449                        synchronized (mInstallLock) {
11450                            synchronized (mPackages) {
11451                                PackageParser.Package pkg = mPackages.get(mp.packageName);
11452                                // Recheck for package again.
11453                                if (pkg == null) {
11454                                    Slog.w(TAG, " Package " + mp.packageName
11455                                            + " doesn't exist. Aborting move");
11456                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11457                                } else if (!mp.srcArgs.getCodePath().equals(
11458                                        pkg.applicationInfo.sourceDir)) {
11459                                    Slog.w(TAG, "Package " + mp.packageName
11460                                            + " code path changed from " + mp.srcArgs.getCodePath()
11461                                            + " to " + pkg.applicationInfo.sourceDir
11462                                            + " Aborting move and returning error");
11463                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11464                                } else {
11465                                    final String oldCodePath = pkg.mPath;
11466                                    final String newCodePath = mp.targetArgs.getCodePath();
11467                                    final String newResPath = mp.targetArgs.getResourcePath();
11468                                    final String newNativePath = mp.targetArgs
11469                                            .getNativeLibraryPath();
11470
11471                                    final File newNativeDir = new File(newNativePath);
11472
11473                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
11474                                        NativeLibraryHelper.copyNativeBinariesIfNeededLI(
11475                                                new File(newCodePath), newNativeDir);
11476                                    }
11477                                    final int[] users = sUserManager.getUserIds();
11478                                    for (int user : users) {
11479                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
11480                                                newNativePath, user) < 0) {
11481                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11482                                        }
11483                                    }
11484
11485                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11486                                        pkg.mPath = newCodePath;
11487                                        // Move dex files around
11488                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
11489                                            // Moving of dex files failed. Set
11490                                            // error code and abort move.
11491                                            pkg.mPath = pkg.mScanPath;
11492                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11493                                        }
11494                                    }
11495
11496                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11497                                        pkg.mScanPath = newCodePath;
11498                                        pkg.applicationInfo.sourceDir = newCodePath;
11499                                        pkg.applicationInfo.publicSourceDir = newResPath;
11500                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
11501                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
11502                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
11503                                        ps.codePathString = ps.codePath.getPath();
11504                                        ps.resourcePath = new File(
11505                                                pkg.applicationInfo.publicSourceDir);
11506                                        ps.resourcePathString = ps.resourcePath.getPath();
11507                                        ps.nativeLibraryPathString = newNativePath;
11508                                        // Set the application info flag
11509                                        // correctly.
11510                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
11511                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11512                                        } else {
11513                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11514                                        }
11515                                        ps.setFlags(pkg.applicationInfo.flags);
11516                                        mAppDirs.remove(oldCodePath);
11517                                        mAppDirs.put(newCodePath, pkg);
11518                                        // Persist settings
11519                                        mSettings.writeLPr();
11520                                    }
11521                                }
11522                            }
11523                        }
11524                        // Send resources available broadcast
11525                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11526                    }
11527                }
11528                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11529                    // Clean up failed installation
11530                    if (mp.targetArgs != null) {
11531                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
11532                                -1);
11533                    }
11534                } else {
11535                    // Force a gc to clear things up.
11536                    Runtime.getRuntime().gc();
11537                    // Delete older code
11538                    synchronized (mInstallLock) {
11539                        mp.srcArgs.doPostDeleteLI(true);
11540                    }
11541                }
11542
11543                // Allow more operations on this file if we didn't fail because
11544                // an operation was already pending for this package.
11545                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
11546                    synchronized (mPackages) {
11547                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11548                        if (pkg != null) {
11549                            pkg.mOperationPending = false;
11550                       }
11551                   }
11552                }
11553
11554                IPackageMoveObserver observer = mp.observer;
11555                if (observer != null) {
11556                    try {
11557                        observer.packageMoved(mp.packageName, returnCode);
11558                    } catch (RemoteException e) {
11559                        Log.i(TAG, "Observer no longer exists.");
11560                    }
11561                }
11562            }
11563        });
11564    }
11565
11566    public boolean setInstallLocation(int loc) {
11567        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
11568                null);
11569        if (getInstallLocation() == loc) {
11570            return true;
11571        }
11572        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
11573                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
11574            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
11575                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
11576            return true;
11577        }
11578        return false;
11579   }
11580
11581    public int getInstallLocation() {
11582        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11583                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
11584                PackageHelper.APP_INSTALL_AUTO);
11585    }
11586
11587    /** Called by UserManagerService */
11588    void cleanUpUserLILPw(int userHandle) {
11589        mDirtyUsers.remove(userHandle);
11590        mSettings.removeUserLPr(userHandle);
11591        mPendingBroadcasts.remove(userHandle);
11592        if (mInstaller != null) {
11593            // Technically, we shouldn't be doing this with the package lock
11594            // held.  However, this is very rare, and there is already so much
11595            // other disk I/O going on, that we'll let it slide for now.
11596            mInstaller.removeUserDataDirs(userHandle);
11597        }
11598    }
11599
11600    /** Called by UserManagerService */
11601    void createNewUserLILPw(int userHandle, File path) {
11602        if (mInstaller != null) {
11603            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
11604        }
11605    }
11606
11607    @Override
11608    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
11609        mContext.enforceCallingOrSelfPermission(
11610                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11611                "Only package verification agents can read the verifier device identity");
11612
11613        synchronized (mPackages) {
11614            return mSettings.getVerifierDeviceIdentityLPw();
11615        }
11616    }
11617
11618    @Override
11619    public void setPermissionEnforced(String permission, boolean enforced) {
11620        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
11621        if (READ_EXTERNAL_STORAGE.equals(permission)) {
11622            synchronized (mPackages) {
11623                if (mSettings.mReadExternalStorageEnforced == null
11624                        || mSettings.mReadExternalStorageEnforced != enforced) {
11625                    mSettings.mReadExternalStorageEnforced = enforced;
11626                    mSettings.writeLPr();
11627                }
11628            }
11629            // kill any non-foreground processes so we restart them and
11630            // grant/revoke the GID.
11631            final IActivityManager am = ActivityManagerNative.getDefault();
11632            if (am != null) {
11633                final long token = Binder.clearCallingIdentity();
11634                try {
11635                    am.killProcessesBelowForeground("setPermissionEnforcement");
11636                } catch (RemoteException e) {
11637                } finally {
11638                    Binder.restoreCallingIdentity(token);
11639                }
11640            }
11641        } else {
11642            throw new IllegalArgumentException("No selective enforcement for " + permission);
11643        }
11644    }
11645
11646    @Override
11647    @Deprecated
11648    public boolean isPermissionEnforced(String permission) {
11649        return true;
11650    }
11651
11652    @Override
11653    public boolean isStorageLow() {
11654        final long token = Binder.clearCallingIdentity();
11655        try {
11656            final DeviceStorageMonitorInternal
11657                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11658            if (dsm != null) {
11659                return dsm.isMemoryLow();
11660            } else {
11661                return false;
11662            }
11663        } finally {
11664            Binder.restoreCallingIdentity(token);
11665        }
11666    }
11667}
11668