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