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