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