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