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