PackageManagerService.java revision c79586ede6dcd6a167bc8360f058cb5cc655b33d
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.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
32import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
33import static com.android.internal.util.ArrayUtils.appendInt;
34import static com.android.internal.util.ArrayUtils.removeInt;
35
36import android.content.pm.PackageParser.*;
37import com.android.internal.app.IMediaContainerService;
38import com.android.internal.app.ResolverActivity;
39import com.android.internal.content.NativeLibraryHelper;
40import com.android.internal.content.PackageHelper;
41import com.android.internal.util.FastPrintWriter;
42import com.android.internal.util.FastXmlSerializer;
43import com.android.internal.util.XmlUtils;
44import com.android.server.EventLogTags;
45import com.android.server.IntentResolver;
46import com.android.server.ServiceThread;
47
48import com.android.server.LocalServices;
49import com.android.server.Watchdog;
50import org.xmlpull.v1.XmlPullParser;
51import org.xmlpull.v1.XmlPullParserException;
52import org.xmlpull.v1.XmlSerializer;
53
54import android.app.ActivityManager;
55import android.app.ActivityManagerNative;
56import android.app.IActivityManager;
57import android.app.admin.IDevicePolicyManager;
58import android.app.backup.IBackupManager;
59import android.content.BroadcastReceiver;
60import android.content.ComponentName;
61import android.content.Context;
62import android.content.IIntentReceiver;
63import android.content.Intent;
64import android.content.IntentFilter;
65import android.content.IntentSender;
66import android.content.IntentSender.SendIntentException;
67import android.content.ServiceConnection;
68import android.content.pm.ActivityInfo;
69import android.content.pm.ApplicationInfo;
70import android.content.pm.ContainerEncryptionParams;
71import android.content.pm.FeatureInfo;
72import android.content.pm.IPackageDataObserver;
73import android.content.pm.IPackageDeleteObserver;
74import android.content.pm.IPackageInstallObserver;
75import android.content.pm.IPackageInstallObserver2;
76import android.content.pm.IPackageManager;
77import android.content.pm.IPackageMoveObserver;
78import android.content.pm.IPackageStatsObserver;
79import android.content.pm.InstrumentationInfo;
80import android.content.pm.ManifestDigest;
81import android.content.pm.PackageCleanItem;
82import android.content.pm.PackageInfo;
83import android.content.pm.PackageInfoLite;
84import android.content.pm.PackageManager;
85import android.content.pm.PackageParser;
86import android.content.pm.PackageStats;
87import android.content.pm.PackageUserState;
88import android.content.pm.ParceledListSlice;
89import android.content.pm.PermissionGroupInfo;
90import android.content.pm.PermissionInfo;
91import android.content.pm.ProviderInfo;
92import android.content.pm.ResolveInfo;
93import android.content.pm.ServiceInfo;
94import android.content.pm.Signature;
95import android.content.pm.VerificationParams;
96import android.content.pm.VerifierDeviceIdentity;
97import android.content.pm.VerifierInfo;
98import android.content.res.Resources;
99import android.hardware.display.DisplayManager;
100import android.net.Uri;
101import android.os.Binder;
102import android.os.Build;
103import android.os.Bundle;
104import android.os.Environment;
105import android.os.Environment.UserEnvironment;
106import android.os.FileObserver;
107import android.os.FileUtils;
108import android.os.Handler;
109import android.os.IBinder;
110import android.os.Looper;
111import android.os.Message;
112import android.os.Parcel;
113import android.os.ParcelFileDescriptor;
114import android.os.Process;
115import android.os.RemoteException;
116import android.os.SELinux;
117import android.os.ServiceManager;
118import android.os.SystemClock;
119import android.os.SystemProperties;
120import android.os.UserHandle;
121import android.os.UserManager;
122import android.security.KeyStore;
123import android.security.SystemKeyStore;
124import android.system.ErrnoException;
125import android.system.Os;
126import android.system.StructStat;
127import android.text.TextUtils;
128import android.util.DisplayMetrics;
129import android.util.EventLog;
130import android.util.Log;
131import android.util.LogPrinter;
132import android.util.PrintStreamPrinter;
133import android.util.Slog;
134import android.util.SparseArray;
135import android.util.Xml;
136import android.view.Display;
137
138import java.io.BufferedOutputStream;
139import java.io.File;
140import java.io.FileDescriptor;
141import java.io.FileInputStream;
142import java.io.FileNotFoundException;
143import java.io.FileOutputStream;
144import java.io.FileReader;
145import java.io.FilenameFilter;
146import java.io.IOException;
147import java.io.PrintWriter;
148import java.security.NoSuchAlgorithmException;
149import java.security.PublicKey;
150import java.security.cert.Certificate;
151import java.security.cert.CertificateEncodingException;
152import java.security.cert.CertificateException;
153import java.text.SimpleDateFormat;
154import java.util.ArrayList;
155import java.util.Arrays;
156import java.util.Collection;
157import java.util.Collections;
158import java.util.Comparator;
159import java.util.Date;
160import java.util.HashMap;
161import java.util.HashSet;
162import java.util.Iterator;
163import java.util.List;
164import java.util.Map;
165import java.util.Set;
166
167import dalvik.system.VMRuntime;
168import libcore.io.IoUtils;
169
170import com.android.internal.R;
171import com.android.server.pm.Settings.DatabaseVersion;
172import com.android.server.storage.DeviceStorageMonitorInternal;
173
174/**
175 * Keep track of all those .apks everywhere.
176 *
177 * This is very central to the platform's security; please run the unit
178 * tests whenever making modifications here:
179 *
180mmm frameworks/base/tests/AndroidTests
181adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
182adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
183 *
184 * {@hide}
185 */
186public class PackageManagerService extends IPackageManager.Stub {
187    static final String TAG = "PackageManager";
188    static final boolean DEBUG_SETTINGS = false;
189    static final boolean DEBUG_PREFERRED = false;
190    static final boolean DEBUG_UPGRADE = false;
191    private static final boolean DEBUG_INSTALL = false;
192    private static final boolean DEBUG_REMOVE = false;
193    private static final boolean DEBUG_BROADCASTS = false;
194    private static final boolean DEBUG_SHOW_INFO = false;
195    private static final boolean DEBUG_PACKAGE_INFO = false;
196    private static final boolean DEBUG_INTENT_MATCHING = false;
197    private static final boolean DEBUG_PACKAGE_SCANNING = false;
198    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
199    private static final boolean DEBUG_VERIFY = false;
200
201    private static final int RADIO_UID = Process.PHONE_UID;
202    private static final int LOG_UID = Process.LOG_UID;
203    private static final int NFC_UID = Process.NFC_UID;
204    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
205    private static final int SHELL_UID = Process.SHELL_UID;
206
207    // Cap the size of permission trees that 3rd party apps can define
208    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
209
210    private static final int REMOVE_EVENTS =
211        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
212    private static final int ADD_EVENTS =
213        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
214
215    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
216    // Suffix used during package installation when copying/moving
217    // package apks to install directory.
218    private static final String INSTALL_PACKAGE_SUFFIX = "-";
219
220    static final int SCAN_MONITOR = 1<<0;
221    static final int SCAN_NO_DEX = 1<<1;
222    static final int SCAN_FORCE_DEX = 1<<2;
223    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
224    static final int SCAN_NEW_INSTALL = 1<<4;
225    static final int SCAN_NO_PATHS = 1<<5;
226    static final int SCAN_UPDATE_TIME = 1<<6;
227    static final int SCAN_DEFER_DEX = 1<<7;
228    static final int SCAN_BOOTING = 1<<8;
229    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
230    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
231
232    static final int REMOVE_CHATTY = 1<<16;
233
234    /**
235     * Timeout (in milliseconds) after which the watchdog should declare that
236     * our handler thread is wedged.  The usual default for such things is one
237     * minute but we sometimes do very lengthy I/O operations on this thread,
238     * such as installing multi-gigabyte applications, so ours needs to be longer.
239     */
240    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
241
242    /**
243     * Whether verification is enabled by default.
244     */
245    private static final boolean DEFAULT_VERIFY_ENABLE = true;
246
247    /**
248     * The default maximum time to wait for the verification agent to return in
249     * milliseconds.
250     */
251    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
252
253    /**
254     * The default response for package verification timeout.
255     *
256     * This can be either PackageManager.VERIFICATION_ALLOW or
257     * PackageManager.VERIFICATION_REJECT.
258     */
259    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
260
261    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
262
263    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
264            DEFAULT_CONTAINER_PACKAGE,
265            "com.android.defcontainer.DefaultContainerService");
266
267    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
268
269    private static final String LIB_DIR_NAME = "lib";
270    private static final String LIB64_DIR_NAME = "lib64";
271
272    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
273
274    static final String mTempContainerPrefix = "smdl2tmp";
275
276    private static String sPreferredInstructionSet;
277
278    final ServiceThread mHandlerThread;
279
280    private static final String IDMAP_PREFIX = "/data/resource-cache/";
281    private static final String IDMAP_SUFFIX = "@idmap";
282
283    final PackageHandler mHandler;
284
285    final int mSdkVersion = Build.VERSION.SDK_INT;
286
287    final Context mContext;
288    final boolean mFactoryTest;
289    final boolean mOnlyCore;
290    final boolean mNoDexOpt;
291    final DisplayMetrics mMetrics;
292    final int mDefParseFlags;
293    final String[] mSeparateProcesses;
294
295    // This is where all application persistent data goes.
296    final File mAppDataDir;
297
298    // This is where all application persistent data goes for secondary users.
299    final File mUserAppDataDir;
300
301    /** The location for ASEC container files on internal storage. */
302    final String mAsecInternalPath;
303
304    // This is the object monitoring the framework dir.
305    final FileObserver mFrameworkInstallObserver;
306
307    // This is the object monitoring the system app dir.
308    final FileObserver mSystemInstallObserver;
309
310    // This is the object monitoring the privileged system app dir.
311    final FileObserver mPrivilegedInstallObserver;
312
313    // This is the object monitoring the vendor app dir.
314    final FileObserver mVendorInstallObserver;
315
316    // This is the object monitoring the vendor overlay package dir.
317    final FileObserver mVendorOverlayInstallObserver;
318
319    // This is the object monitoring the OEM app dir.
320    final FileObserver mOemInstallObserver;
321
322    // This is the object monitoring mAppInstallDir.
323    final FileObserver mAppInstallObserver;
324
325    // This is the object monitoring mDrmAppPrivateInstallDir.
326    final FileObserver mDrmAppInstallObserver;
327
328    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
329    // LOCK HELD.  Can be called with mInstallLock held.
330    final Installer mInstaller;
331
332    final File mAppInstallDir;
333
334    /**
335     * Directory to which applications installed internally have native
336     * libraries copied.
337     */
338    private File mAppLibInstallDir;
339
340    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
341    // apps.
342    final File mDrmAppPrivateInstallDir;
343
344    // ----------------------------------------------------------------
345
346    // Lock for state used when installing and doing other long running
347    // operations.  Methods that must be called with this lock held have
348    // the suffix "LI".
349    final Object mInstallLock = new Object();
350
351    // These are the directories in the 3rd party applications installed dir
352    // that we have currently loaded packages from.  Keys are the application's
353    // installed zip file (absolute codePath), and values are Package.
354    final HashMap<String, PackageParser.Package> mAppDirs =
355            new HashMap<String, PackageParser.Package>();
356
357    // Information for the parser to write more useful error messages.
358    int mLastScanError;
359
360    // ----------------------------------------------------------------
361
362    // Keys are String (package name), values are Package.  This also serves
363    // as the lock for the global state.  Methods that must be called with
364    // this lock held have the prefix "LP".
365    final HashMap<String, PackageParser.Package> mPackages =
366            new HashMap<String, PackageParser.Package>();
367
368    // Tracks available target package names -> overlay package paths.
369    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
370        new HashMap<String, HashMap<String, PackageParser.Package>>();
371
372    final Settings mSettings;
373    boolean mRestoredSettings;
374
375    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
376    int[] mGlobalGids;
377
378    // These are the built-in uid -> permission mappings that were read from the
379    // etc/permissions.xml file.
380    final SparseArray<HashSet<String>> mSystemPermissions =
381            new SparseArray<HashSet<String>>();
382
383    static final class SharedLibraryEntry {
384        final String path;
385        final String apk;
386
387        SharedLibraryEntry(String _path, String _apk) {
388            path = _path;
389            apk = _apk;
390        }
391    }
392
393    // These are the built-in shared libraries that were read from the
394    // etc/permissions.xml file.
395    final HashMap<String, SharedLibraryEntry> mSharedLibraries
396            = new HashMap<String, SharedLibraryEntry>();
397
398    // Temporary for building the final shared libraries for an .apk.
399    String[] mTmpSharedLibraries = null;
400
401    // These are the features this devices supports that were read from the
402    // etc/permissions.xml file.
403    final HashMap<String, FeatureInfo> mAvailableFeatures =
404            new HashMap<String, FeatureInfo>();
405
406    // If mac_permissions.xml was found for seinfo labeling.
407    boolean mFoundPolicyFile;
408
409    // If a recursive restorecon of /data/data/<pkg> is needed.
410    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
411
412    // All available activities, for your resolving pleasure.
413    final ActivityIntentResolver mActivities =
414            new ActivityIntentResolver();
415
416    // All available receivers, for your resolving pleasure.
417    final ActivityIntentResolver mReceivers =
418            new ActivityIntentResolver();
419
420    // All available services, for your resolving pleasure.
421    final ServiceIntentResolver mServices = new ServiceIntentResolver();
422
423    // All available providers, for your resolving pleasure.
424    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
425
426    // Mapping from provider base names (first directory in content URI codePath)
427    // to the provider information.
428    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
429            new HashMap<String, PackageParser.Provider>();
430
431    // Mapping from instrumentation class names to info about them.
432    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
433            new HashMap<ComponentName, PackageParser.Instrumentation>();
434
435    // Mapping from permission names to info about them.
436    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
437            new HashMap<String, PackageParser.PermissionGroup>();
438
439    // Packages whose data we have transfered into another package, thus
440    // should no longer exist.
441    final HashSet<String> mTransferedPackages = new HashSet<String>();
442
443    // Broadcast actions that are only available to the system.
444    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
445
446    /** List of packages waiting for verification. */
447    final SparseArray<PackageVerificationState> mPendingVerification
448            = new SparseArray<PackageVerificationState>();
449
450    HashSet<PackageParser.Package> mDeferredDexOpt = null;
451
452    /** Token for keys in mPendingVerification. */
453    private int mPendingVerificationToken = 0;
454
455    boolean mSystemReady;
456    boolean mSafeMode;
457    boolean mHasSystemUidErrors;
458
459    ApplicationInfo mAndroidApplication;
460    final ActivityInfo mResolveActivity = new ActivityInfo();
461    final ResolveInfo mResolveInfo = new ResolveInfo();
462    ComponentName mResolveComponentName;
463    PackageParser.Package mPlatformPackage;
464    ComponentName mCustomResolverComponentName;
465
466    boolean mResolverReplaced = false;
467
468    // Set of pending broadcasts for aggregating enable/disable of components.
469    static class PendingPackageBroadcasts {
470        // for each user id, a map of <package name -> components within that package>
471        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
472
473        public PendingPackageBroadcasts() {
474            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
475        }
476
477        public ArrayList<String> get(int userId, String packageName) {
478            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
479            return packages.get(packageName);
480        }
481
482        public void put(int userId, String packageName, ArrayList<String> components) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            packages.put(packageName, components);
485        }
486
487        public void remove(int userId, String packageName) {
488            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
489            if (packages != null) {
490                packages.remove(packageName);
491            }
492        }
493
494        public void remove(int userId) {
495            mUidMap.remove(userId);
496        }
497
498        public int userIdCount() {
499            return mUidMap.size();
500        }
501
502        public int userIdAt(int n) {
503            return mUidMap.keyAt(n);
504        }
505
506        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
507            return mUidMap.get(userId);
508        }
509
510        public int size() {
511            // total number of pending broadcast entries across all userIds
512            int num = 0;
513            for (int i = 0; i< mUidMap.size(); i++) {
514                num += mUidMap.valueAt(i).size();
515            }
516            return num;
517        }
518
519        public void clear() {
520            mUidMap.clear();
521        }
522
523        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
524            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
525            if (map == null) {
526                map = new HashMap<String, ArrayList<String>>();
527                mUidMap.put(userId, map);
528            }
529            return map;
530        }
531    }
532    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
533
534    // Service Connection to remote media container service to copy
535    // package uri's from external media onto secure containers
536    // or internal storage.
537    private IMediaContainerService mContainerService = null;
538
539    static final int SEND_PENDING_BROADCAST = 1;
540    static final int MCS_BOUND = 3;
541    static final int END_COPY = 4;
542    static final int INIT_COPY = 5;
543    static final int MCS_UNBIND = 6;
544    static final int START_CLEANING_PACKAGE = 7;
545    static final int FIND_INSTALL_LOC = 8;
546    static final int POST_INSTALL = 9;
547    static final int MCS_RECONNECT = 10;
548    static final int MCS_GIVE_UP = 11;
549    static final int UPDATED_MEDIA_STATUS = 12;
550    static final int WRITE_SETTINGS = 13;
551    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
552    static final int PACKAGE_VERIFIED = 15;
553    static final int CHECK_PENDING_VERIFICATION = 16;
554
555    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
556
557    // Delay time in millisecs
558    static final int BROADCAST_DELAY = 10 * 1000;
559
560    static UserManagerService sUserManager;
561
562    // Stores a list of users whose package restrictions file needs to be updated
563    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
564
565    final private DefaultContainerConnection mDefContainerConn =
566            new DefaultContainerConnection();
567    class DefaultContainerConnection implements ServiceConnection {
568        public void onServiceConnected(ComponentName name, IBinder service) {
569            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
570            IMediaContainerService imcs =
571                IMediaContainerService.Stub.asInterface(service);
572            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
573        }
574
575        public void onServiceDisconnected(ComponentName name) {
576            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
577        }
578    };
579
580    // Recordkeeping of restore-after-install operations that are currently in flight
581    // between the Package Manager and the Backup Manager
582    class PostInstallData {
583        public InstallArgs args;
584        public PackageInstalledInfo res;
585
586        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
587            args = _a;
588            res = _r;
589        }
590    };
591    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
592    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
593
594    private final String mRequiredVerifierPackage;
595
596    class PackageHandler extends Handler {
597        private boolean mBound = false;
598        final ArrayList<HandlerParams> mPendingInstalls =
599            new ArrayList<HandlerParams>();
600
601        private boolean connectToService() {
602            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
603                    " DefaultContainerService");
604            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
605            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
606            if (mContext.bindServiceAsUser(service, mDefContainerConn,
607                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
608                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
609                mBound = true;
610                return true;
611            }
612            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
613            return false;
614        }
615
616        private void disconnectService() {
617            mContainerService = null;
618            mBound = false;
619            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
620            mContext.unbindService(mDefContainerConn);
621            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
622        }
623
624        PackageHandler(Looper looper) {
625            super(looper);
626        }
627
628        public void handleMessage(Message msg) {
629            try {
630                doHandleMessage(msg);
631            } finally {
632                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
633            }
634        }
635
636        void doHandleMessage(Message msg) {
637            switch (msg.what) {
638                case INIT_COPY: {
639                    HandlerParams params = (HandlerParams) msg.obj;
640                    int idx = mPendingInstalls.size();
641                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
642                    // If a bind was already initiated we dont really
643                    // need to do anything. The pending install
644                    // will be processed later on.
645                    if (!mBound) {
646                        // If this is the only one pending we might
647                        // have to bind to the service again.
648                        if (!connectToService()) {
649                            Slog.e(TAG, "Failed to bind to media container service");
650                            params.serviceError();
651                            return;
652                        } else {
653                            // Once we bind to the service, the first
654                            // pending request will be processed.
655                            mPendingInstalls.add(idx, params);
656                        }
657                    } else {
658                        mPendingInstalls.add(idx, params);
659                        // Already bound to the service. Just make
660                        // sure we trigger off processing the first request.
661                        if (idx == 0) {
662                            mHandler.sendEmptyMessage(MCS_BOUND);
663                        }
664                    }
665                    break;
666                }
667                case MCS_BOUND: {
668                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
669                    if (msg.obj != null) {
670                        mContainerService = (IMediaContainerService) msg.obj;
671                    }
672                    if (mContainerService == null) {
673                        // Something seriously wrong. Bail out
674                        Slog.e(TAG, "Cannot bind to media container service");
675                        for (HandlerParams params : mPendingInstalls) {
676                            // Indicate service bind error
677                            params.serviceError();
678                        }
679                        mPendingInstalls.clear();
680                    } else if (mPendingInstalls.size() > 0) {
681                        HandlerParams params = mPendingInstalls.get(0);
682                        if (params != null) {
683                            if (params.startCopy()) {
684                                // We are done...  look for more work or to
685                                // go idle.
686                                if (DEBUG_SD_INSTALL) Log.i(TAG,
687                                        "Checking for more work or unbind...");
688                                // Delete pending install
689                                if (mPendingInstalls.size() > 0) {
690                                    mPendingInstalls.remove(0);
691                                }
692                                if (mPendingInstalls.size() == 0) {
693                                    if (mBound) {
694                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
695                                                "Posting delayed MCS_UNBIND");
696                                        removeMessages(MCS_UNBIND);
697                                        Message ubmsg = obtainMessage(MCS_UNBIND);
698                                        // Unbind after a little delay, to avoid
699                                        // continual thrashing.
700                                        sendMessageDelayed(ubmsg, 10000);
701                                    }
702                                } else {
703                                    // There are more pending requests in queue.
704                                    // Just post MCS_BOUND message to trigger processing
705                                    // of next pending install.
706                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
707                                            "Posting MCS_BOUND for next work");
708                                    mHandler.sendEmptyMessage(MCS_BOUND);
709                                }
710                            }
711                        }
712                    } else {
713                        // Should never happen ideally.
714                        Slog.w(TAG, "Empty queue");
715                    }
716                    break;
717                }
718                case MCS_RECONNECT: {
719                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
720                    if (mPendingInstalls.size() > 0) {
721                        if (mBound) {
722                            disconnectService();
723                        }
724                        if (!connectToService()) {
725                            Slog.e(TAG, "Failed to bind to media container service");
726                            for (HandlerParams params : mPendingInstalls) {
727                                // Indicate service bind error
728                                params.serviceError();
729                            }
730                            mPendingInstalls.clear();
731                        }
732                    }
733                    break;
734                }
735                case MCS_UNBIND: {
736                    // If there is no actual work left, then time to unbind.
737                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
738
739                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
740                        if (mBound) {
741                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
742
743                            disconnectService();
744                        }
745                    } else if (mPendingInstalls.size() > 0) {
746                        // There are more pending requests in queue.
747                        // Just post MCS_BOUND message to trigger processing
748                        // of next pending install.
749                        mHandler.sendEmptyMessage(MCS_BOUND);
750                    }
751
752                    break;
753                }
754                case MCS_GIVE_UP: {
755                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
756                    mPendingInstalls.remove(0);
757                    break;
758                }
759                case SEND_PENDING_BROADCAST: {
760                    String packages[];
761                    ArrayList<String> components[];
762                    int size = 0;
763                    int uids[];
764                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765                    synchronized (mPackages) {
766                        if (mPendingBroadcasts == null) {
767                            return;
768                        }
769                        size = mPendingBroadcasts.size();
770                        if (size <= 0) {
771                            // Nothing to be done. Just return
772                            return;
773                        }
774                        packages = new String[size];
775                        components = new ArrayList[size];
776                        uids = new int[size];
777                        int i = 0;  // filling out the above arrays
778
779                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
780                            int packageUserId = mPendingBroadcasts.userIdAt(n);
781                            Iterator<Map.Entry<String, ArrayList<String>>> it
782                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
783                                            .entrySet().iterator();
784                            while (it.hasNext() && i < size) {
785                                Map.Entry<String, ArrayList<String>> ent = it.next();
786                                packages[i] = ent.getKey();
787                                components[i] = ent.getValue();
788                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
789                                uids[i] = (ps != null)
790                                        ? UserHandle.getUid(packageUserId, ps.appId)
791                                        : -1;
792                                i++;
793                            }
794                        }
795                        size = i;
796                        mPendingBroadcasts.clear();
797                    }
798                    // Send broadcasts
799                    for (int i = 0; i < size; i++) {
800                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
801                    }
802                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
803                    break;
804                }
805                case START_CLEANING_PACKAGE: {
806                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
807                    final String packageName = (String)msg.obj;
808                    final int userId = msg.arg1;
809                    final boolean andCode = msg.arg2 != 0;
810                    synchronized (mPackages) {
811                        if (userId == UserHandle.USER_ALL) {
812                            int[] users = sUserManager.getUserIds();
813                            for (int user : users) {
814                                mSettings.addPackageToCleanLPw(
815                                        new PackageCleanItem(user, packageName, andCode));
816                            }
817                        } else {
818                            mSettings.addPackageToCleanLPw(
819                                    new PackageCleanItem(userId, packageName, andCode));
820                        }
821                    }
822                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
823                    startCleaningPackages();
824                } break;
825                case POST_INSTALL: {
826                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
827                    PostInstallData data = mRunningInstalls.get(msg.arg1);
828                    mRunningInstalls.delete(msg.arg1);
829                    boolean deleteOld = false;
830
831                    if (data != null) {
832                        InstallArgs args = data.args;
833                        PackageInstalledInfo res = data.res;
834
835                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
836                            res.removedInfo.sendBroadcast(false, true, false);
837                            Bundle extras = new Bundle(1);
838                            extras.putInt(Intent.EXTRA_UID, res.uid);
839                            // Determine the set of users who are adding this
840                            // package for the first time vs. those who are seeing
841                            // an update.
842                            int[] firstUsers;
843                            int[] updateUsers = new int[0];
844                            if (res.origUsers == null || res.origUsers.length == 0) {
845                                firstUsers = res.newUsers;
846                            } else {
847                                firstUsers = new int[0];
848                                for (int i=0; i<res.newUsers.length; i++) {
849                                    int user = res.newUsers[i];
850                                    boolean isNew = true;
851                                    for (int j=0; j<res.origUsers.length; j++) {
852                                        if (res.origUsers[j] == user) {
853                                            isNew = false;
854                                            break;
855                                        }
856                                    }
857                                    if (isNew) {
858                                        int[] newFirst = new int[firstUsers.length+1];
859                                        System.arraycopy(firstUsers, 0, newFirst, 0,
860                                                firstUsers.length);
861                                        newFirst[firstUsers.length] = user;
862                                        firstUsers = newFirst;
863                                    } else {
864                                        int[] newUpdate = new int[updateUsers.length+1];
865                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
866                                                updateUsers.length);
867                                        newUpdate[updateUsers.length] = user;
868                                        updateUsers = newUpdate;
869                                    }
870                                }
871                            }
872                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
873                                    res.pkg.applicationInfo.packageName,
874                                    extras, null, null, firstUsers);
875                            final boolean update = res.removedInfo.removedPackage != null;
876                            if (update) {
877                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
878                            }
879                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
880                                    res.pkg.applicationInfo.packageName,
881                                    extras, null, null, updateUsers);
882                            if (update) {
883                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
884                                        res.pkg.applicationInfo.packageName,
885                                        extras, null, null, updateUsers);
886                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
887                                        null, null,
888                                        res.pkg.applicationInfo.packageName, null, updateUsers);
889
890                                // treat asec-hosted packages like removable media on upgrade
891                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
892                                    if (DEBUG_INSTALL) {
893                                        Slog.i(TAG, "upgrading pkg " + res.pkg
894                                                + " is ASEC-hosted -> AVAILABLE");
895                                    }
896                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
897                                    ArrayList<String> pkgList = new ArrayList<String>(1);
898                                    pkgList.add(res.pkg.applicationInfo.packageName);
899                                    sendResourcesChangedBroadcast(true, true,
900                                            pkgList,uidArray, null);
901                                }
902                            }
903                            if (res.removedInfo.args != null) {
904                                // Remove the replaced package's older resources safely now
905                                deleteOld = true;
906                            }
907
908                            // Log current value of "unknown sources" setting
909                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
910                                getUnknownSourcesSettings());
911                        }
912                        // Force a gc to clear up things
913                        Runtime.getRuntime().gc();
914                        // We delete after a gc for applications  on sdcard.
915                        if (deleteOld) {
916                            synchronized (mInstallLock) {
917                                res.removedInfo.args.doPostDeleteLI(true);
918                            }
919                        }
920                        if (args.observer != null) {
921                            try {
922                                args.observer.packageInstalled(res.name, res.returnCode);
923                            } catch (RemoteException e) {
924                                Slog.i(TAG, "Observer no longer exists.");
925                            }
926                        }
927                        if (args.observer2 != null) {
928                            try {
929                                Bundle extras = extrasForInstallResult(res);
930                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
931                            } catch (RemoteException e) {
932                                Slog.i(TAG, "Observer no longer exists.");
933                            }
934                        }
935                    } else {
936                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
937                    }
938                } break;
939                case UPDATED_MEDIA_STATUS: {
940                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
941                    boolean reportStatus = msg.arg1 == 1;
942                    boolean doGc = msg.arg2 == 1;
943                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
944                    if (doGc) {
945                        // Force a gc to clear up stale containers.
946                        Runtime.getRuntime().gc();
947                    }
948                    if (msg.obj != null) {
949                        @SuppressWarnings("unchecked")
950                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
951                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
952                        // Unload containers
953                        unloadAllContainers(args);
954                    }
955                    if (reportStatus) {
956                        try {
957                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
958                            PackageHelper.getMountService().finishMediaUpdate();
959                        } catch (RemoteException e) {
960                            Log.e(TAG, "MountService not running?");
961                        }
962                    }
963                } break;
964                case WRITE_SETTINGS: {
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
966                    synchronized (mPackages) {
967                        removeMessages(WRITE_SETTINGS);
968                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
969                        mSettings.writeLPr();
970                        mDirtyUsers.clear();
971                    }
972                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
973                } break;
974                case WRITE_PACKAGE_RESTRICTIONS: {
975                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
976                    synchronized (mPackages) {
977                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
978                        for (int userId : mDirtyUsers) {
979                            mSettings.writePackageRestrictionsLPr(userId);
980                        }
981                        mDirtyUsers.clear();
982                    }
983                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
984                } break;
985                case CHECK_PENDING_VERIFICATION: {
986                    final int verificationId = msg.arg1;
987                    final PackageVerificationState state = mPendingVerification.get(verificationId);
988
989                    if ((state != null) && !state.timeoutExtended()) {
990                        final InstallArgs args = state.getInstallArgs();
991                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
992                        mPendingVerification.remove(verificationId);
993
994                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
995
996                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
997                            Slog.i(TAG, "Continuing with installation of "
998                                    + args.packageURI.toString());
999                            state.setVerifierResponse(Binder.getCallingUid(),
1000                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1001                            broadcastPackageVerified(verificationId, args.packageURI,
1002                                    PackageManager.VERIFICATION_ALLOW,
1003                                    state.getInstallArgs().getUser());
1004                            try {
1005                                ret = args.copyApk(mContainerService, true);
1006                            } catch (RemoteException e) {
1007                                Slog.e(TAG, "Could not contact the ContainerService");
1008                            }
1009                        } else {
1010                            broadcastPackageVerified(verificationId, args.packageURI,
1011                                    PackageManager.VERIFICATION_REJECT,
1012                                    state.getInstallArgs().getUser());
1013                        }
1014
1015                        processPendingInstall(args, ret);
1016                        mHandler.sendEmptyMessage(MCS_UNBIND);
1017                    }
1018                    break;
1019                }
1020                case PACKAGE_VERIFIED: {
1021                    final int verificationId = msg.arg1;
1022
1023                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1024                    if (state == null) {
1025                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1026                        break;
1027                    }
1028
1029                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1030
1031                    state.setVerifierResponse(response.callerUid, response.code);
1032
1033                    if (state.isVerificationComplete()) {
1034                        mPendingVerification.remove(verificationId);
1035
1036                        final InstallArgs args = state.getInstallArgs();
1037
1038                        int ret;
1039                        if (state.isInstallAllowed()) {
1040                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1041                            broadcastPackageVerified(verificationId, args.packageURI,
1042                                    response.code, state.getInstallArgs().getUser());
1043                            try {
1044                                ret = args.copyApk(mContainerService, true);
1045                            } catch (RemoteException e) {
1046                                Slog.e(TAG, "Could not contact the ContainerService");
1047                            }
1048                        } else {
1049                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1050                        }
1051
1052                        processPendingInstall(args, ret);
1053
1054                        mHandler.sendEmptyMessage(MCS_UNBIND);
1055                    }
1056
1057                    break;
1058                }
1059            }
1060        }
1061    }
1062
1063    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1064        Bundle extras = null;
1065        switch (res.returnCode) {
1066            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1067                extras = new Bundle();
1068                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1069                        res.origPermission);
1070                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1071                        res.origPackage);
1072                break;
1073            }
1074        }
1075        return extras;
1076    }
1077
1078    void scheduleWriteSettingsLocked() {
1079        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1080            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1081        }
1082    }
1083
1084    void scheduleWritePackageRestrictionsLocked(int userId) {
1085        if (!sUserManager.exists(userId)) return;
1086        mDirtyUsers.add(userId);
1087        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1088            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1089        }
1090    }
1091
1092    public static final IPackageManager main(Context context, Installer installer,
1093            boolean factoryTest, boolean onlyCore) {
1094        PackageManagerService m = new PackageManagerService(context, installer,
1095                factoryTest, onlyCore);
1096        ServiceManager.addService("package", m);
1097        return m;
1098    }
1099
1100    static String[] splitString(String str, char sep) {
1101        int count = 1;
1102        int i = 0;
1103        while ((i=str.indexOf(sep, i)) >= 0) {
1104            count++;
1105            i++;
1106        }
1107
1108        String[] res = new String[count];
1109        i=0;
1110        count = 0;
1111        int lastI=0;
1112        while ((i=str.indexOf(sep, i)) >= 0) {
1113            res[count] = str.substring(lastI, i);
1114            count++;
1115            i++;
1116            lastI = i;
1117        }
1118        res[count] = str.substring(lastI, str.length());
1119        return res;
1120    }
1121
1122    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1123        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1124                Context.DISPLAY_SERVICE);
1125        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1126    }
1127
1128    public PackageManagerService(Context context, Installer installer,
1129            boolean factoryTest, boolean onlyCore) {
1130        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1131                SystemClock.uptimeMillis());
1132
1133        if (mSdkVersion <= 0) {
1134            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1135        }
1136
1137        mContext = context;
1138        mFactoryTest = factoryTest;
1139        mOnlyCore = onlyCore;
1140        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1141        mMetrics = new DisplayMetrics();
1142        mSettings = new Settings(context);
1143        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1144                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1145        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1146                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1147        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1148                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1149        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1150                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1151        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1152                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1153        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1154                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1155
1156        String separateProcesses = SystemProperties.get("debug.separate_processes");
1157        if (separateProcesses != null && separateProcesses.length() > 0) {
1158            if ("*".equals(separateProcesses)) {
1159                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1160                mSeparateProcesses = null;
1161                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1162            } else {
1163                mDefParseFlags = 0;
1164                mSeparateProcesses = separateProcesses.split(",");
1165                Slog.w(TAG, "Running with debug.separate_processes: "
1166                        + separateProcesses);
1167            }
1168        } else {
1169            mDefParseFlags = 0;
1170            mSeparateProcesses = null;
1171        }
1172
1173        mInstaller = installer;
1174
1175        getDefaultDisplayMetrics(context, mMetrics);
1176
1177        synchronized (mInstallLock) {
1178        // writer
1179        synchronized (mPackages) {
1180            mHandlerThread = new ServiceThread(TAG,
1181                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1182            mHandlerThread.start();
1183            mHandler = new PackageHandler(mHandlerThread.getLooper());
1184            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1185
1186            File dataDir = Environment.getDataDirectory();
1187            mAppDataDir = new File(dataDir, "data");
1188            mAppInstallDir = new File(dataDir, "app");
1189            mAppLibInstallDir = new File(dataDir, "app-lib");
1190            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1191            mUserAppDataDir = new File(dataDir, "user");
1192            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1193
1194            sUserManager = new UserManagerService(context, this,
1195                    mInstallLock, mPackages);
1196
1197            // Read permissions and features from system
1198            readPermissions(Environment.buildPath(
1199                    Environment.getRootDirectory(), "etc", "permissions"), false);
1200            // Only read features from OEM
1201            readPermissions(Environment.buildPath(
1202                    Environment.getOemDirectory(), "etc", "permissions"), true);
1203
1204            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1205
1206            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1207                    mSdkVersion, mOnlyCore);
1208
1209            String customResolverActivity = Resources.getSystem().getString(
1210                    R.string.config_customResolverActivity);
1211            if (TextUtils.isEmpty(customResolverActivity)) {
1212                customResolverActivity = null;
1213            } else {
1214                mCustomResolverComponentName = ComponentName.unflattenFromString(
1215                        customResolverActivity);
1216            }
1217
1218            long startTime = SystemClock.uptimeMillis();
1219
1220            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1221                    startTime);
1222
1223            // Set flag to monitor and not change apk file paths when
1224            // scanning install directories.
1225            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1226            if (mNoDexOpt) {
1227                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1228                scanMode |= SCAN_NO_DEX;
1229            }
1230
1231            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1232
1233            /**
1234             * Add everything in the in the boot class path to the
1235             * list of process files because dexopt will have been run
1236             * if necessary during zygote startup.
1237             */
1238            String bootClassPath = System.getProperty("java.boot.class.path");
1239            if (bootClassPath != null) {
1240                String[] paths = splitString(bootClassPath, ':');
1241                for (int i=0; i<paths.length; i++) {
1242                    alreadyDexOpted.add(paths[i]);
1243                }
1244            } else {
1245                Slog.w(TAG, "No BOOTCLASSPATH found!");
1246            }
1247
1248            boolean didDexOpt = false;
1249
1250            final List<String> instructionSets = getAllInstructionSets();
1251
1252            /**
1253             * Ensure all external libraries have had dexopt run on them.
1254             */
1255            if (mSharedLibraries.size() > 0) {
1256                // NOTE: For now, we're compiling these system "shared libraries"
1257                // (and framework jars) into all available architectures. It's possible
1258                // to compile them only when we come across an app that uses them (there's
1259                // already logic for that in scanPackageLI) but that adds some complexity.
1260                for (String instructionSet : instructionSets) {
1261                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1262                        final String lib = libEntry.path;
1263                        if (lib == null) {
1264                            continue;
1265                        }
1266
1267                        try {
1268                            if (dalvik.system.DexFile.isDexOptNeededInternal(
1269                                    lib, null, instructionSet, false)) {
1270                                alreadyDexOpted.add(lib);
1271
1272                                // The list of "shared libraries" we have at this point is
1273                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1274                                didDexOpt = true;
1275                            }
1276                        } catch (FileNotFoundException e) {
1277                            Slog.w(TAG, "Library not found: " + lib);
1278                        } catch (IOException e) {
1279                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1280                                    + e.getMessage());
1281                        }
1282                    }
1283                }
1284            }
1285
1286            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1287
1288            // Gross hack for now: we know this file doesn't contain any
1289            // code, so don't dexopt it to avoid the resulting log spew.
1290            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1291
1292            // Gross hack for now: we know this file is only part of
1293            // the boot class path for art, so don't dexopt it to
1294            // avoid the resulting log spew.
1295            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1296
1297            /**
1298             * And there are a number of commands implemented in Java, which
1299             * we currently need to do the dexopt on so that they can be
1300             * run from a non-root shell.
1301             */
1302            String[] frameworkFiles = frameworkDir.list();
1303            if (frameworkFiles != null) {
1304                // TODO: We could compile these only for the most preferred ABI. We should
1305                // first double check that the dex files for these commands are not referenced
1306                // by other system apps.
1307                for (String instructionSet : instructionSets) {
1308                    for (int i=0; i<frameworkFiles.length; i++) {
1309                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1310                        String path = libPath.getPath();
1311                        // Skip the file if we already did it.
1312                        if (alreadyDexOpted.contains(path)) {
1313                            continue;
1314                        }
1315                        // Skip the file if it is not a type we want to dexopt.
1316                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1317                            continue;
1318                        }
1319                        try {
1320                            if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1321                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1322                                didDexOpt = true;
1323                            }
1324                        } catch (FileNotFoundException e) {
1325                            Slog.w(TAG, "Jar not found: " + path);
1326                        } catch (IOException e) {
1327                            Slog.w(TAG, "Exception reading jar: " + path, e);
1328                        }
1329                    }
1330                }
1331            }
1332
1333            if (didDexOpt) {
1334                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1335            }
1336
1337            // Collect vendor overlay packages.
1338            // (Do this before scanning any apps.)
1339            // For security and version matching reason, only consider
1340            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1341            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1342            mVendorOverlayInstallObserver = new AppDirObserver(
1343                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1344            mVendorOverlayInstallObserver.startWatching();
1345            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1346                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1347
1348            // Find base frameworks (resource packages without code).
1349            mFrameworkInstallObserver = new AppDirObserver(
1350                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1351            mFrameworkInstallObserver.startWatching();
1352            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1353                    | PackageParser.PARSE_IS_SYSTEM_DIR
1354                    | PackageParser.PARSE_IS_PRIVILEGED,
1355                    scanMode | SCAN_NO_DEX, 0);
1356
1357            // Collected privileged system packages.
1358            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1359            mPrivilegedInstallObserver = new AppDirObserver(
1360                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1361            mPrivilegedInstallObserver.startWatching();
1362                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1363                        | PackageParser.PARSE_IS_SYSTEM_DIR
1364                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1365
1366            // Collect ordinary system packages.
1367            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1368            mSystemInstallObserver = new AppDirObserver(
1369                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1370            mSystemInstallObserver.startWatching();
1371            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1372                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1373
1374            // Collect all vendor packages.
1375            File vendorAppDir = new File("/vendor/app");
1376            try {
1377                vendorAppDir = vendorAppDir.getCanonicalFile();
1378            } catch (IOException e) {
1379                // failed to look up canonical path, continue with original one
1380            }
1381            mVendorInstallObserver = new AppDirObserver(
1382                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1383            mVendorInstallObserver.startWatching();
1384            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1385                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1386
1387            // Collect all OEM packages.
1388            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1389            mOemInstallObserver = new AppDirObserver(
1390                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1391            mOemInstallObserver.startWatching();
1392            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1393                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1394
1395            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1396            mInstaller.moveFiles();
1397
1398            // Prune any system packages that no longer exist.
1399            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1400            if (!mOnlyCore) {
1401                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1402                while (psit.hasNext()) {
1403                    PackageSetting ps = psit.next();
1404
1405                    /*
1406                     * If this is not a system app, it can't be a
1407                     * disable system app.
1408                     */
1409                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1410                        continue;
1411                    }
1412
1413                    /*
1414                     * If the package is scanned, it's not erased.
1415                     */
1416                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1417                    if (scannedPkg != null) {
1418                        /*
1419                         * If the system app is both scanned and in the
1420                         * disabled packages list, then it must have been
1421                         * added via OTA. Remove it from the currently
1422                         * scanned package so the previously user-installed
1423                         * application can be scanned.
1424                         */
1425                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1426                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1427                                    + "; removing system app");
1428                            removePackageLI(ps, true);
1429                        }
1430
1431                        continue;
1432                    }
1433
1434                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1435                        psit.remove();
1436                        String msg = "System package " + ps.name
1437                                + " no longer exists; wiping its data";
1438                        reportSettingsProblem(Log.WARN, msg);
1439                        removeDataDirsLI(ps.name);
1440                    } else {
1441                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1442                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1443                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1444                        }
1445                    }
1446                }
1447            }
1448
1449            //look for any incomplete package installations
1450            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1451            //clean up list
1452            for(int i = 0; i < deletePkgsList.size(); i++) {
1453                //clean up here
1454                cleanupInstallFailedPackage(deletePkgsList.get(i));
1455            }
1456            //delete tmp files
1457            deleteTempPackageFiles();
1458
1459            // Remove any shared userIDs that have no associated packages
1460            mSettings.pruneSharedUsersLPw();
1461
1462            if (!mOnlyCore) {
1463                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1464                        SystemClock.uptimeMillis());
1465                mAppInstallObserver = new AppDirObserver(
1466                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1467                mAppInstallObserver.startWatching();
1468                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1469
1470                mDrmAppInstallObserver = new AppDirObserver(
1471                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1472                mDrmAppInstallObserver.startWatching();
1473                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1474                        scanMode, 0);
1475
1476                /**
1477                 * Remove disable package settings for any updated system
1478                 * apps that were removed via an OTA. If they're not a
1479                 * previously-updated app, remove them completely.
1480                 * Otherwise, just revoke their system-level permissions.
1481                 */
1482                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1483                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1484                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1485
1486                    String msg;
1487                    if (deletedPkg == null) {
1488                        msg = "Updated system package " + deletedAppName
1489                                + " no longer exists; wiping its data";
1490                        removeDataDirsLI(deletedAppName);
1491                    } else {
1492                        msg = "Updated system app + " + deletedAppName
1493                                + " no longer present; removing system privileges for "
1494                                + deletedAppName;
1495
1496                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1497
1498                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1499                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1500                    }
1501                    reportSettingsProblem(Log.WARN, msg);
1502                }
1503            } else {
1504                mAppInstallObserver = null;
1505                mDrmAppInstallObserver = null;
1506            }
1507
1508            // Now that we know all of the shared libraries, update all clients to have
1509            // the correct library paths.
1510            updateAllSharedLibrariesLPw();
1511
1512
1513            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1514                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1515                        false /* force dexopt */, false /* defer dexopt */);
1516            }
1517
1518            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1519                    SystemClock.uptimeMillis());
1520            Slog.i(TAG, "Time to scan packages: "
1521                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1522                    + " seconds");
1523
1524            // If the platform SDK has changed since the last time we booted,
1525            // we need to re-grant app permission to catch any new ones that
1526            // appear.  This is really a hack, and means that apps can in some
1527            // cases get permissions that the user didn't initially explicitly
1528            // allow...  it would be nice to have some better way to handle
1529            // this situation.
1530            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1531                    != mSdkVersion;
1532            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1533                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1534                    + "; regranting permissions for internal storage");
1535            mSettings.mInternalSdkPlatform = mSdkVersion;
1536
1537            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1538                    | (regrantPermissions
1539                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1540                            : 0));
1541
1542            // If this is the first boot, and it is a normal boot, then
1543            // we need to initialize the default preferred apps.
1544            if (!mRestoredSettings && !onlyCore) {
1545                mSettings.readDefaultPreferredAppsLPw(this, 0);
1546            }
1547
1548            // All the changes are done during package scanning.
1549            mSettings.updateInternalDatabaseVersion();
1550
1551            // can downgrade to reader
1552            mSettings.writeLPr();
1553
1554            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1555                    SystemClock.uptimeMillis());
1556
1557            // Now after opening every single application zip, make sure they
1558            // are all flushed.  Not really needed, but keeps things nice and
1559            // tidy.
1560            Runtime.getRuntime().gc();
1561
1562            mRequiredVerifierPackage = getRequiredVerifierLPr();
1563        } // synchronized (mPackages)
1564        } // synchronized (mInstallLock)
1565    }
1566
1567    private static void pruneDexFiles(File cacheDir) {
1568        // If we had to do a dexopt of one of the previous
1569        // things, then something on the system has changed.
1570        // Consider this significant, and wipe away all other
1571        // existing dexopt files to ensure we don't leave any
1572        // dangling around.
1573        //
1574        // Additionally, delete all dex files from the root directory
1575        // since there shouldn't be any there anyway.
1576        File[] files = cacheDir.listFiles();
1577        if (files != null) {
1578            for (File file : files) {
1579                if (!file.isDirectory()) {
1580                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1581                    file.delete();
1582                } else {
1583                    File[] subDirList = file.listFiles();
1584                    if (subDirList != null) {
1585                        for (File subDirFile : subDirList) {
1586                            final String fn = subDirFile.getName();
1587                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1588                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1589                                subDirFile.delete();
1590                            }
1591                        }
1592                    }
1593                }
1594            }
1595        }
1596    }
1597
1598    public boolean isFirstBoot() {
1599        return !mRestoredSettings;
1600    }
1601
1602    public boolean isOnlyCoreApps() {
1603        return mOnlyCore;
1604    }
1605
1606    private String getRequiredVerifierLPr() {
1607        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1608        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1609                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1610
1611        String requiredVerifier = null;
1612
1613        final int N = receivers.size();
1614        for (int i = 0; i < N; i++) {
1615            final ResolveInfo info = receivers.get(i);
1616
1617            if (info.activityInfo == null) {
1618                continue;
1619            }
1620
1621            final String packageName = info.activityInfo.packageName;
1622
1623            final PackageSetting ps = mSettings.mPackages.get(packageName);
1624            if (ps == null) {
1625                continue;
1626            }
1627
1628            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1629            if (!gp.grantedPermissions
1630                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1631                continue;
1632            }
1633
1634            if (requiredVerifier != null) {
1635                throw new RuntimeException("There can be only one required verifier");
1636            }
1637
1638            requiredVerifier = packageName;
1639        }
1640
1641        return requiredVerifier;
1642    }
1643
1644    @Override
1645    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1646            throws RemoteException {
1647        try {
1648            return super.onTransact(code, data, reply, flags);
1649        } catch (RuntimeException e) {
1650            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1651                Slog.wtf(TAG, "Package Manager Crash", e);
1652            }
1653            throw e;
1654        }
1655    }
1656
1657    void cleanupInstallFailedPackage(PackageSetting ps) {
1658        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1659        removeDataDirsLI(ps.name);
1660        if (ps.codePath != null) {
1661            if (!ps.codePath.delete()) {
1662                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1663            }
1664        }
1665        if (ps.resourcePath != null) {
1666            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1667                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1668            }
1669        }
1670        mSettings.removePackageLPw(ps.name);
1671    }
1672
1673    void readPermissions(File libraryDir, boolean onlyFeatures) {
1674        // Read permissions from .../etc/permission directory.
1675        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1676            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1677            return;
1678        }
1679        if (!libraryDir.canRead()) {
1680            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1681            return;
1682        }
1683
1684        // Iterate over the files in the directory and scan .xml files
1685        for (File f : libraryDir.listFiles()) {
1686            // We'll read platform.xml last
1687            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1688                continue;
1689            }
1690
1691            if (!f.getPath().endsWith(".xml")) {
1692                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1693                continue;
1694            }
1695            if (!f.canRead()) {
1696                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1697                continue;
1698            }
1699
1700            readPermissionsFromXml(f, onlyFeatures);
1701        }
1702
1703        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1704        final File permFile = new File(Environment.getRootDirectory(),
1705                "etc/permissions/platform.xml");
1706        readPermissionsFromXml(permFile, onlyFeatures);
1707    }
1708
1709    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1710        FileReader permReader = null;
1711        try {
1712            permReader = new FileReader(permFile);
1713        } catch (FileNotFoundException e) {
1714            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1715            return;
1716        }
1717
1718        try {
1719            XmlPullParser parser = Xml.newPullParser();
1720            parser.setInput(permReader);
1721
1722            XmlUtils.beginDocument(parser, "permissions");
1723
1724            while (true) {
1725                XmlUtils.nextElement(parser);
1726                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1727                    break;
1728                }
1729
1730                String name = parser.getName();
1731                if ("group".equals(name) && !onlyFeatures) {
1732                    String gidStr = parser.getAttributeValue(null, "gid");
1733                    if (gidStr != null) {
1734                        int gid = Process.getGidForName(gidStr);
1735                        mGlobalGids = appendInt(mGlobalGids, gid);
1736                    } else {
1737                        Slog.w(TAG, "<group> without gid at "
1738                                + parser.getPositionDescription());
1739                    }
1740
1741                    XmlUtils.skipCurrentTag(parser);
1742                    continue;
1743                } else if ("permission".equals(name) && !onlyFeatures) {
1744                    String perm = parser.getAttributeValue(null, "name");
1745                    if (perm == null) {
1746                        Slog.w(TAG, "<permission> without name at "
1747                                + parser.getPositionDescription());
1748                        XmlUtils.skipCurrentTag(parser);
1749                        continue;
1750                    }
1751                    perm = perm.intern();
1752                    readPermission(parser, perm);
1753
1754                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1755                    String perm = parser.getAttributeValue(null, "name");
1756                    if (perm == null) {
1757                        Slog.w(TAG, "<assign-permission> without name at "
1758                                + parser.getPositionDescription());
1759                        XmlUtils.skipCurrentTag(parser);
1760                        continue;
1761                    }
1762                    String uidStr = parser.getAttributeValue(null, "uid");
1763                    if (uidStr == null) {
1764                        Slog.w(TAG, "<assign-permission> without uid at "
1765                                + parser.getPositionDescription());
1766                        XmlUtils.skipCurrentTag(parser);
1767                        continue;
1768                    }
1769                    int uid = Process.getUidForName(uidStr);
1770                    if (uid < 0) {
1771                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1772                                + uidStr + "\" at "
1773                                + parser.getPositionDescription());
1774                        XmlUtils.skipCurrentTag(parser);
1775                        continue;
1776                    }
1777                    perm = perm.intern();
1778                    HashSet<String> perms = mSystemPermissions.get(uid);
1779                    if (perms == null) {
1780                        perms = new HashSet<String>();
1781                        mSystemPermissions.put(uid, perms);
1782                    }
1783                    perms.add(perm);
1784                    XmlUtils.skipCurrentTag(parser);
1785
1786                } else if ("library".equals(name) && !onlyFeatures) {
1787                    String lname = parser.getAttributeValue(null, "name");
1788                    String lfile = parser.getAttributeValue(null, "file");
1789                    if (lname == null) {
1790                        Slog.w(TAG, "<library> without name at "
1791                                + parser.getPositionDescription());
1792                    } else if (lfile == null) {
1793                        Slog.w(TAG, "<library> without file at "
1794                                + parser.getPositionDescription());
1795                    } else {
1796                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1797                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1798                    }
1799                    XmlUtils.skipCurrentTag(parser);
1800                    continue;
1801
1802                } else if ("feature".equals(name)) {
1803                    String fname = parser.getAttributeValue(null, "name");
1804                    if (fname == null) {
1805                        Slog.w(TAG, "<feature> without name at "
1806                                + parser.getPositionDescription());
1807                    } else {
1808                        //Log.i(TAG, "Got feature " + fname);
1809                        FeatureInfo fi = new FeatureInfo();
1810                        fi.name = fname;
1811                        mAvailableFeatures.put(fname, fi);
1812                    }
1813                    XmlUtils.skipCurrentTag(parser);
1814                    continue;
1815
1816                } else {
1817                    XmlUtils.skipCurrentTag(parser);
1818                    continue;
1819                }
1820
1821            }
1822            permReader.close();
1823        } catch (XmlPullParserException e) {
1824            Slog.w(TAG, "Got execption parsing permissions.", e);
1825        } catch (IOException e) {
1826            Slog.w(TAG, "Got execption parsing permissions.", e);
1827        }
1828    }
1829
1830    void readPermission(XmlPullParser parser, String name)
1831            throws IOException, XmlPullParserException {
1832
1833        name = name.intern();
1834
1835        BasePermission bp = mSettings.mPermissions.get(name);
1836        if (bp == null) {
1837            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1838            mSettings.mPermissions.put(name, bp);
1839        }
1840        int outerDepth = parser.getDepth();
1841        int type;
1842        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1843               && (type != XmlPullParser.END_TAG
1844                       || parser.getDepth() > outerDepth)) {
1845            if (type == XmlPullParser.END_TAG
1846                    || type == XmlPullParser.TEXT) {
1847                continue;
1848            }
1849
1850            String tagName = parser.getName();
1851            if ("group".equals(tagName)) {
1852                String gidStr = parser.getAttributeValue(null, "gid");
1853                if (gidStr != null) {
1854                    int gid = Process.getGidForName(gidStr);
1855                    bp.gids = appendInt(bp.gids, gid);
1856                } else {
1857                    Slog.w(TAG, "<group> without gid at "
1858                            + parser.getPositionDescription());
1859                }
1860            }
1861            XmlUtils.skipCurrentTag(parser);
1862        }
1863    }
1864
1865    static int[] appendInts(int[] cur, int[] add) {
1866        if (add == null) return cur;
1867        if (cur == null) return add;
1868        final int N = add.length;
1869        for (int i=0; i<N; i++) {
1870            cur = appendInt(cur, add[i]);
1871        }
1872        return cur;
1873    }
1874
1875    static int[] removeInts(int[] cur, int[] rem) {
1876        if (rem == null) return cur;
1877        if (cur == null) return cur;
1878        final int N = rem.length;
1879        for (int i=0; i<N; i++) {
1880            cur = removeInt(cur, rem[i]);
1881        }
1882        return cur;
1883    }
1884
1885    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1886        if (!sUserManager.exists(userId)) return null;
1887        final PackageSetting ps = (PackageSetting) p.mExtras;
1888        if (ps == null) {
1889            return null;
1890        }
1891        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1892        final PackageUserState state = ps.readUserState(userId);
1893        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1894                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1895                state, userId);
1896    }
1897
1898    public boolean isPackageAvailable(String packageName, int userId) {
1899        if (!sUserManager.exists(userId)) return false;
1900        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1901        synchronized (mPackages) {
1902            PackageParser.Package p = mPackages.get(packageName);
1903            if (p != null) {
1904                final PackageSetting ps = (PackageSetting) p.mExtras;
1905                if (ps != null) {
1906                    final PackageUserState state = ps.readUserState(userId);
1907                    if (state != null) {
1908                        return PackageParser.isAvailable(state);
1909                    }
1910                }
1911            }
1912        }
1913        return false;
1914    }
1915
1916    @Override
1917    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1918        if (!sUserManager.exists(userId)) return null;
1919        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1920        // reader
1921        synchronized (mPackages) {
1922            PackageParser.Package p = mPackages.get(packageName);
1923            if (DEBUG_PACKAGE_INFO)
1924                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1925            if (p != null) {
1926                return generatePackageInfo(p, flags, userId);
1927            }
1928            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1929                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1930            }
1931        }
1932        return null;
1933    }
1934
1935    public String[] currentToCanonicalPackageNames(String[] names) {
1936        String[] out = new String[names.length];
1937        // reader
1938        synchronized (mPackages) {
1939            for (int i=names.length-1; i>=0; i--) {
1940                PackageSetting ps = mSettings.mPackages.get(names[i]);
1941                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1942            }
1943        }
1944        return out;
1945    }
1946
1947    public String[] canonicalToCurrentPackageNames(String[] names) {
1948        String[] out = new String[names.length];
1949        // reader
1950        synchronized (mPackages) {
1951            for (int i=names.length-1; i>=0; i--) {
1952                String cur = mSettings.mRenamedPackages.get(names[i]);
1953                out[i] = cur != null ? cur : names[i];
1954            }
1955        }
1956        return out;
1957    }
1958
1959    @Override
1960    public int getPackageUid(String packageName, int userId) {
1961        if (!sUserManager.exists(userId)) return -1;
1962        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1963        // reader
1964        synchronized (mPackages) {
1965            PackageParser.Package p = mPackages.get(packageName);
1966            if(p != null) {
1967                return UserHandle.getUid(userId, p.applicationInfo.uid);
1968            }
1969            PackageSetting ps = mSettings.mPackages.get(packageName);
1970            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1971                return -1;
1972            }
1973            p = ps.pkg;
1974            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1975        }
1976    }
1977
1978    @Override
1979    public int[] getPackageGids(String packageName) {
1980        // reader
1981        synchronized (mPackages) {
1982            PackageParser.Package p = mPackages.get(packageName);
1983            if (DEBUG_PACKAGE_INFO)
1984                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1985            if (p != null) {
1986                final PackageSetting ps = (PackageSetting)p.mExtras;
1987                return ps.getGids();
1988            }
1989        }
1990        // stupid thing to indicate an error.
1991        return new int[0];
1992    }
1993
1994    static final PermissionInfo generatePermissionInfo(
1995            BasePermission bp, int flags) {
1996        if (bp.perm != null) {
1997            return PackageParser.generatePermissionInfo(bp.perm, flags);
1998        }
1999        PermissionInfo pi = new PermissionInfo();
2000        pi.name = bp.name;
2001        pi.packageName = bp.sourcePackage;
2002        pi.nonLocalizedLabel = bp.name;
2003        pi.protectionLevel = bp.protectionLevel;
2004        return pi;
2005    }
2006
2007    public PermissionInfo getPermissionInfo(String name, int flags) {
2008        // reader
2009        synchronized (mPackages) {
2010            final BasePermission p = mSettings.mPermissions.get(name);
2011            if (p != null) {
2012                return generatePermissionInfo(p, flags);
2013            }
2014            return null;
2015        }
2016    }
2017
2018    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2019        // reader
2020        synchronized (mPackages) {
2021            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2022            for (BasePermission p : mSettings.mPermissions.values()) {
2023                if (group == null) {
2024                    if (p.perm == null || p.perm.info.group == null) {
2025                        out.add(generatePermissionInfo(p, flags));
2026                    }
2027                } else {
2028                    if (p.perm != null && group.equals(p.perm.info.group)) {
2029                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2030                    }
2031                }
2032            }
2033
2034            if (out.size() > 0) {
2035                return out;
2036            }
2037            return mPermissionGroups.containsKey(group) ? out : null;
2038        }
2039    }
2040
2041    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2042        // reader
2043        synchronized (mPackages) {
2044            return PackageParser.generatePermissionGroupInfo(
2045                    mPermissionGroups.get(name), flags);
2046        }
2047    }
2048
2049    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2050        // reader
2051        synchronized (mPackages) {
2052            final int N = mPermissionGroups.size();
2053            ArrayList<PermissionGroupInfo> out
2054                    = new ArrayList<PermissionGroupInfo>(N);
2055            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2056                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2057            }
2058            return out;
2059        }
2060    }
2061
2062    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2063            int userId) {
2064        if (!sUserManager.exists(userId)) return null;
2065        PackageSetting ps = mSettings.mPackages.get(packageName);
2066        if (ps != null) {
2067            if (ps.pkg == null) {
2068                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2069                        flags, userId);
2070                if (pInfo != null) {
2071                    return pInfo.applicationInfo;
2072                }
2073                return null;
2074            }
2075            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2076                    ps.readUserState(userId), userId);
2077        }
2078        return null;
2079    }
2080
2081    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2082            int userId) {
2083        if (!sUserManager.exists(userId)) return null;
2084        PackageSetting ps = mSettings.mPackages.get(packageName);
2085        if (ps != null) {
2086            PackageParser.Package pkg = ps.pkg;
2087            if (pkg == null) {
2088                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2089                    return null;
2090                }
2091                pkg = new PackageParser.Package(packageName);
2092                pkg.applicationInfo.packageName = packageName;
2093                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2094                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2095                pkg.applicationInfo.sourceDir = ps.codePathString;
2096                pkg.applicationInfo.dataDir =
2097                        getDataPathForPackage(packageName, 0).getPath();
2098                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2099                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2100            }
2101            return generatePackageInfo(pkg, flags, userId);
2102        }
2103        return null;
2104    }
2105
2106    @Override
2107    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2108        if (!sUserManager.exists(userId)) return null;
2109        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2110        // writer
2111        synchronized (mPackages) {
2112            PackageParser.Package p = mPackages.get(packageName);
2113            if (DEBUG_PACKAGE_INFO) Log.v(
2114                    TAG, "getApplicationInfo " + packageName
2115                    + ": " + p);
2116            if (p != null) {
2117                PackageSetting ps = mSettings.mPackages.get(packageName);
2118                if (ps == null) return null;
2119                // Note: isEnabledLP() does not apply here - always return info
2120                return PackageParser.generateApplicationInfo(
2121                        p, flags, ps.readUserState(userId), userId);
2122            }
2123            if ("android".equals(packageName)||"system".equals(packageName)) {
2124                return mAndroidApplication;
2125            }
2126            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2127                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2128            }
2129        }
2130        return null;
2131    }
2132
2133
2134    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2135        mContext.enforceCallingOrSelfPermission(
2136                android.Manifest.permission.CLEAR_APP_CACHE, null);
2137        // Queue up an async operation since clearing cache may take a little while.
2138        mHandler.post(new Runnable() {
2139            public void run() {
2140                mHandler.removeCallbacks(this);
2141                int retCode = -1;
2142                synchronized (mInstallLock) {
2143                    retCode = mInstaller.freeCache(freeStorageSize);
2144                    if (retCode < 0) {
2145                        Slog.w(TAG, "Couldn't clear application caches");
2146                    }
2147                }
2148                if (observer != null) {
2149                    try {
2150                        observer.onRemoveCompleted(null, (retCode >= 0));
2151                    } catch (RemoteException e) {
2152                        Slog.w(TAG, "RemoveException when invoking call back");
2153                    }
2154                }
2155            }
2156        });
2157    }
2158
2159    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2160        mContext.enforceCallingOrSelfPermission(
2161                android.Manifest.permission.CLEAR_APP_CACHE, null);
2162        // Queue up an async operation since clearing cache may take a little while.
2163        mHandler.post(new Runnable() {
2164            public void run() {
2165                mHandler.removeCallbacks(this);
2166                int retCode = -1;
2167                synchronized (mInstallLock) {
2168                    retCode = mInstaller.freeCache(freeStorageSize);
2169                    if (retCode < 0) {
2170                        Slog.w(TAG, "Couldn't clear application caches");
2171                    }
2172                }
2173                if(pi != null) {
2174                    try {
2175                        // Callback via pending intent
2176                        int code = (retCode >= 0) ? 1 : 0;
2177                        pi.sendIntent(null, code, null,
2178                                null, null);
2179                    } catch (SendIntentException e1) {
2180                        Slog.i(TAG, "Failed to send pending intent");
2181                    }
2182                }
2183            }
2184        });
2185    }
2186
2187    @Override
2188    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2189        if (!sUserManager.exists(userId)) return null;
2190        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2191        synchronized (mPackages) {
2192            PackageParser.Activity a = mActivities.mActivities.get(component);
2193
2194            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2195            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2196                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2197                if (ps == null) return null;
2198                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2199                        userId);
2200            }
2201            if (mResolveComponentName.equals(component)) {
2202                return mResolveActivity;
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2210            String resolvedType) {
2211        synchronized (mPackages) {
2212            PackageParser.Activity a = mActivities.mActivities.get(component);
2213            if (a == null) {
2214                return false;
2215            }
2216            for (int i=0; i<a.intents.size(); i++) {
2217                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2218                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2219                    return true;
2220                }
2221            }
2222            return false;
2223        }
2224    }
2225
2226    @Override
2227    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2230        synchronized (mPackages) {
2231            PackageParser.Activity a = mReceivers.mActivities.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getReceiverInfo " + component + ": " + a);
2234            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2246        if (!sUserManager.exists(userId)) return null;
2247        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2248        synchronized (mPackages) {
2249            PackageParser.Service s = mServices.mServices.get(component);
2250            if (DEBUG_PACKAGE_INFO) Log.v(
2251                TAG, "getServiceInfo " + component + ": " + s);
2252            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2253                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2254                if (ps == null) return null;
2255                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2256                        userId);
2257            }
2258        }
2259        return null;
2260    }
2261
2262    @Override
2263    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2264        if (!sUserManager.exists(userId)) return null;
2265        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2266        synchronized (mPackages) {
2267            PackageParser.Provider p = mProviders.mProviders.get(component);
2268            if (DEBUG_PACKAGE_INFO) Log.v(
2269                TAG, "getProviderInfo " + component + ": " + p);
2270            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2271                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2272                if (ps == null) return null;
2273                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2274                        userId);
2275            }
2276        }
2277        return null;
2278    }
2279
2280    public String[] getSystemSharedLibraryNames() {
2281        Set<String> libSet;
2282        synchronized (mPackages) {
2283            libSet = mSharedLibraries.keySet();
2284            int size = libSet.size();
2285            if (size > 0) {
2286                String[] libs = new String[size];
2287                libSet.toArray(libs);
2288                return libs;
2289            }
2290        }
2291        return null;
2292    }
2293
2294    public FeatureInfo[] getSystemAvailableFeatures() {
2295        Collection<FeatureInfo> featSet;
2296        synchronized (mPackages) {
2297            featSet = mAvailableFeatures.values();
2298            int size = featSet.size();
2299            if (size > 0) {
2300                FeatureInfo[] features = new FeatureInfo[size+1];
2301                featSet.toArray(features);
2302                FeatureInfo fi = new FeatureInfo();
2303                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2304                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2305                features[size] = fi;
2306                return features;
2307            }
2308        }
2309        return null;
2310    }
2311
2312    public boolean hasSystemFeature(String name) {
2313        synchronized (mPackages) {
2314            return mAvailableFeatures.containsKey(name);
2315        }
2316    }
2317
2318    private void checkValidCaller(int uid, int userId) {
2319        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2320            return;
2321
2322        throw new SecurityException("Caller uid=" + uid
2323                + " is not privileged to communicate with user=" + userId);
2324    }
2325
2326    public int checkPermission(String permName, String pkgName) {
2327        synchronized (mPackages) {
2328            PackageParser.Package p = mPackages.get(pkgName);
2329            if (p != null && p.mExtras != null) {
2330                PackageSetting ps = (PackageSetting)p.mExtras;
2331                if (ps.sharedUser != null) {
2332                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2333                        return PackageManager.PERMISSION_GRANTED;
2334                    }
2335                } else if (ps.grantedPermissions.contains(permName)) {
2336                    return PackageManager.PERMISSION_GRANTED;
2337                }
2338            }
2339        }
2340        return PackageManager.PERMISSION_DENIED;
2341    }
2342
2343    public int checkUidPermission(String permName, int uid) {
2344        synchronized (mPackages) {
2345            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2346            if (obj != null) {
2347                GrantedPermissions gp = (GrantedPermissions)obj;
2348                if (gp.grantedPermissions.contains(permName)) {
2349                    return PackageManager.PERMISSION_GRANTED;
2350                }
2351            } else {
2352                HashSet<String> perms = mSystemPermissions.get(uid);
2353                if (perms != null && perms.contains(permName)) {
2354                    return PackageManager.PERMISSION_GRANTED;
2355                }
2356            }
2357        }
2358        return PackageManager.PERMISSION_DENIED;
2359    }
2360
2361    /**
2362     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2363     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2364     * @param message the message to log on security exception
2365     * @return
2366     */
2367    private void enforceCrossUserPermission(int callingUid, int userId,
2368            boolean requireFullPermission, String message) {
2369        if (userId < 0) {
2370            throw new IllegalArgumentException("Invalid userId " + userId);
2371        }
2372        if (userId == UserHandle.getUserId(callingUid)) return;
2373        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2374            if (requireFullPermission) {
2375                mContext.enforceCallingOrSelfPermission(
2376                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2377            } else {
2378                try {
2379                    mContext.enforceCallingOrSelfPermission(
2380                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2381                } catch (SecurityException se) {
2382                    mContext.enforceCallingOrSelfPermission(
2383                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2384                }
2385            }
2386        }
2387    }
2388
2389    private BasePermission findPermissionTreeLP(String permName) {
2390        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2391            if (permName.startsWith(bp.name) &&
2392                    permName.length() > bp.name.length() &&
2393                    permName.charAt(bp.name.length()) == '.') {
2394                return bp;
2395            }
2396        }
2397        return null;
2398    }
2399
2400    private BasePermission checkPermissionTreeLP(String permName) {
2401        if (permName != null) {
2402            BasePermission bp = findPermissionTreeLP(permName);
2403            if (bp != null) {
2404                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2405                    return bp;
2406                }
2407                throw new SecurityException("Calling uid "
2408                        + Binder.getCallingUid()
2409                        + " is not allowed to add to permission tree "
2410                        + bp.name + " owned by uid " + bp.uid);
2411            }
2412        }
2413        throw new SecurityException("No permission tree found for " + permName);
2414    }
2415
2416    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2417        if (s1 == null) {
2418            return s2 == null;
2419        }
2420        if (s2 == null) {
2421            return false;
2422        }
2423        if (s1.getClass() != s2.getClass()) {
2424            return false;
2425        }
2426        return s1.equals(s2);
2427    }
2428
2429    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2430        if (pi1.icon != pi2.icon) return false;
2431        if (pi1.logo != pi2.logo) return false;
2432        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2433        if (!compareStrings(pi1.name, pi2.name)) return false;
2434        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2435        // We'll take care of setting this one.
2436        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2437        // These are not currently stored in settings.
2438        //if (!compareStrings(pi1.group, pi2.group)) return false;
2439        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2440        //if (pi1.labelRes != pi2.labelRes) return false;
2441        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2442        return true;
2443    }
2444
2445    int permissionInfoFootprint(PermissionInfo info) {
2446        int size = info.name.length();
2447        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2448        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2449        return size;
2450    }
2451
2452    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2453        int size = 0;
2454        for (BasePermission perm : mSettings.mPermissions.values()) {
2455            if (perm.uid == tree.uid) {
2456                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2457            }
2458        }
2459        return size;
2460    }
2461
2462    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2463        // We calculate the max size of permissions defined by this uid and throw
2464        // if that plus the size of 'info' would exceed our stated maximum.
2465        if (tree.uid != Process.SYSTEM_UID) {
2466            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2467            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2468                throw new SecurityException("Permission tree size cap exceeded");
2469            }
2470        }
2471    }
2472
2473    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2474        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2475            throw new SecurityException("Label must be specified in permission");
2476        }
2477        BasePermission tree = checkPermissionTreeLP(info.name);
2478        BasePermission bp = mSettings.mPermissions.get(info.name);
2479        boolean added = bp == null;
2480        boolean changed = true;
2481        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2482        if (added) {
2483            enforcePermissionCapLocked(info, tree);
2484            bp = new BasePermission(info.name, tree.sourcePackage,
2485                    BasePermission.TYPE_DYNAMIC);
2486        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2487            throw new SecurityException(
2488                    "Not allowed to modify non-dynamic permission "
2489                    + info.name);
2490        } else {
2491            if (bp.protectionLevel == fixedLevel
2492                    && bp.perm.owner.equals(tree.perm.owner)
2493                    && bp.uid == tree.uid
2494                    && comparePermissionInfos(bp.perm.info, info)) {
2495                changed = false;
2496            }
2497        }
2498        bp.protectionLevel = fixedLevel;
2499        info = new PermissionInfo(info);
2500        info.protectionLevel = fixedLevel;
2501        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2502        bp.perm.info.packageName = tree.perm.info.packageName;
2503        bp.uid = tree.uid;
2504        if (added) {
2505            mSettings.mPermissions.put(info.name, bp);
2506        }
2507        if (changed) {
2508            if (!async) {
2509                mSettings.writeLPr();
2510            } else {
2511                scheduleWriteSettingsLocked();
2512            }
2513        }
2514        return added;
2515    }
2516
2517    public boolean addPermission(PermissionInfo info) {
2518        synchronized (mPackages) {
2519            return addPermissionLocked(info, false);
2520        }
2521    }
2522
2523    public boolean addPermissionAsync(PermissionInfo info) {
2524        synchronized (mPackages) {
2525            return addPermissionLocked(info, true);
2526        }
2527    }
2528
2529    public void removePermission(String name) {
2530        synchronized (mPackages) {
2531            checkPermissionTreeLP(name);
2532            BasePermission bp = mSettings.mPermissions.get(name);
2533            if (bp != null) {
2534                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2535                    throw new SecurityException(
2536                            "Not allowed to modify non-dynamic permission "
2537                            + name);
2538                }
2539                mSettings.mPermissions.remove(name);
2540                mSettings.writeLPr();
2541            }
2542        }
2543    }
2544
2545    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2546        int index = pkg.requestedPermissions.indexOf(bp.name);
2547        if (index == -1) {
2548            throw new SecurityException("Package " + pkg.packageName
2549                    + " has not requested permission " + bp.name);
2550        }
2551        boolean isNormal =
2552                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2553                        == PermissionInfo.PROTECTION_NORMAL);
2554        boolean isDangerous =
2555                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2556                        == PermissionInfo.PROTECTION_DANGEROUS);
2557        boolean isDevelopment =
2558                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2559
2560        if (!isNormal && !isDangerous && !isDevelopment) {
2561            throw new SecurityException("Permission " + bp.name
2562                    + " is not a changeable permission type");
2563        }
2564
2565        if (isNormal || isDangerous) {
2566            if (pkg.requestedPermissionsRequired.get(index)) {
2567                throw new SecurityException("Can't change " + bp.name
2568                        + ". It is required by the application");
2569            }
2570        }
2571    }
2572
2573    public void grantPermission(String packageName, String permissionName) {
2574        mContext.enforceCallingOrSelfPermission(
2575                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2576        synchronized (mPackages) {
2577            final PackageParser.Package pkg = mPackages.get(packageName);
2578            if (pkg == null) {
2579                throw new IllegalArgumentException("Unknown package: " + packageName);
2580            }
2581            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2582            if (bp == null) {
2583                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2584            }
2585
2586            checkGrantRevokePermissions(pkg, bp);
2587
2588            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2589            if (ps == null) {
2590                return;
2591            }
2592            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2593            if (gp.grantedPermissions.add(permissionName)) {
2594                if (ps.haveGids) {
2595                    gp.gids = appendInts(gp.gids, bp.gids);
2596                }
2597                mSettings.writeLPr();
2598            }
2599        }
2600    }
2601
2602    public void revokePermission(String packageName, String permissionName) {
2603        int changedAppId = -1;
2604
2605        synchronized (mPackages) {
2606            final PackageParser.Package pkg = mPackages.get(packageName);
2607            if (pkg == null) {
2608                throw new IllegalArgumentException("Unknown package: " + packageName);
2609            }
2610            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2611                mContext.enforceCallingOrSelfPermission(
2612                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2613            }
2614            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2615            if (bp == null) {
2616                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2617            }
2618
2619            checkGrantRevokePermissions(pkg, bp);
2620
2621            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2622            if (ps == null) {
2623                return;
2624            }
2625            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2626            if (gp.grantedPermissions.remove(permissionName)) {
2627                gp.grantedPermissions.remove(permissionName);
2628                if (ps.haveGids) {
2629                    gp.gids = removeInts(gp.gids, bp.gids);
2630                }
2631                mSettings.writeLPr();
2632                changedAppId = ps.appId;
2633            }
2634        }
2635
2636        if (changedAppId >= 0) {
2637            // We changed the perm on someone, kill its processes.
2638            IActivityManager am = ActivityManagerNative.getDefault();
2639            if (am != null) {
2640                final int callingUserId = UserHandle.getCallingUserId();
2641                final long ident = Binder.clearCallingIdentity();
2642                try {
2643                    //XXX we should only revoke for the calling user's app permissions,
2644                    // but for now we impact all users.
2645                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2646                    //        "revoke " + permissionName);
2647                    int[] users = sUserManager.getUserIds();
2648                    for (int user : users) {
2649                        am.killUid(UserHandle.getUid(user, changedAppId),
2650                                "revoke " + permissionName);
2651                    }
2652                } catch (RemoteException e) {
2653                } finally {
2654                    Binder.restoreCallingIdentity(ident);
2655                }
2656            }
2657        }
2658    }
2659
2660    public boolean isProtectedBroadcast(String actionName) {
2661        synchronized (mPackages) {
2662            return mProtectedBroadcasts.contains(actionName);
2663        }
2664    }
2665
2666    public int checkSignatures(String pkg1, String pkg2) {
2667        synchronized (mPackages) {
2668            final PackageParser.Package p1 = mPackages.get(pkg1);
2669            final PackageParser.Package p2 = mPackages.get(pkg2);
2670            if (p1 == null || p1.mExtras == null
2671                    || p2 == null || p2.mExtras == null) {
2672                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2673            }
2674            return compareSignatures(p1.mSignatures, p2.mSignatures);
2675        }
2676    }
2677
2678    public int checkUidSignatures(int uid1, int uid2) {
2679        // Map to base uids.
2680        uid1 = UserHandle.getAppId(uid1);
2681        uid2 = UserHandle.getAppId(uid2);
2682        // reader
2683        synchronized (mPackages) {
2684            Signature[] s1;
2685            Signature[] s2;
2686            Object obj = mSettings.getUserIdLPr(uid1);
2687            if (obj != null) {
2688                if (obj instanceof SharedUserSetting) {
2689                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2690                } else if (obj instanceof PackageSetting) {
2691                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2692                } else {
2693                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2694                }
2695            } else {
2696                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2697            }
2698            obj = mSettings.getUserIdLPr(uid2);
2699            if (obj != null) {
2700                if (obj instanceof SharedUserSetting) {
2701                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2702                } else if (obj instanceof PackageSetting) {
2703                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2704                } else {
2705                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2706                }
2707            } else {
2708                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2709            }
2710            return compareSignatures(s1, s2);
2711        }
2712    }
2713
2714    /**
2715     * Compares two sets of signatures. Returns:
2716     * <br />
2717     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2718     * <br />
2719     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2720     * <br />
2721     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2722     * <br />
2723     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2724     * <br />
2725     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2726     */
2727    static int compareSignatures(Signature[] s1, Signature[] s2) {
2728        if (s1 == null) {
2729            return s2 == null
2730                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2731                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2732        }
2733
2734        if (s2 == null) {
2735            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2736        }
2737
2738        if (s1.length != s2.length) {
2739            return PackageManager.SIGNATURE_NO_MATCH;
2740        }
2741
2742        // Since both signature sets are of size 1, we can compare without HashSets.
2743        if (s1.length == 1) {
2744            return s1[0].equals(s2[0]) ?
2745                    PackageManager.SIGNATURE_MATCH :
2746                    PackageManager.SIGNATURE_NO_MATCH;
2747        }
2748
2749        HashSet<Signature> set1 = new HashSet<Signature>();
2750        for (Signature sig : s1) {
2751            set1.add(sig);
2752        }
2753        HashSet<Signature> set2 = new HashSet<Signature>();
2754        for (Signature sig : s2) {
2755            set2.add(sig);
2756        }
2757        // Make sure s2 contains all signatures in s1.
2758        if (set1.equals(set2)) {
2759            return PackageManager.SIGNATURE_MATCH;
2760        }
2761        return PackageManager.SIGNATURE_NO_MATCH;
2762    }
2763
2764    /**
2765     * If the database version for this type of package (internal storage or
2766     * external storage) is less than the version where package signatures
2767     * were updated, return true.
2768     */
2769    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2770        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2771                DatabaseVersion.SIGNATURE_END_ENTITY))
2772                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2773                        DatabaseVersion.SIGNATURE_END_ENTITY));
2774    }
2775
2776    /**
2777     * Used for backward compatibility to make sure any packages with
2778     * certificate chains get upgraded to the new style. {@code existingSigs}
2779     * will be in the old format (since they were stored on disk from before the
2780     * system upgrade) and {@code scannedSigs} will be in the newer format.
2781     */
2782    private int compareSignaturesCompat(PackageSignatures existingSigs,
2783            PackageParser.Package scannedPkg) {
2784        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2785            return PackageManager.SIGNATURE_NO_MATCH;
2786        }
2787
2788        HashSet<Signature> existingSet = new HashSet<Signature>();
2789        for (Signature sig : existingSigs.mSignatures) {
2790            existingSet.add(sig);
2791        }
2792        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2793        for (Signature sig : scannedPkg.mSignatures) {
2794            try {
2795                Signature[] chainSignatures = sig.getChainSignatures();
2796                for (Signature chainSig : chainSignatures) {
2797                    scannedCompatSet.add(chainSig);
2798                }
2799            } catch (CertificateEncodingException e) {
2800                scannedCompatSet.add(sig);
2801            }
2802        }
2803        /*
2804         * Make sure the expanded scanned set contains all signatures in the
2805         * existing one.
2806         */
2807        if (scannedCompatSet.equals(existingSet)) {
2808            // Migrate the old signatures to the new scheme.
2809            existingSigs.assignSignatures(scannedPkg.mSignatures);
2810            // The new KeySets will be re-added later in the scanning process.
2811            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2812            return PackageManager.SIGNATURE_MATCH;
2813        }
2814        return PackageManager.SIGNATURE_NO_MATCH;
2815    }
2816
2817    public String[] getPackagesForUid(int uid) {
2818        uid = UserHandle.getAppId(uid);
2819        // reader
2820        synchronized (mPackages) {
2821            Object obj = mSettings.getUserIdLPr(uid);
2822            if (obj instanceof SharedUserSetting) {
2823                final SharedUserSetting sus = (SharedUserSetting) obj;
2824                final int N = sus.packages.size();
2825                final String[] res = new String[N];
2826                final Iterator<PackageSetting> it = sus.packages.iterator();
2827                int i = 0;
2828                while (it.hasNext()) {
2829                    res[i++] = it.next().name;
2830                }
2831                return res;
2832            } else if (obj instanceof PackageSetting) {
2833                final PackageSetting ps = (PackageSetting) obj;
2834                return new String[] { ps.name };
2835            }
2836        }
2837        return null;
2838    }
2839
2840    public String getNameForUid(int uid) {
2841        // reader
2842        synchronized (mPackages) {
2843            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2844            if (obj instanceof SharedUserSetting) {
2845                final SharedUserSetting sus = (SharedUserSetting) obj;
2846                return sus.name + ":" + sus.userId;
2847            } else if (obj instanceof PackageSetting) {
2848                final PackageSetting ps = (PackageSetting) obj;
2849                return ps.name;
2850            }
2851        }
2852        return null;
2853    }
2854
2855    public int getUidForSharedUser(String sharedUserName) {
2856        if(sharedUserName == null) {
2857            return -1;
2858        }
2859        // reader
2860        synchronized (mPackages) {
2861            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2862            if (suid == null) {
2863                return -1;
2864            }
2865            return suid.userId;
2866        }
2867    }
2868
2869    public int getFlagsForUid(int uid) {
2870        synchronized (mPackages) {
2871            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2872            if (obj instanceof SharedUserSetting) {
2873                final SharedUserSetting sus = (SharedUserSetting) obj;
2874                return sus.pkgFlags;
2875            } else if (obj instanceof PackageSetting) {
2876                final PackageSetting ps = (PackageSetting) obj;
2877                return ps.pkgFlags;
2878            }
2879        }
2880        return 0;
2881    }
2882
2883    @Override
2884    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2885            int flags, int userId) {
2886        if (!sUserManager.exists(userId)) return null;
2887        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2888        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2889        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2890    }
2891
2892    @Override
2893    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2894            IntentFilter filter, int match, ComponentName activity) {
2895        final int userId = UserHandle.getCallingUserId();
2896        if (DEBUG_PREFERRED) {
2897            Log.v(TAG, "setLastChosenActivity intent=" + intent
2898                + " resolvedType=" + resolvedType
2899                + " flags=" + flags
2900                + " filter=" + filter
2901                + " match=" + match
2902                + " activity=" + activity);
2903            filter.dump(new PrintStreamPrinter(System.out), "    ");
2904        }
2905        intent.setComponent(null);
2906        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2907        // Find any earlier preferred or last chosen entries and nuke them
2908        findPreferredActivity(intent, resolvedType,
2909                flags, query, 0, false, true, false, userId);
2910        // Add the new activity as the last chosen for this filter
2911        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2912    }
2913
2914    @Override
2915    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2916        final int userId = UserHandle.getCallingUserId();
2917        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2918        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2919        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2920                false, false, false, userId);
2921    }
2922
2923    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2924            int flags, List<ResolveInfo> query, int userId) {
2925        if (query != null) {
2926            final int N = query.size();
2927            if (N == 1) {
2928                return query.get(0);
2929            } else if (N > 1) {
2930                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2931                // If there is more than one activity with the same priority,
2932                // then let the user decide between them.
2933                ResolveInfo r0 = query.get(0);
2934                ResolveInfo r1 = query.get(1);
2935                if (DEBUG_INTENT_MATCHING || debug) {
2936                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2937                            + r1.activityInfo.name + "=" + r1.priority);
2938                }
2939                // If the first activity has a higher priority, or a different
2940                // default, then it is always desireable to pick it.
2941                if (r0.priority != r1.priority
2942                        || r0.preferredOrder != r1.preferredOrder
2943                        || r0.isDefault != r1.isDefault) {
2944                    return query.get(0);
2945                }
2946                // If we have saved a preference for a preferred activity for
2947                // this Intent, use that.
2948                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2949                        flags, query, r0.priority, true, false, debug, userId);
2950                if (ri != null) {
2951                    return ri;
2952                }
2953                if (userId != 0) {
2954                    ri = new ResolveInfo(mResolveInfo);
2955                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2956                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2957                            ri.activityInfo.applicationInfo);
2958                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2959                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2960                    return ri;
2961                }
2962                return mResolveInfo;
2963            }
2964        }
2965        return null;
2966    }
2967
2968    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2969            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2970        final int N = query.size();
2971        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2972                .get(userId);
2973        // Get the list of persistent preferred activities that handle the intent
2974        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2975        List<PersistentPreferredActivity> pprefs = ppir != null
2976                ? ppir.queryIntent(intent, resolvedType,
2977                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2978                : null;
2979        if (pprefs != null && pprefs.size() > 0) {
2980            final int M = pprefs.size();
2981            for (int i=0; i<M; i++) {
2982                final PersistentPreferredActivity ppa = pprefs.get(i);
2983                if (DEBUG_PREFERRED || debug) {
2984                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2985                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2986                            + "\n  component=" + ppa.mComponent);
2987                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2988                }
2989                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2990                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2991                if (DEBUG_PREFERRED || debug) {
2992                    Slog.v(TAG, "Found persistent preferred activity:");
2993                    if (ai != null) {
2994                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2995                    } else {
2996                        Slog.v(TAG, "  null");
2997                    }
2998                }
2999                if (ai == null) {
3000                    // This previously registered persistent preferred activity
3001                    // component is no longer known. Ignore it and do NOT remove it.
3002                    continue;
3003                }
3004                for (int j=0; j<N; j++) {
3005                    final ResolveInfo ri = query.get(j);
3006                    if (!ri.activityInfo.applicationInfo.packageName
3007                            .equals(ai.applicationInfo.packageName)) {
3008                        continue;
3009                    }
3010                    if (!ri.activityInfo.name.equals(ai.name)) {
3011                        continue;
3012                    }
3013                    //  Found a persistent preference that can handle the intent.
3014                    if (DEBUG_PREFERRED || debug) {
3015                        Slog.v(TAG, "Returning persistent preferred activity: " +
3016                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3017                    }
3018                    return ri;
3019                }
3020            }
3021        }
3022        return null;
3023    }
3024
3025    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3026            List<ResolveInfo> query, int priority, boolean always,
3027            boolean removeMatches, boolean debug, int userId) {
3028        if (!sUserManager.exists(userId)) return null;
3029        // writer
3030        synchronized (mPackages) {
3031            if (intent.getSelector() != null) {
3032                intent = intent.getSelector();
3033            }
3034            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3035
3036            // Try to find a matching persistent preferred activity.
3037            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3038                    debug, userId);
3039
3040            // If a persistent preferred activity matched, use it.
3041            if (pri != null) {
3042                return pri;
3043            }
3044
3045            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3046            // Get the list of preferred activities that handle the intent
3047            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3048            List<PreferredActivity> prefs = pir != null
3049                    ? pir.queryIntent(intent, resolvedType,
3050                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3051                    : null;
3052            if (prefs != null && prefs.size() > 0) {
3053                // First figure out how good the original match set is.
3054                // We will only allow preferred activities that came
3055                // from the same match quality.
3056                int match = 0;
3057
3058                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3059
3060                final int N = query.size();
3061                for (int j=0; j<N; j++) {
3062                    final ResolveInfo ri = query.get(j);
3063                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3064                            + ": 0x" + Integer.toHexString(match));
3065                    if (ri.match > match) {
3066                        match = ri.match;
3067                    }
3068                }
3069
3070                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3071                        + Integer.toHexString(match));
3072
3073                match &= IntentFilter.MATCH_CATEGORY_MASK;
3074                final int M = prefs.size();
3075                for (int i=0; i<M; i++) {
3076                    final PreferredActivity pa = prefs.get(i);
3077                    if (DEBUG_PREFERRED || debug) {
3078                        Slog.v(TAG, "Checking PreferredActivity ds="
3079                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3080                                + "\n  component=" + pa.mPref.mComponent);
3081                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3082                    }
3083                    if (pa.mPref.mMatch != match) {
3084                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3085                                + Integer.toHexString(pa.mPref.mMatch));
3086                        continue;
3087                    }
3088                    // If it's not an "always" type preferred activity and that's what we're
3089                    // looking for, skip it.
3090                    if (always && !pa.mPref.mAlways) {
3091                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3092                        continue;
3093                    }
3094                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3095                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3096                    if (DEBUG_PREFERRED || debug) {
3097                        Slog.v(TAG, "Found preferred activity:");
3098                        if (ai != null) {
3099                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3100                        } else {
3101                            Slog.v(TAG, "  null");
3102                        }
3103                    }
3104                    if (ai == null) {
3105                        // This previously registered preferred activity
3106                        // component is no longer known.  Most likely an update
3107                        // to the app was installed and in the new version this
3108                        // component no longer exists.  Clean it up by removing
3109                        // it from the preferred activities list, and skip it.
3110                        Slog.w(TAG, "Removing dangling preferred activity: "
3111                                + pa.mPref.mComponent);
3112                        pir.removeFilter(pa);
3113                        continue;
3114                    }
3115                    for (int j=0; j<N; j++) {
3116                        final ResolveInfo ri = query.get(j);
3117                        if (!ri.activityInfo.applicationInfo.packageName
3118                                .equals(ai.applicationInfo.packageName)) {
3119                            continue;
3120                        }
3121                        if (!ri.activityInfo.name.equals(ai.name)) {
3122                            continue;
3123                        }
3124
3125                        if (removeMatches) {
3126                            pir.removeFilter(pa);
3127                            if (DEBUG_PREFERRED) {
3128                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3129                            }
3130                            break;
3131                        }
3132
3133                        // Okay we found a previously set preferred or last chosen app.
3134                        // If the result set is different from when this
3135                        // was created, we need to clear it and re-ask the
3136                        // user their preference, if we're looking for an "always" type entry.
3137                        if (always && !pa.mPref.sameSet(query, priority)) {
3138                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3139                                    + intent + " type " + resolvedType);
3140                            if (DEBUG_PREFERRED) {
3141                                Slog.v(TAG, "Removing preferred activity since set changed "
3142                                        + pa.mPref.mComponent);
3143                            }
3144                            pir.removeFilter(pa);
3145                            // Re-add the filter as a "last chosen" entry (!always)
3146                            PreferredActivity lastChosen = new PreferredActivity(
3147                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3148                            pir.addFilter(lastChosen);
3149                            mSettings.writePackageRestrictionsLPr(userId);
3150                            return null;
3151                        }
3152
3153                        // Yay! Either the set matched or we're looking for the last chosen
3154                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3155                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3156                        mSettings.writePackageRestrictionsLPr(userId);
3157                        return ri;
3158                    }
3159                }
3160            }
3161            mSettings.writePackageRestrictionsLPr(userId);
3162        }
3163        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3164        return null;
3165    }
3166
3167    /*
3168     * Returns if intent can be forwarded from the userId from to dest
3169     */
3170    @Override
3171    public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) {
3172        mContext.enforceCallingOrSelfPermission(
3173                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3174        List<ForwardingIntentFilter> matches =
3175                getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom);
3176        if (matches != null) {
3177            int size = matches.size();
3178            for (int i = 0; i < size; i++) {
3179                if (matches.get(i).getUserIdDest() == userIdDest) return true;
3180            }
3181        }
3182        return false;
3183    }
3184
3185    private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent,
3186            String resolvedType, int userId) {
3187        ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId);
3188        if (fir != null) {
3189            return fir.queryIntent(intent, resolvedType, false, userId);
3190        }
3191        return null;
3192    }
3193
3194    @Override
3195    public List<ResolveInfo> queryIntentActivities(Intent intent,
3196            String resolvedType, int flags, int userId) {
3197        if (!sUserManager.exists(userId)) return Collections.emptyList();
3198        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3199        ComponentName comp = intent.getComponent();
3200        if (comp == null) {
3201            if (intent.getSelector() != null) {
3202                intent = intent.getSelector();
3203                comp = intent.getComponent();
3204            }
3205        }
3206
3207        if (comp != null) {
3208            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3209            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3210            if (ai != null) {
3211                final ResolveInfo ri = new ResolveInfo();
3212                ri.activityInfo = ai;
3213                list.add(ri);
3214            }
3215            return list;
3216        }
3217
3218        // reader
3219        synchronized (mPackages) {
3220            final String pkgName = intent.getPackage();
3221            if (pkgName == null) {
3222                List<ResolveInfo> result =
3223                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3224                // Checking if we can forward the intent to another user
3225                List<ForwardingIntentFilter> fifs =
3226                        getMatchingForwardingIntentFilters(intent, resolvedType, userId);
3227                if (fifs != null) {
3228                    ForwardingIntentFilter forwardingIntentFilterWithResult = null;
3229                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3230                    for (ForwardingIntentFilter fif : fifs) {
3231                        int userIdDest = fif.getUserIdDest();
3232                        // Two {@link ForwardingIntentFilter}s can have the same userIdDest and
3233                        // match the same an intent. For performance reasons, it is better not to
3234                        // run queryIntent twice for the same userId
3235                        if (!alreadyTriedUserIds.contains(userIdDest)) {
3236                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3237                                    resolvedType, flags, userIdDest);
3238                            if (resultUser != null) {
3239                                forwardingIntentFilterWithResult = fif;
3240                                // As soon as there is a match in another user, we add the
3241                                // intentForwarderActivity to the list of ResolveInfo.
3242                                break;
3243                            }
3244                            alreadyTriedUserIds.add(userIdDest);
3245                        }
3246                    }
3247                    if (forwardingIntentFilterWithResult != null) {
3248                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3249                                forwardingIntentFilterWithResult, userId);
3250                        result.add(forwardingResolveInfo);
3251                    }
3252                }
3253                return result;
3254            }
3255            final PackageParser.Package pkg = mPackages.get(pkgName);
3256            if (pkg != null) {
3257                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3258                        pkg.activities, userId);
3259            }
3260            return new ArrayList<ResolveInfo>();
3261        }
3262    }
3263
3264    private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) {
3265        String className;
3266        int userIdDest = fif.getUserIdDest();
3267        if (userIdDest == UserHandle.USER_OWNER) {
3268            className = FORWARD_INTENT_TO_USER_OWNER;
3269        } else {
3270            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3271        }
3272        ComponentName forwardingActivityComponentName = new ComponentName(
3273                mAndroidApplication.packageName, className);
3274        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3275                userIdFrom);
3276        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3277        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3278        forwardingResolveInfo.priority = 0;
3279        forwardingResolveInfo.preferredOrder = 0;
3280        forwardingResolveInfo.match = 0;
3281        forwardingResolveInfo.isDefault = true;
3282        forwardingResolveInfo.filter = fif;
3283        return forwardingResolveInfo;
3284    }
3285
3286    @Override
3287    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3288            Intent[] specifics, String[] specificTypes, Intent intent,
3289            String resolvedType, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return Collections.emptyList();
3291        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3292                "query intent activity options");
3293        final String resultsAction = intent.getAction();
3294
3295        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3296                | PackageManager.GET_RESOLVED_FILTER, userId);
3297
3298        if (DEBUG_INTENT_MATCHING) {
3299            Log.v(TAG, "Query " + intent + ": " + results);
3300        }
3301
3302        int specificsPos = 0;
3303        int N;
3304
3305        // todo: note that the algorithm used here is O(N^2).  This
3306        // isn't a problem in our current environment, but if we start running
3307        // into situations where we have more than 5 or 10 matches then this
3308        // should probably be changed to something smarter...
3309
3310        // First we go through and resolve each of the specific items
3311        // that were supplied, taking care of removing any corresponding
3312        // duplicate items in the generic resolve list.
3313        if (specifics != null) {
3314            for (int i=0; i<specifics.length; i++) {
3315                final Intent sintent = specifics[i];
3316                if (sintent == null) {
3317                    continue;
3318                }
3319
3320                if (DEBUG_INTENT_MATCHING) {
3321                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3322                }
3323
3324                String action = sintent.getAction();
3325                if (resultsAction != null && resultsAction.equals(action)) {
3326                    // If this action was explicitly requested, then don't
3327                    // remove things that have it.
3328                    action = null;
3329                }
3330
3331                ResolveInfo ri = null;
3332                ActivityInfo ai = null;
3333
3334                ComponentName comp = sintent.getComponent();
3335                if (comp == null) {
3336                    ri = resolveIntent(
3337                        sintent,
3338                        specificTypes != null ? specificTypes[i] : null,
3339                            flags, userId);
3340                    if (ri == null) {
3341                        continue;
3342                    }
3343                    if (ri == mResolveInfo) {
3344                        // ACK!  Must do something better with this.
3345                    }
3346                    ai = ri.activityInfo;
3347                    comp = new ComponentName(ai.applicationInfo.packageName,
3348                            ai.name);
3349                } else {
3350                    ai = getActivityInfo(comp, flags, userId);
3351                    if (ai == null) {
3352                        continue;
3353                    }
3354                }
3355
3356                // Look for any generic query activities that are duplicates
3357                // of this specific one, and remove them from the results.
3358                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3359                N = results.size();
3360                int j;
3361                for (j=specificsPos; j<N; j++) {
3362                    ResolveInfo sri = results.get(j);
3363                    if ((sri.activityInfo.name.equals(comp.getClassName())
3364                            && sri.activityInfo.applicationInfo.packageName.equals(
3365                                    comp.getPackageName()))
3366                        || (action != null && sri.filter.matchAction(action))) {
3367                        results.remove(j);
3368                        if (DEBUG_INTENT_MATCHING) Log.v(
3369                            TAG, "Removing duplicate item from " + j
3370                            + " due to specific " + specificsPos);
3371                        if (ri == null) {
3372                            ri = sri;
3373                        }
3374                        j--;
3375                        N--;
3376                    }
3377                }
3378
3379                // Add this specific item to its proper place.
3380                if (ri == null) {
3381                    ri = new ResolveInfo();
3382                    ri.activityInfo = ai;
3383                }
3384                results.add(specificsPos, ri);
3385                ri.specificIndex = i;
3386                specificsPos++;
3387            }
3388        }
3389
3390        // Now we go through the remaining generic results and remove any
3391        // duplicate actions that are found here.
3392        N = results.size();
3393        for (int i=specificsPos; i<N-1; i++) {
3394            final ResolveInfo rii = results.get(i);
3395            if (rii.filter == null) {
3396                continue;
3397            }
3398
3399            // Iterate over all of the actions of this result's intent
3400            // filter...  typically this should be just one.
3401            final Iterator<String> it = rii.filter.actionsIterator();
3402            if (it == null) {
3403                continue;
3404            }
3405            while (it.hasNext()) {
3406                final String action = it.next();
3407                if (resultsAction != null && resultsAction.equals(action)) {
3408                    // If this action was explicitly requested, then don't
3409                    // remove things that have it.
3410                    continue;
3411                }
3412                for (int j=i+1; j<N; j++) {
3413                    final ResolveInfo rij = results.get(j);
3414                    if (rij.filter != null && rij.filter.hasAction(action)) {
3415                        results.remove(j);
3416                        if (DEBUG_INTENT_MATCHING) Log.v(
3417                            TAG, "Removing duplicate item from " + j
3418                            + " due to action " + action + " at " + i);
3419                        j--;
3420                        N--;
3421                    }
3422                }
3423            }
3424
3425            // If the caller didn't request filter information, drop it now
3426            // so we don't have to marshall/unmarshall it.
3427            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3428                rii.filter = null;
3429            }
3430        }
3431
3432        // Filter out the caller activity if so requested.
3433        if (caller != null) {
3434            N = results.size();
3435            for (int i=0; i<N; i++) {
3436                ActivityInfo ainfo = results.get(i).activityInfo;
3437                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3438                        && caller.getClassName().equals(ainfo.name)) {
3439                    results.remove(i);
3440                    break;
3441                }
3442            }
3443        }
3444
3445        // If the caller didn't request filter information,
3446        // drop them now so we don't have to
3447        // marshall/unmarshall it.
3448        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3449            N = results.size();
3450            for (int i=0; i<N; i++) {
3451                results.get(i).filter = null;
3452            }
3453        }
3454
3455        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3456        return results;
3457    }
3458
3459    @Override
3460    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3461            int userId) {
3462        if (!sUserManager.exists(userId)) return Collections.emptyList();
3463        ComponentName comp = intent.getComponent();
3464        if (comp == null) {
3465            if (intent.getSelector() != null) {
3466                intent = intent.getSelector();
3467                comp = intent.getComponent();
3468            }
3469        }
3470        if (comp != null) {
3471            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3472            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3473            if (ai != null) {
3474                ResolveInfo ri = new ResolveInfo();
3475                ri.activityInfo = ai;
3476                list.add(ri);
3477            }
3478            return list;
3479        }
3480
3481        // reader
3482        synchronized (mPackages) {
3483            String pkgName = intent.getPackage();
3484            if (pkgName == null) {
3485                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3486            }
3487            final PackageParser.Package pkg = mPackages.get(pkgName);
3488            if (pkg != null) {
3489                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3490                        userId);
3491            }
3492            return null;
3493        }
3494    }
3495
3496    @Override
3497    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3498        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3499        if (!sUserManager.exists(userId)) return null;
3500        if (query != null) {
3501            if (query.size() >= 1) {
3502                // If there is more than one service with the same priority,
3503                // just arbitrarily pick the first one.
3504                return query.get(0);
3505            }
3506        }
3507        return null;
3508    }
3509
3510    @Override
3511    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3512            int userId) {
3513        if (!sUserManager.exists(userId)) return Collections.emptyList();
3514        ComponentName comp = intent.getComponent();
3515        if (comp == null) {
3516            if (intent.getSelector() != null) {
3517                intent = intent.getSelector();
3518                comp = intent.getComponent();
3519            }
3520        }
3521        if (comp != null) {
3522            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3523            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3524            if (si != null) {
3525                final ResolveInfo ri = new ResolveInfo();
3526                ri.serviceInfo = si;
3527                list.add(ri);
3528            }
3529            return list;
3530        }
3531
3532        // reader
3533        synchronized (mPackages) {
3534            String pkgName = intent.getPackage();
3535            if (pkgName == null) {
3536                return mServices.queryIntent(intent, resolvedType, flags, userId);
3537            }
3538            final PackageParser.Package pkg = mPackages.get(pkgName);
3539            if (pkg != null) {
3540                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3541                        userId);
3542            }
3543            return null;
3544        }
3545    }
3546
3547    @Override
3548    public List<ResolveInfo> queryIntentContentProviders(
3549            Intent intent, String resolvedType, int flags, int userId) {
3550        if (!sUserManager.exists(userId)) return Collections.emptyList();
3551        ComponentName comp = intent.getComponent();
3552        if (comp == null) {
3553            if (intent.getSelector() != null) {
3554                intent = intent.getSelector();
3555                comp = intent.getComponent();
3556            }
3557        }
3558        if (comp != null) {
3559            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3560            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3561            if (pi != null) {
3562                final ResolveInfo ri = new ResolveInfo();
3563                ri.providerInfo = pi;
3564                list.add(ri);
3565            }
3566            return list;
3567        }
3568
3569        // reader
3570        synchronized (mPackages) {
3571            String pkgName = intent.getPackage();
3572            if (pkgName == null) {
3573                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3574            }
3575            final PackageParser.Package pkg = mPackages.get(pkgName);
3576            if (pkg != null) {
3577                return mProviders.queryIntentForPackage(
3578                        intent, resolvedType, flags, pkg.providers, userId);
3579            }
3580            return null;
3581        }
3582    }
3583
3584    @Override
3585    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3586        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3587
3588        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3589
3590        // writer
3591        synchronized (mPackages) {
3592            ArrayList<PackageInfo> list;
3593            if (listUninstalled) {
3594                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3595                for (PackageSetting ps : mSettings.mPackages.values()) {
3596                    PackageInfo pi;
3597                    if (ps.pkg != null) {
3598                        pi = generatePackageInfo(ps.pkg, flags, userId);
3599                    } else {
3600                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3601                    }
3602                    if (pi != null) {
3603                        list.add(pi);
3604                    }
3605                }
3606            } else {
3607                list = new ArrayList<PackageInfo>(mPackages.size());
3608                for (PackageParser.Package p : mPackages.values()) {
3609                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3610                    if (pi != null) {
3611                        list.add(pi);
3612                    }
3613                }
3614            }
3615
3616            return new ParceledListSlice<PackageInfo>(list);
3617        }
3618    }
3619
3620    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3621            String[] permissions, boolean[] tmp, int flags, int userId) {
3622        int numMatch = 0;
3623        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3624        for (int i=0; i<permissions.length; i++) {
3625            if (gp.grantedPermissions.contains(permissions[i])) {
3626                tmp[i] = true;
3627                numMatch++;
3628            } else {
3629                tmp[i] = false;
3630            }
3631        }
3632        if (numMatch == 0) {
3633            return;
3634        }
3635        PackageInfo pi;
3636        if (ps.pkg != null) {
3637            pi = generatePackageInfo(ps.pkg, flags, userId);
3638        } else {
3639            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3640        }
3641        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3642            if (numMatch == permissions.length) {
3643                pi.requestedPermissions = permissions;
3644            } else {
3645                pi.requestedPermissions = new String[numMatch];
3646                numMatch = 0;
3647                for (int i=0; i<permissions.length; i++) {
3648                    if (tmp[i]) {
3649                        pi.requestedPermissions[numMatch] = permissions[i];
3650                        numMatch++;
3651                    }
3652                }
3653            }
3654        }
3655        list.add(pi);
3656    }
3657
3658    @Override
3659    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3660            String[] permissions, int flags, int userId) {
3661        if (!sUserManager.exists(userId)) return null;
3662        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3663
3664        // writer
3665        synchronized (mPackages) {
3666            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3667            boolean[] tmpBools = new boolean[permissions.length];
3668            if (listUninstalled) {
3669                for (PackageSetting ps : mSettings.mPackages.values()) {
3670                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3671                }
3672            } else {
3673                for (PackageParser.Package pkg : mPackages.values()) {
3674                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3675                    if (ps != null) {
3676                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3677                                userId);
3678                    }
3679                }
3680            }
3681
3682            return new ParceledListSlice<PackageInfo>(list);
3683        }
3684    }
3685
3686    @Override
3687    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3688        if (!sUserManager.exists(userId)) return null;
3689        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3690
3691        // writer
3692        synchronized (mPackages) {
3693            ArrayList<ApplicationInfo> list;
3694            if (listUninstalled) {
3695                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3696                for (PackageSetting ps : mSettings.mPackages.values()) {
3697                    ApplicationInfo ai;
3698                    if (ps.pkg != null) {
3699                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3700                                ps.readUserState(userId), userId);
3701                    } else {
3702                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3703                    }
3704                    if (ai != null) {
3705                        list.add(ai);
3706                    }
3707                }
3708            } else {
3709                list = new ArrayList<ApplicationInfo>(mPackages.size());
3710                for (PackageParser.Package p : mPackages.values()) {
3711                    if (p.mExtras != null) {
3712                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3713                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3714                        if (ai != null) {
3715                            list.add(ai);
3716                        }
3717                    }
3718                }
3719            }
3720
3721            return new ParceledListSlice<ApplicationInfo>(list);
3722        }
3723    }
3724
3725    public List<ApplicationInfo> getPersistentApplications(int flags) {
3726        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3727
3728        // reader
3729        synchronized (mPackages) {
3730            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3731            final int userId = UserHandle.getCallingUserId();
3732            while (i.hasNext()) {
3733                final PackageParser.Package p = i.next();
3734                if (p.applicationInfo != null
3735                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3736                        && (!mSafeMode || isSystemApp(p))) {
3737                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3738                    if (ps != null) {
3739                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3740                                ps.readUserState(userId), userId);
3741                        if (ai != null) {
3742                            finalList.add(ai);
3743                        }
3744                    }
3745                }
3746            }
3747        }
3748
3749        return finalList;
3750    }
3751
3752    @Override
3753    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3754        if (!sUserManager.exists(userId)) return null;
3755        // reader
3756        synchronized (mPackages) {
3757            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3758            PackageSetting ps = provider != null
3759                    ? mSettings.mPackages.get(provider.owner.packageName)
3760                    : null;
3761            return ps != null
3762                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3763                    && (!mSafeMode || (provider.info.applicationInfo.flags
3764                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3765                    ? PackageParser.generateProviderInfo(provider, flags,
3766                            ps.readUserState(userId), userId)
3767                    : null;
3768        }
3769    }
3770
3771    /**
3772     * @deprecated
3773     */
3774    @Deprecated
3775    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3776        // reader
3777        synchronized (mPackages) {
3778            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3779                    .entrySet().iterator();
3780            final int userId = UserHandle.getCallingUserId();
3781            while (i.hasNext()) {
3782                Map.Entry<String, PackageParser.Provider> entry = i.next();
3783                PackageParser.Provider p = entry.getValue();
3784                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3785
3786                if (ps != null && p.syncable
3787                        && (!mSafeMode || (p.info.applicationInfo.flags
3788                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3789                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3790                            ps.readUserState(userId), userId);
3791                    if (info != null) {
3792                        outNames.add(entry.getKey());
3793                        outInfo.add(info);
3794                    }
3795                }
3796            }
3797        }
3798    }
3799
3800    public List<ProviderInfo> queryContentProviders(String processName,
3801            int uid, int flags) {
3802        ArrayList<ProviderInfo> finalList = null;
3803        // reader
3804        synchronized (mPackages) {
3805            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3806            final int userId = processName != null ?
3807                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3808            while (i.hasNext()) {
3809                final PackageParser.Provider p = i.next();
3810                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3811                if (ps != null && p.info.authority != null
3812                        && (processName == null
3813                                || (p.info.processName.equals(processName)
3814                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3815                        && mSettings.isEnabledLPr(p.info, flags, userId)
3816                        && (!mSafeMode
3817                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3818                    if (finalList == null) {
3819                        finalList = new ArrayList<ProviderInfo>(3);
3820                    }
3821                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3822                            ps.readUserState(userId), userId);
3823                    if (info != null) {
3824                        finalList.add(info);
3825                    }
3826                }
3827            }
3828        }
3829
3830        if (finalList != null) {
3831            Collections.sort(finalList, mProviderInitOrderSorter);
3832        }
3833
3834        return finalList;
3835    }
3836
3837    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3838            int flags) {
3839        // reader
3840        synchronized (mPackages) {
3841            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3842            return PackageParser.generateInstrumentationInfo(i, flags);
3843        }
3844    }
3845
3846    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3847            int flags) {
3848        ArrayList<InstrumentationInfo> finalList =
3849            new ArrayList<InstrumentationInfo>();
3850
3851        // reader
3852        synchronized (mPackages) {
3853            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3854            while (i.hasNext()) {
3855                final PackageParser.Instrumentation p = i.next();
3856                if (targetPackage == null
3857                        || targetPackage.equals(p.info.targetPackage)) {
3858                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3859                            flags);
3860                    if (ii != null) {
3861                        finalList.add(ii);
3862                    }
3863                }
3864            }
3865        }
3866
3867        return finalList;
3868    }
3869
3870    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3871        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3872        if (overlays == null) {
3873            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3874            return;
3875        }
3876        for (PackageParser.Package opkg : overlays.values()) {
3877            // Not much to do if idmap fails: we already logged the error
3878            // and we certainly don't want to abort installation of pkg simply
3879            // because an overlay didn't fit properly. For these reasons,
3880            // ignore the return value of createIdmapForPackagePairLI.
3881            createIdmapForPackagePairLI(pkg, opkg);
3882        }
3883    }
3884
3885    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3886            PackageParser.Package opkg) {
3887        if (!opkg.mTrustedOverlay) {
3888            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3889                    opkg.mScanPath + ": overlay not trusted");
3890            return false;
3891        }
3892        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3893        if (overlaySet == null) {
3894            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3895                    opkg.mScanPath + " but target package has no known overlays");
3896            return false;
3897        }
3898        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3899        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3900            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3901            return false;
3902        }
3903        PackageParser.Package[] overlayArray =
3904            overlaySet.values().toArray(new PackageParser.Package[0]);
3905        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3906            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3907                return p1.mOverlayPriority - p2.mOverlayPriority;
3908            }
3909        };
3910        Arrays.sort(overlayArray, cmp);
3911
3912        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3913        int i = 0;
3914        for (PackageParser.Package p : overlayArray) {
3915            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3916        }
3917        return true;
3918    }
3919
3920    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3921        String[] files = dir.list();
3922        if (files == null) {
3923            Log.d(TAG, "No files in app dir " + dir);
3924            return;
3925        }
3926
3927        if (DEBUG_PACKAGE_SCANNING) {
3928            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3929                    + " flags=0x" + Integer.toHexString(flags));
3930        }
3931
3932        int i;
3933        for (i=0; i<files.length; i++) {
3934            File file = new File(dir, files[i]);
3935            if (!isPackageFilename(files[i])) {
3936                // Ignore entries which are not apk's
3937                continue;
3938            }
3939            PackageParser.Package pkg = scanPackageLI(file,
3940                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3941            // Don't mess around with apps in system partition.
3942            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3943                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3944                // Delete the apk
3945                Slog.w(TAG, "Cleaning up failed install of " + file);
3946                file.delete();
3947            }
3948        }
3949    }
3950
3951    private static File getSettingsProblemFile() {
3952        File dataDir = Environment.getDataDirectory();
3953        File systemDir = new File(dataDir, "system");
3954        File fname = new File(systemDir, "uiderrors.txt");
3955        return fname;
3956    }
3957
3958    static void reportSettingsProblem(int priority, String msg) {
3959        try {
3960            File fname = getSettingsProblemFile();
3961            FileOutputStream out = new FileOutputStream(fname, true);
3962            PrintWriter pw = new FastPrintWriter(out);
3963            SimpleDateFormat formatter = new SimpleDateFormat();
3964            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3965            pw.println(dateString + ": " + msg);
3966            pw.close();
3967            FileUtils.setPermissions(
3968                    fname.toString(),
3969                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3970                    -1, -1);
3971        } catch (java.io.IOException e) {
3972        }
3973        Slog.println(priority, TAG, msg);
3974    }
3975
3976    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3977            PackageParser.Package pkg, File srcFile, int parseFlags) {
3978        if (ps != null
3979                && ps.codePath.equals(srcFile)
3980                && ps.timeStamp == srcFile.lastModified()
3981                && !isCompatSignatureUpdateNeeded(pkg)) {
3982            if (ps.signatures.mSignatures != null
3983                    && ps.signatures.mSignatures.length != 0) {
3984                // Optimization: reuse the existing cached certificates
3985                // if the package appears to be unchanged.
3986                pkg.mSignatures = ps.signatures.mSignatures;
3987                return true;
3988            }
3989
3990            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3991        } else {
3992            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3993        }
3994
3995        if (!pp.collectCertificates(pkg, parseFlags)) {
3996            mLastScanError = pp.getParseError();
3997            return false;
3998        }
3999        return true;
4000    }
4001
4002    /*
4003     *  Scan a package and return the newly parsed package.
4004     *  Returns null in case of errors and the error code is stored in mLastScanError
4005     */
4006    private PackageParser.Package scanPackageLI(File scanFile,
4007            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4008        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4009        String scanPath = scanFile.getPath();
4010        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4011        parseFlags |= mDefParseFlags;
4012        PackageParser pp = new PackageParser(scanPath);
4013        pp.setSeparateProcesses(mSeparateProcesses);
4014        pp.setOnlyCoreApps(mOnlyCore);
4015        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4016                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4017
4018        if (pkg == null) {
4019            mLastScanError = pp.getParseError();
4020            return null;
4021        }
4022
4023        PackageSetting ps = null;
4024        PackageSetting updatedPkg;
4025        // reader
4026        synchronized (mPackages) {
4027            // Look to see if we already know about this package.
4028            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4029            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4030                // This package has been renamed to its original name.  Let's
4031                // use that.
4032                ps = mSettings.peekPackageLPr(oldName);
4033            }
4034            // If there was no original package, see one for the real package name.
4035            if (ps == null) {
4036                ps = mSettings.peekPackageLPr(pkg.packageName);
4037            }
4038            // Check to see if this package could be hiding/updating a system
4039            // package.  Must look for it either under the original or real
4040            // package name depending on our state.
4041            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4042            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4043        }
4044        boolean updatedPkgBetter = false;
4045        // First check if this is a system package that may involve an update
4046        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4047            if (ps != null && !ps.codePath.equals(scanFile)) {
4048                // The path has changed from what was last scanned...  check the
4049                // version of the new path against what we have stored to determine
4050                // what to do.
4051                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4052                if (pkg.mVersionCode < ps.versionCode) {
4053                    // The system package has been updated and the code path does not match
4054                    // Ignore entry. Skip it.
4055                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4056                            + " ignored: updated version " + ps.versionCode
4057                            + " better than this " + pkg.mVersionCode);
4058                    if (!updatedPkg.codePath.equals(scanFile)) {
4059                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4060                                + ps.name + " changing from " + updatedPkg.codePathString
4061                                + " to " + scanFile);
4062                        updatedPkg.codePath = scanFile;
4063                        updatedPkg.codePathString = scanFile.toString();
4064                        // This is the point at which we know that the system-disk APK
4065                        // for this package has moved during a reboot (e.g. due to an OTA),
4066                        // so we need to reevaluate it for privilege policy.
4067                        if (locationIsPrivileged(scanFile)) {
4068                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4069                        }
4070                    }
4071                    updatedPkg.pkg = pkg;
4072                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4073                    return null;
4074                } else {
4075                    // The current app on the system partion is better than
4076                    // what we have updated to on the data partition; switch
4077                    // back to the system partition version.
4078                    // At this point, its safely assumed that package installation for
4079                    // apps in system partition will go through. If not there won't be a working
4080                    // version of the app
4081                    // writer
4082                    synchronized (mPackages) {
4083                        // Just remove the loaded entries from package lists.
4084                        mPackages.remove(ps.name);
4085                    }
4086                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4087                            + "reverting from " + ps.codePathString
4088                            + ": new version " + pkg.mVersionCode
4089                            + " better than installed " + ps.versionCode);
4090
4091                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4092                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4093                            getAppInstructionSetFromSettings(ps));
4094                    synchronized (mInstallLock) {
4095                        args.cleanUpResourcesLI();
4096                    }
4097                    synchronized (mPackages) {
4098                        mSettings.enableSystemPackageLPw(ps.name);
4099                    }
4100                    updatedPkgBetter = true;
4101                }
4102            }
4103        }
4104
4105        if (updatedPkg != null) {
4106            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4107            // initially
4108            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4109
4110            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4111            // flag set initially
4112            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4113                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4114            }
4115        }
4116        // Verify certificates against what was last scanned
4117        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4118            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4119            return null;
4120        }
4121
4122        /*
4123         * A new system app appeared, but we already had a non-system one of the
4124         * same name installed earlier.
4125         */
4126        boolean shouldHideSystemApp = false;
4127        if (updatedPkg == null && ps != null
4128                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4129            /*
4130             * Check to make sure the signatures match first. If they don't,
4131             * wipe the installed application and its data.
4132             */
4133            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4134                    != PackageManager.SIGNATURE_MATCH) {
4135                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4136                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4137                ps = null;
4138            } else {
4139                /*
4140                 * If the newly-added system app is an older version than the
4141                 * already installed version, hide it. It will be scanned later
4142                 * and re-added like an update.
4143                 */
4144                if (pkg.mVersionCode < ps.versionCode) {
4145                    shouldHideSystemApp = true;
4146                } else {
4147                    /*
4148                     * The newly found system app is a newer version that the
4149                     * one previously installed. Simply remove the
4150                     * already-installed application and replace it with our own
4151                     * while keeping the application data.
4152                     */
4153                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4154                            + ps.codePathString + ": new version " + pkg.mVersionCode
4155                            + " better than installed " + ps.versionCode);
4156                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4157                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4158                            getAppInstructionSetFromSettings(ps));
4159                    synchronized (mInstallLock) {
4160                        args.cleanUpResourcesLI();
4161                    }
4162                }
4163            }
4164        }
4165
4166        // The apk is forward locked (not public) if its code and resources
4167        // are kept in different files. (except for app in either system or
4168        // vendor path).
4169        // TODO grab this value from PackageSettings
4170        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4171            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4172                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4173            }
4174        }
4175
4176        String codePath = null;
4177        String resPath = null;
4178        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4179            if (ps != null && ps.resourcePathString != null) {
4180                resPath = ps.resourcePathString;
4181            } else {
4182                // Should not happen at all. Just log an error.
4183                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4184            }
4185        } else {
4186            resPath = pkg.mScanPath;
4187        }
4188
4189        codePath = pkg.mScanPath;
4190        // Set application objects path explicitly.
4191        setApplicationInfoPaths(pkg, codePath, resPath);
4192        // Note that we invoke the following method only if we are about to unpack an application
4193        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4194                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4195
4196        /*
4197         * If the system app should be overridden by a previously installed
4198         * data, hide the system app now and let the /data/app scan pick it up
4199         * again.
4200         */
4201        if (shouldHideSystemApp) {
4202            synchronized (mPackages) {
4203                /*
4204                 * We have to grant systems permissions before we hide, because
4205                 * grantPermissions will assume the package update is trying to
4206                 * expand its permissions.
4207                 */
4208                grantPermissionsLPw(pkg, true);
4209                mSettings.disableSystemPackageLPw(pkg.packageName);
4210            }
4211        }
4212
4213        return scannedPkg;
4214    }
4215
4216    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4217            String destResPath) {
4218        pkg.mPath = pkg.mScanPath = destCodePath;
4219        pkg.applicationInfo.sourceDir = destCodePath;
4220        pkg.applicationInfo.publicSourceDir = destResPath;
4221    }
4222
4223    private static String fixProcessName(String defProcessName,
4224            String processName, int uid) {
4225        if (processName == null) {
4226            return defProcessName;
4227        }
4228        return processName;
4229    }
4230
4231    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4232        if (pkgSetting.signatures.mSignatures != null) {
4233            // Already existing package. Make sure signatures match
4234            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4235                    == PackageManager.SIGNATURE_MATCH;
4236            if (!match) {
4237                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4238                        == PackageManager.SIGNATURE_MATCH;
4239            }
4240            if (!match) {
4241                Slog.e(TAG, "Package " + pkg.packageName
4242                        + " signatures do not match the previously installed version; ignoring!");
4243                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4244                return false;
4245            }
4246        }
4247        // Check for shared user signatures
4248        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4249            // Already existing package. Make sure signatures match
4250            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4251                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4252            if (!match) {
4253                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4254                        == PackageManager.SIGNATURE_MATCH;
4255            }
4256            if (!match) {
4257                Slog.e(TAG, "Package " + pkg.packageName
4258                        + " has no signatures that match those in shared user "
4259                        + pkgSetting.sharedUser.name + "; ignoring!");
4260                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4261                return false;
4262            }
4263        }
4264        return true;
4265    }
4266
4267    /**
4268     * Enforces that only the system UID or root's UID can call a method exposed
4269     * via Binder.
4270     *
4271     * @param message used as message if SecurityException is thrown
4272     * @throws SecurityException if the caller is not system or root
4273     */
4274    private static final void enforceSystemOrRoot(String message) {
4275        final int uid = Binder.getCallingUid();
4276        if (uid != Process.SYSTEM_UID && uid != 0) {
4277            throw new SecurityException(message);
4278        }
4279    }
4280
4281    @Override
4282    public void performBootDexOpt() {
4283        enforceSystemOrRoot("Only the system can request dexopt be performed");
4284
4285        final HashSet<PackageParser.Package> pkgs;
4286        synchronized (mPackages) {
4287            pkgs = mDeferredDexOpt;
4288            mDeferredDexOpt = null;
4289        }
4290
4291        if (pkgs != null) {
4292            int i = 0;
4293            for (PackageParser.Package pkg : pkgs) {
4294                if (!isFirstBoot()) {
4295                    i++;
4296                    try {
4297                        ActivityManagerNative.getDefault().showBootMessage(
4298                                mContext.getResources().getString(
4299                                        com.android.internal.R.string.android_upgrading_apk,
4300                                        i, pkgs.size()), true);
4301                    } catch (RemoteException e) {
4302                    }
4303                }
4304                PackageParser.Package p = pkg;
4305                synchronized (mInstallLock) {
4306                    if (!p.mDidDexOpt) {
4307                        performDexOptLI(p, false /* force dex */, false /* defer */,
4308                                true /* include dependencies */);
4309                    }
4310                }
4311            }
4312        }
4313    }
4314
4315    @Override
4316    public boolean performDexOpt(String packageName) {
4317        enforceSystemOrRoot("Only the system can request dexopt be performed");
4318        if (!mNoDexOpt) {
4319            return false;
4320        }
4321
4322        PackageParser.Package p;
4323        synchronized (mPackages) {
4324            p = mPackages.get(packageName);
4325            if (p == null || p.mDidDexOpt) {
4326                return false;
4327            }
4328        }
4329        synchronized (mInstallLock) {
4330            return performDexOptLI(p, false /* force dex */, false /* defer */,
4331                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4332        }
4333    }
4334
4335    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex,
4336            boolean defer, HashSet<String> done) {
4337        for (int i=0; i<libs.size(); i++) {
4338            PackageParser.Package libPkg;
4339            String libName;
4340            synchronized (mPackages) {
4341                libName = libs.get(i);
4342                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4343                if (lib != null && lib.apk != null) {
4344                    libPkg = mPackages.get(lib.apk);
4345                } else {
4346                    libPkg = null;
4347                }
4348            }
4349            if (libPkg != null && !done.contains(libName)) {
4350                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4351            }
4352        }
4353    }
4354
4355    static final int DEX_OPT_SKIPPED = 0;
4356    static final int DEX_OPT_PERFORMED = 1;
4357    static final int DEX_OPT_DEFERRED = 2;
4358    static final int DEX_OPT_FAILED = -1;
4359
4360    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4361            boolean forceDex,
4362            boolean defer, HashSet<String> done) {
4363        final String instructionSet = instructionSetOverride != null ?
4364                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4365
4366        if (done != null) {
4367            done.add(pkg.packageName);
4368            if (pkg.usesLibraries != null) {
4369                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4370            }
4371            if (pkg.usesOptionalLibraries != null) {
4372                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4373            }
4374        }
4375
4376        boolean performed = false;
4377        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4378            String path = pkg.mScanPath;
4379            int ret = 0;
4380            try {
4381                if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path,
4382                        pkg.packageName, instructionSet, defer)) {
4383                    if (!forceDex && defer) {
4384                        if (mDeferredDexOpt == null) {
4385                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4386                        }
4387                        mDeferredDexOpt.add(pkg);
4388                        return DEX_OPT_DEFERRED;
4389                    } else {
4390                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName +
4391                                " (instructionSet=" + instructionSet + ")");
4392
4393                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4394                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4395                                                pkg.packageName, instructionSet);
4396                        pkg.mDidDexOpt = true;
4397                        performed = true;
4398                    }
4399                }
4400            } catch (FileNotFoundException e) {
4401                Slog.w(TAG, "Apk not found for dexopt: " + path);
4402                ret = -1;
4403            } catch (IOException e) {
4404                Slog.w(TAG, "IOException reading apk: " + path, e);
4405                ret = -1;
4406            } catch (dalvik.system.StaleDexCacheError e) {
4407                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4408                ret = -1;
4409            } catch (Exception e) {
4410                Slog.w(TAG, "Exception when doing dexopt : ", e);
4411                ret = -1;
4412            }
4413            if (ret < 0) {
4414                //error from installer
4415                return DEX_OPT_FAILED;
4416            }
4417        }
4418
4419        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4420    }
4421
4422    private String getAppInstructionSet(ApplicationInfo info) {
4423        String instructionSet = getPreferredInstructionSet();
4424
4425        if (info.requiredCpuAbi != null) {
4426            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4427        }
4428
4429        return instructionSet;
4430    }
4431
4432    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4433        String instructionSet = getPreferredInstructionSet();
4434
4435        if (ps.requiredCpuAbiString != null) {
4436            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4437        }
4438
4439        return instructionSet;
4440    }
4441
4442    private static String getPreferredInstructionSet() {
4443        if (sPreferredInstructionSet == null) {
4444            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4445        }
4446
4447        return sPreferredInstructionSet;
4448    }
4449
4450    private static List<String> getAllInstructionSets() {
4451        final String[] allAbis = Build.SUPPORTED_ABIS;
4452        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4453
4454        for (String abi : allAbis) {
4455            final String instructionSet = VMRuntime.getInstructionSet(abi);
4456            if (!allInstructionSets.contains(instructionSet)) {
4457                allInstructionSets.add(instructionSet);
4458            }
4459        }
4460
4461        return allInstructionSets;
4462    }
4463
4464    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4465            boolean inclDependencies) {
4466        HashSet<String> done;
4467        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4468            done = new HashSet<String>();
4469            done.add(pkg.packageName);
4470        } else {
4471            done = null;
4472        }
4473        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4474    }
4475
4476    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4477        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4478            Slog.w(TAG, "Unable to update from " + oldPkg.name
4479                    + " to " + newPkg.packageName
4480                    + ": old package not in system partition");
4481            return false;
4482        } else if (mPackages.get(oldPkg.name) != null) {
4483            Slog.w(TAG, "Unable to update from " + oldPkg.name
4484                    + " to " + newPkg.packageName
4485                    + ": old package still exists");
4486            return false;
4487        }
4488        return true;
4489    }
4490
4491    File getDataPathForUser(int userId) {
4492        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4493    }
4494
4495    private File getDataPathForPackage(String packageName, int userId) {
4496        /*
4497         * Until we fully support multiple users, return the directory we
4498         * previously would have. The PackageManagerTests will need to be
4499         * revised when this is changed back..
4500         */
4501        if (userId == 0) {
4502            return new File(mAppDataDir, packageName);
4503        } else {
4504            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4505                + File.separator + packageName);
4506        }
4507    }
4508
4509    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4510        int[] users = sUserManager.getUserIds();
4511        int res = mInstaller.install(packageName, uid, uid, seinfo);
4512        if (res < 0) {
4513            return res;
4514        }
4515        for (int user : users) {
4516            if (user != 0) {
4517                res = mInstaller.createUserData(packageName,
4518                        UserHandle.getUid(user, uid), user, seinfo);
4519                if (res < 0) {
4520                    return res;
4521                }
4522            }
4523        }
4524        return res;
4525    }
4526
4527    private int removeDataDirsLI(String packageName) {
4528        int[] users = sUserManager.getUserIds();
4529        int res = 0;
4530        for (int user : users) {
4531            int resInner = mInstaller.remove(packageName, user);
4532            if (resInner < 0) {
4533                res = resInner;
4534            }
4535        }
4536
4537        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4538        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4539        if (!nativeLibraryFile.delete()) {
4540            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4541        }
4542
4543        return res;
4544    }
4545
4546    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4547            PackageParser.Package changingLib) {
4548        if (file.path != null) {
4549            mTmpSharedLibraries[num] = file.path;
4550            return num+1;
4551        }
4552        PackageParser.Package p = mPackages.get(file.apk);
4553        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4554            // If we are doing this while in the middle of updating a library apk,
4555            // then we need to make sure to use that new apk for determining the
4556            // dependencies here.  (We haven't yet finished committing the new apk
4557            // to the package manager state.)
4558            if (p == null || p.packageName.equals(changingLib.packageName)) {
4559                p = changingLib;
4560            }
4561        }
4562        if (p != null) {
4563            String path = p.mPath;
4564            for (int i=0; i<num; i++) {
4565                if (mTmpSharedLibraries[i].equals(path)) {
4566                    return num;
4567                }
4568            }
4569            mTmpSharedLibraries[num] = p.mPath;
4570            return num+1;
4571        }
4572        return num;
4573    }
4574
4575    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4576            PackageParser.Package changingLib) {
4577        // We might be upgrading from a version of the platform that did not
4578        // provide per-package native library directories for system apps.
4579        // Fix that up here.
4580        if (isSystemApp(pkg)) {
4581            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4582            setInternalAppNativeLibraryPath(pkg, ps);
4583        }
4584
4585        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4586            if (mTmpSharedLibraries == null ||
4587                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4588                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4589            }
4590            int num = 0;
4591            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4592            for (int i=0; i<N; i++) {
4593                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4594                if (file == null) {
4595                    Slog.e(TAG, "Package " + pkg.packageName
4596                            + " requires unavailable shared library "
4597                            + pkg.usesLibraries.get(i) + "; failing!");
4598                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4599                    return false;
4600                }
4601                num = addSharedLibraryLPw(file, num, changingLib);
4602            }
4603            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4604            for (int i=0; i<N; i++) {
4605                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4606                if (file == null) {
4607                    Slog.w(TAG, "Package " + pkg.packageName
4608                            + " desires unavailable shared library "
4609                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4610                } else {
4611                    num = addSharedLibraryLPw(file, num, changingLib);
4612                }
4613            }
4614            if (num > 0) {
4615                pkg.usesLibraryFiles = new String[num];
4616                System.arraycopy(mTmpSharedLibraries, 0,
4617                        pkg.usesLibraryFiles, 0, num);
4618            } else {
4619                pkg.usesLibraryFiles = null;
4620            }
4621        }
4622        return true;
4623    }
4624
4625    private static boolean hasString(List<String> list, List<String> which) {
4626        if (list == null) {
4627            return false;
4628        }
4629        for (int i=list.size()-1; i>=0; i--) {
4630            for (int j=which.size()-1; j>=0; j--) {
4631                if (which.get(j).equals(list.get(i))) {
4632                    return true;
4633                }
4634            }
4635        }
4636        return false;
4637    }
4638
4639    private void updateAllSharedLibrariesLPw() {
4640        for (PackageParser.Package pkg : mPackages.values()) {
4641            updateSharedLibrariesLPw(pkg, null);
4642        }
4643    }
4644
4645    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4646            PackageParser.Package changingPkg) {
4647        ArrayList<PackageParser.Package> res = null;
4648        for (PackageParser.Package pkg : mPackages.values()) {
4649            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4650                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4651                if (res == null) {
4652                    res = new ArrayList<PackageParser.Package>();
4653                }
4654                res.add(pkg);
4655                updateSharedLibrariesLPw(pkg, changingPkg);
4656            }
4657        }
4658        return res;
4659    }
4660
4661    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4662            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4663        File scanFile = new File(pkg.mScanPath);
4664        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4665                pkg.applicationInfo.publicSourceDir == null) {
4666            // Bail out. The resource and code paths haven't been set.
4667            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4668            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4669            return null;
4670        }
4671
4672        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4673            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4674        }
4675
4676        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4677            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4678        }
4679
4680        if (mCustomResolverComponentName != null &&
4681                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4682            setUpCustomResolverActivity(pkg);
4683        }
4684
4685        if (pkg.packageName.equals("android")) {
4686            synchronized (mPackages) {
4687                if (mAndroidApplication != null) {
4688                    Slog.w(TAG, "*************************************************");
4689                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4690                    Slog.w(TAG, " file=" + scanFile);
4691                    Slog.w(TAG, "*************************************************");
4692                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4693                    return null;
4694                }
4695
4696                // Set up information for our fall-back user intent resolution activity.
4697                mPlatformPackage = pkg;
4698                pkg.mVersionCode = mSdkVersion;
4699                mAndroidApplication = pkg.applicationInfo;
4700
4701                if (!mResolverReplaced) {
4702                    mResolveActivity.applicationInfo = mAndroidApplication;
4703                    mResolveActivity.name = ResolverActivity.class.getName();
4704                    mResolveActivity.packageName = mAndroidApplication.packageName;
4705                    mResolveActivity.processName = "system:ui";
4706                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4707                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4708                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4709                    mResolveActivity.exported = true;
4710                    mResolveActivity.enabled = true;
4711                    mResolveInfo.activityInfo = mResolveActivity;
4712                    mResolveInfo.priority = 0;
4713                    mResolveInfo.preferredOrder = 0;
4714                    mResolveInfo.match = 0;
4715                    mResolveComponentName = new ComponentName(
4716                            mAndroidApplication.packageName, mResolveActivity.name);
4717                }
4718            }
4719        }
4720
4721        if (DEBUG_PACKAGE_SCANNING) {
4722            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4723                Log.d(TAG, "Scanning package " + pkg.packageName);
4724        }
4725
4726        if (mPackages.containsKey(pkg.packageName)
4727                || mSharedLibraries.containsKey(pkg.packageName)) {
4728            Slog.w(TAG, "Application package " + pkg.packageName
4729                    + " already installed.  Skipping duplicate.");
4730            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4731            return null;
4732        }
4733
4734        // Initialize package source and resource directories
4735        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4736        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4737
4738        SharedUserSetting suid = null;
4739        PackageSetting pkgSetting = null;
4740
4741        if (!isSystemApp(pkg)) {
4742            // Only system apps can use these features.
4743            pkg.mOriginalPackages = null;
4744            pkg.mRealPackage = null;
4745            pkg.mAdoptPermissions = null;
4746        }
4747
4748        // writer
4749        synchronized (mPackages) {
4750            if (pkg.mSharedUserId != null) {
4751                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4752                if (suid == null) {
4753                    Slog.w(TAG, "Creating application package " + pkg.packageName
4754                            + " for shared user failed");
4755                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4756                    return null;
4757                }
4758                if (DEBUG_PACKAGE_SCANNING) {
4759                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4760                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4761                                + "): packages=" + suid.packages);
4762                }
4763            }
4764
4765            // Check if we are renaming from an original package name.
4766            PackageSetting origPackage = null;
4767            String realName = null;
4768            if (pkg.mOriginalPackages != null) {
4769                // This package may need to be renamed to a previously
4770                // installed name.  Let's check on that...
4771                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4772                if (pkg.mOriginalPackages.contains(renamed)) {
4773                    // This package had originally been installed as the
4774                    // original name, and we have already taken care of
4775                    // transitioning to the new one.  Just update the new
4776                    // one to continue using the old name.
4777                    realName = pkg.mRealPackage;
4778                    if (!pkg.packageName.equals(renamed)) {
4779                        // Callers into this function may have already taken
4780                        // care of renaming the package; only do it here if
4781                        // it is not already done.
4782                        pkg.setPackageName(renamed);
4783                    }
4784
4785                } else {
4786                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4787                        if ((origPackage = mSettings.peekPackageLPr(
4788                                pkg.mOriginalPackages.get(i))) != null) {
4789                            // We do have the package already installed under its
4790                            // original name...  should we use it?
4791                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4792                                // New package is not compatible with original.
4793                                origPackage = null;
4794                                continue;
4795                            } else if (origPackage.sharedUser != null) {
4796                                // Make sure uid is compatible between packages.
4797                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4798                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4799                                            + " to " + pkg.packageName + ": old uid "
4800                                            + origPackage.sharedUser.name
4801                                            + " differs from " + pkg.mSharedUserId);
4802                                    origPackage = null;
4803                                    continue;
4804                                }
4805                            } else {
4806                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4807                                        + pkg.packageName + " to old name " + origPackage.name);
4808                            }
4809                            break;
4810                        }
4811                    }
4812                }
4813            }
4814
4815            if (mTransferedPackages.contains(pkg.packageName)) {
4816                Slog.w(TAG, "Package " + pkg.packageName
4817                        + " was transferred to another, but its .apk remains");
4818            }
4819
4820            // Just create the setting, don't add it yet. For already existing packages
4821            // the PkgSetting exists already and doesn't have to be created.
4822            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4823                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4824                    pkg.applicationInfo.requiredCpuAbi,
4825                    pkg.applicationInfo.flags, user, false);
4826            if (pkgSetting == null) {
4827                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4828                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4829                return null;
4830            }
4831
4832            if (pkgSetting.origPackage != null) {
4833                // If we are first transitioning from an original package,
4834                // fix up the new package's name now.  We need to do this after
4835                // looking up the package under its new name, so getPackageLP
4836                // can take care of fiddling things correctly.
4837                pkg.setPackageName(origPackage.name);
4838
4839                // File a report about this.
4840                String msg = "New package " + pkgSetting.realName
4841                        + " renamed to replace old package " + pkgSetting.name;
4842                reportSettingsProblem(Log.WARN, msg);
4843
4844                // Make a note of it.
4845                mTransferedPackages.add(origPackage.name);
4846
4847                // No longer need to retain this.
4848                pkgSetting.origPackage = null;
4849            }
4850
4851            if (realName != null) {
4852                // Make a note of it.
4853                mTransferedPackages.add(pkg.packageName);
4854            }
4855
4856            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4857                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4858            }
4859
4860            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4861                // Check all shared libraries and map to their actual file path.
4862                // We only do this here for apps not on a system dir, because those
4863                // are the only ones that can fail an install due to this.  We
4864                // will take care of the system apps by updating all of their
4865                // library paths after the scan is done.
4866                if (!updateSharedLibrariesLPw(pkg, null)) {
4867                    return null;
4868                }
4869            }
4870
4871            if (mFoundPolicyFile) {
4872                SELinuxMMAC.assignSeinfoValue(pkg);
4873            }
4874
4875            pkg.applicationInfo.uid = pkgSetting.appId;
4876            pkg.mExtras = pkgSetting;
4877
4878            if (!verifySignaturesLP(pkgSetting, pkg)) {
4879                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4880                    return null;
4881                }
4882                // The signature has changed, but this package is in the system
4883                // image...  let's recover!
4884                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4885                // However...  if this package is part of a shared user, but it
4886                // doesn't match the signature of the shared user, let's fail.
4887                // What this means is that you can't change the signatures
4888                // associated with an overall shared user, which doesn't seem all
4889                // that unreasonable.
4890                if (pkgSetting.sharedUser != null) {
4891                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4892                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4893                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4894                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4895                        return null;
4896                    }
4897                }
4898                // File a report about this.
4899                String msg = "System package " + pkg.packageName
4900                        + " signature changed; retaining data.";
4901                reportSettingsProblem(Log.WARN, msg);
4902            }
4903
4904            // Verify that this new package doesn't have any content providers
4905            // that conflict with existing packages.  Only do this if the
4906            // package isn't already installed, since we don't want to break
4907            // things that are installed.
4908            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4909                final int N = pkg.providers.size();
4910                int i;
4911                for (i=0; i<N; i++) {
4912                    PackageParser.Provider p = pkg.providers.get(i);
4913                    if (p.info.authority != null) {
4914                        String names[] = p.info.authority.split(";");
4915                        for (int j = 0; j < names.length; j++) {
4916                            if (mProvidersByAuthority.containsKey(names[j])) {
4917                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4918                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4919                                        " (in package " + pkg.applicationInfo.packageName +
4920                                        ") is already used by "
4921                                        + ((other != null && other.getComponentName() != null)
4922                                                ? other.getComponentName().getPackageName() : "?"));
4923                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4924                                return null;
4925                            }
4926                        }
4927                    }
4928                }
4929            }
4930
4931            if (pkg.mAdoptPermissions != null) {
4932                // This package wants to adopt ownership of permissions from
4933                // another package.
4934                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4935                    final String origName = pkg.mAdoptPermissions.get(i);
4936                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4937                    if (orig != null) {
4938                        if (verifyPackageUpdateLPr(orig, pkg)) {
4939                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4940                                    + pkg.packageName);
4941                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4942                        }
4943                    }
4944                }
4945            }
4946        }
4947
4948        final String pkgName = pkg.packageName;
4949
4950        final long scanFileTime = scanFile.lastModified();
4951        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4952        pkg.applicationInfo.processName = fixProcessName(
4953                pkg.applicationInfo.packageName,
4954                pkg.applicationInfo.processName,
4955                pkg.applicationInfo.uid);
4956
4957        File dataPath;
4958        if (mPlatformPackage == pkg) {
4959            // The system package is special.
4960            dataPath = new File (Environment.getDataDirectory(), "system");
4961            pkg.applicationInfo.dataDir = dataPath.getPath();
4962        } else {
4963            // This is a normal package, need to make its data directory.
4964            dataPath = getDataPathForPackage(pkg.packageName, 0);
4965
4966            boolean uidError = false;
4967
4968            if (dataPath.exists()) {
4969                int currentUid = 0;
4970                try {
4971                    StructStat stat = Os.stat(dataPath.getPath());
4972                    currentUid = stat.st_uid;
4973                } catch (ErrnoException e) {
4974                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4975                }
4976
4977                // If we have mismatched owners for the data path, we have a problem.
4978                if (currentUid != pkg.applicationInfo.uid) {
4979                    boolean recovered = false;
4980                    if (currentUid == 0) {
4981                        // The directory somehow became owned by root.  Wow.
4982                        // This is probably because the system was stopped while
4983                        // installd was in the middle of messing with its libs
4984                        // directory.  Ask installd to fix that.
4985                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4986                                pkg.applicationInfo.uid);
4987                        if (ret >= 0) {
4988                            recovered = true;
4989                            String msg = "Package " + pkg.packageName
4990                                    + " unexpectedly changed to uid 0; recovered to " +
4991                                    + pkg.applicationInfo.uid;
4992                            reportSettingsProblem(Log.WARN, msg);
4993                        }
4994                    }
4995                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4996                            || (scanMode&SCAN_BOOTING) != 0)) {
4997                        // If this is a system app, we can at least delete its
4998                        // current data so the application will still work.
4999                        int ret = removeDataDirsLI(pkgName);
5000                        if (ret >= 0) {
5001                            // TODO: Kill the processes first
5002                            // Old data gone!
5003                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5004                                    ? "System package " : "Third party package ";
5005                            String msg = prefix + pkg.packageName
5006                                    + " has changed from uid: "
5007                                    + currentUid + " to "
5008                                    + pkg.applicationInfo.uid + "; old data erased";
5009                            reportSettingsProblem(Log.WARN, msg);
5010                            recovered = true;
5011
5012                            // And now re-install the app.
5013                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5014                                                   pkg.applicationInfo.seinfo);
5015                            if (ret == -1) {
5016                                // Ack should not happen!
5017                                msg = prefix + pkg.packageName
5018                                        + " could not have data directory re-created after delete.";
5019                                reportSettingsProblem(Log.WARN, msg);
5020                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5021                                return null;
5022                            }
5023                        }
5024                        if (!recovered) {
5025                            mHasSystemUidErrors = true;
5026                        }
5027                    } else if (!recovered) {
5028                        // If we allow this install to proceed, we will be broken.
5029                        // Abort, abort!
5030                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5031                        return null;
5032                    }
5033                    if (!recovered) {
5034                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5035                            + pkg.applicationInfo.uid + "/fs_"
5036                            + currentUid;
5037                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5038                        String msg = "Package " + pkg.packageName
5039                                + " has mismatched uid: "
5040                                + currentUid + " on disk, "
5041                                + pkg.applicationInfo.uid + " in settings";
5042                        // writer
5043                        synchronized (mPackages) {
5044                            mSettings.mReadMessages.append(msg);
5045                            mSettings.mReadMessages.append('\n');
5046                            uidError = true;
5047                            if (!pkgSetting.uidError) {
5048                                reportSettingsProblem(Log.ERROR, msg);
5049                            }
5050                        }
5051                    }
5052                }
5053                pkg.applicationInfo.dataDir = dataPath.getPath();
5054                if (mShouldRestoreconData) {
5055                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5056                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5057                                pkg.applicationInfo.uid);
5058                }
5059            } else {
5060                if (DEBUG_PACKAGE_SCANNING) {
5061                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5062                        Log.v(TAG, "Want this data dir: " + dataPath);
5063                }
5064                //invoke installer to do the actual installation
5065                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5066                                           pkg.applicationInfo.seinfo);
5067                if (ret < 0) {
5068                    // Error from installer
5069                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5070                    return null;
5071                }
5072
5073                if (dataPath.exists()) {
5074                    pkg.applicationInfo.dataDir = dataPath.getPath();
5075                } else {
5076                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5077                    pkg.applicationInfo.dataDir = null;
5078                }
5079            }
5080
5081            /*
5082             * Set the data dir to the default "/data/data/<package name>/lib"
5083             * if we got here without anyone telling us different (e.g., apps
5084             * stored on SD card have their native libraries stored in the ASEC
5085             * container with the APK).
5086             *
5087             * This happens during an upgrade from a package settings file that
5088             * doesn't have a native library path attribute at all.
5089             */
5090            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5091                if (pkgSetting.nativeLibraryPathString == null) {
5092                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5093                } else {
5094                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5095                }
5096            }
5097            pkgSetting.uidError = uidError;
5098        }
5099
5100        String path = scanFile.getPath();
5101        /* Note: We don't want to unpack the native binaries for
5102         *        system applications, unless they have been updated
5103         *        (the binaries are already under /system/lib).
5104         *        Also, don't unpack libs for apps on the external card
5105         *        since they should have their libraries in the ASEC
5106         *        container already.
5107         *
5108         *        In other words, we're going to unpack the binaries
5109         *        only for non-system apps and system app upgrades.
5110         */
5111        if (pkg.applicationInfo.nativeLibraryDir != null) {
5112            try {
5113                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5114                final String dataPathString = dataPath.getCanonicalPath();
5115
5116                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5117                    /*
5118                     * Upgrading from a previous version of the OS sometimes
5119                     * leaves native libraries in the /data/data/<app>/lib
5120                     * directory for system apps even when they shouldn't be.
5121                     * Recent changes in the JNI library search path
5122                     * necessitates we remove those to match previous behavior.
5123                     */
5124                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5125                        Log.i(TAG, "removed obsolete native libraries for system package "
5126                                + path);
5127                    }
5128
5129                    setInternalAppAbi(pkg, pkgSetting);
5130                } else {
5131                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5132                        /*
5133                         * Update native library dir if it starts with
5134                         * /data/data
5135                         */
5136                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5137                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5138                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5139                        }
5140
5141                        try {
5142                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5143                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5144                                Slog.e(TAG, "Unable to copy native libraries");
5145                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5146                                return null;
5147                            }
5148
5149                            // We've successfully copied native libraries across, so we make a
5150                            // note of what ABI we're using
5151                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5152                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
5153                            } else {
5154                                pkg.applicationInfo.requiredCpuAbi = null;
5155                            }
5156                        } catch (IOException e) {
5157                            Slog.e(TAG, "Unable to copy native libraries", e);
5158                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5159                            return null;
5160                        }
5161                    } else {
5162                        // We don't have to copy the shared libraries if we're in the ASEC container
5163                        // but we still need to scan the file to figure out what ABI the app needs.
5164                        //
5165                        // TODO: This duplicates work done in the default container service. It's possible
5166                        // to clean this up but we'll need to change the interface between this service
5167                        // and IMediaContainerService (but doing so will spread this logic out, rather
5168                        // than centralizing it).
5169                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5170                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5171                        if (abi >= 0) {
5172                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
5173                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5174                            // Note that (non upgraded) system apps will not have any native
5175                            // libraries bundled in their APK, but we're guaranteed not to be
5176                            // such an app at this point.
5177                            pkg.applicationInfo.requiredCpuAbi = null;
5178                        } else {
5179                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5180                            return null;
5181                        }
5182                        handle.close();
5183                    }
5184
5185                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5186                    final int[] userIds = sUserManager.getUserIds();
5187                    synchronized (mInstallLock) {
5188                        for (int userId : userIds) {
5189                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5190                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5191                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5192                                        + ")");
5193                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5194                                return null;
5195                            }
5196                        }
5197                    }
5198                }
5199            } catch (IOException ioe) {
5200                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5201            }
5202        }
5203        pkg.mScanPath = path;
5204
5205        if ((scanMode&SCAN_NO_DEX) == 0) {
5206            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5207                    == DEX_OPT_FAILED) {
5208                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5209                    removeDataDirsLI(pkg.packageName);
5210                }
5211
5212                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5213                return null;
5214            }
5215        }
5216
5217        if (mFactoryTest && pkg.requestedPermissions.contains(
5218                android.Manifest.permission.FACTORY_TEST)) {
5219            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5220        }
5221
5222        ArrayList<PackageParser.Package> clientLibPkgs = null;
5223
5224        // writer
5225        synchronized (mPackages) {
5226            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5227                // Only system apps can add new shared libraries.
5228                if (pkg.libraryNames != null) {
5229                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5230                        String name = pkg.libraryNames.get(i);
5231                        boolean allowed = false;
5232                        if (isUpdatedSystemApp(pkg)) {
5233                            // New library entries can only be added through the
5234                            // system image.  This is important to get rid of a lot
5235                            // of nasty edge cases: for example if we allowed a non-
5236                            // system update of the app to add a library, then uninstalling
5237                            // the update would make the library go away, and assumptions
5238                            // we made such as through app install filtering would now
5239                            // have allowed apps on the device which aren't compatible
5240                            // with it.  Better to just have the restriction here, be
5241                            // conservative, and create many fewer cases that can negatively
5242                            // impact the user experience.
5243                            final PackageSetting sysPs = mSettings
5244                                    .getDisabledSystemPkgLPr(pkg.packageName);
5245                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5246                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5247                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5248                                        allowed = true;
5249                                        allowed = true;
5250                                        break;
5251                                    }
5252                                }
5253                            }
5254                        } else {
5255                            allowed = true;
5256                        }
5257                        if (allowed) {
5258                            if (!mSharedLibraries.containsKey(name)) {
5259                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5260                            } else if (!name.equals(pkg.packageName)) {
5261                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5262                                        + name + " already exists; skipping");
5263                            }
5264                        } else {
5265                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5266                                    + name + " that is not declared on system image; skipping");
5267                        }
5268                    }
5269                    if ((scanMode&SCAN_BOOTING) == 0) {
5270                        // If we are not booting, we need to update any applications
5271                        // that are clients of our shared library.  If we are booting,
5272                        // this will all be done once the scan is complete.
5273                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5274                    }
5275                }
5276            }
5277        }
5278
5279        // We also need to dexopt any apps that are dependent on this library.  Note that
5280        // if these fail, we should abort the install since installing the library will
5281        // result in some apps being broken.
5282        if (clientLibPkgs != null) {
5283            if ((scanMode&SCAN_NO_DEX) == 0) {
5284                for (int i=0; i<clientLibPkgs.size(); i++) {
5285                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5286                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5287                            == DEX_OPT_FAILED) {
5288                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5289                            removeDataDirsLI(pkg.packageName);
5290                        }
5291
5292                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5293                        return null;
5294                    }
5295                }
5296            }
5297        }
5298
5299        // Request the ActivityManager to kill the process(only for existing packages)
5300        // so that we do not end up in a confused state while the user is still using the older
5301        // version of the application while the new one gets installed.
5302        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5303            // If the package lives in an asec, tell everyone that the container is going
5304            // away so they can clean up any references to its resources (which would prevent
5305            // vold from being able to unmount the asec)
5306            if (isForwardLocked(pkg) || isExternal(pkg)) {
5307                if (DEBUG_INSTALL) {
5308                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5309                }
5310                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5311                final ArrayList<String> pkgList = new ArrayList<String>(1);
5312                pkgList.add(pkg.applicationInfo.packageName);
5313                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5314            }
5315
5316            // Post the request that it be killed now that the going-away broadcast is en route
5317            killApplication(pkg.applicationInfo.packageName,
5318                        pkg.applicationInfo.uid, "update pkg");
5319        }
5320
5321        // Also need to kill any apps that are dependent on the library.
5322        if (clientLibPkgs != null) {
5323            for (int i=0; i<clientLibPkgs.size(); i++) {
5324                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5325                killApplication(clientPkg.applicationInfo.packageName,
5326                        clientPkg.applicationInfo.uid, "update lib");
5327            }
5328        }
5329
5330        // writer
5331        synchronized (mPackages) {
5332            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5333                // We don't do this here during boot because we can do it all
5334                // at once after scanning all existing packages.
5335                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5336                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5337            }
5338            // We don't expect installation to fail beyond this point,
5339            if ((scanMode&SCAN_MONITOR) != 0) {
5340                mAppDirs.put(pkg.mPath, pkg);
5341            }
5342            // Add the new setting to mSettings
5343            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5344            // Add the new setting to mPackages
5345            mPackages.put(pkg.applicationInfo.packageName, pkg);
5346            // Make sure we don't accidentally delete its data.
5347            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5348            while (iter.hasNext()) {
5349                PackageCleanItem item = iter.next();
5350                if (pkgName.equals(item.packageName)) {
5351                    iter.remove();
5352                }
5353            }
5354
5355            // Take care of first install / last update times.
5356            if (currentTime != 0) {
5357                if (pkgSetting.firstInstallTime == 0) {
5358                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5359                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5360                    pkgSetting.lastUpdateTime = currentTime;
5361                }
5362            } else if (pkgSetting.firstInstallTime == 0) {
5363                // We need *something*.  Take time time stamp of the file.
5364                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5365            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5366                if (scanFileTime != pkgSetting.timeStamp) {
5367                    // A package on the system image has changed; consider this
5368                    // to be an update.
5369                    pkgSetting.lastUpdateTime = scanFileTime;
5370                }
5371            }
5372
5373            // Add the package's KeySets to the global KeySetManager
5374            KeySetManager ksm = mSettings.mKeySetManager;
5375            try {
5376                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5377                if (pkg.mKeySetMapping != null) {
5378                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5379                        if (entry.getValue() != null) {
5380                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5381                                entry.getValue(), entry.getKey());
5382                        }
5383                    }
5384                }
5385            } catch (NullPointerException e) {
5386                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5387            } catch (IllegalArgumentException e) {
5388                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5389            }
5390
5391            int N = pkg.providers.size();
5392            StringBuilder r = null;
5393            int i;
5394            for (i=0; i<N; i++) {
5395                PackageParser.Provider p = pkg.providers.get(i);
5396                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5397                        p.info.processName, pkg.applicationInfo.uid);
5398                mProviders.addProvider(p);
5399                p.syncable = p.info.isSyncable;
5400                if (p.info.authority != null) {
5401                    String names[] = p.info.authority.split(";");
5402                    p.info.authority = null;
5403                    for (int j = 0; j < names.length; j++) {
5404                        if (j == 1 && p.syncable) {
5405                            // We only want the first authority for a provider to possibly be
5406                            // syncable, so if we already added this provider using a different
5407                            // authority clear the syncable flag. We copy the provider before
5408                            // changing it because the mProviders object contains a reference
5409                            // to a provider that we don't want to change.
5410                            // Only do this for the second authority since the resulting provider
5411                            // object can be the same for all future authorities for this provider.
5412                            p = new PackageParser.Provider(p);
5413                            p.syncable = false;
5414                        }
5415                        if (!mProvidersByAuthority.containsKey(names[j])) {
5416                            mProvidersByAuthority.put(names[j], p);
5417                            if (p.info.authority == null) {
5418                                p.info.authority = names[j];
5419                            } else {
5420                                p.info.authority = p.info.authority + ";" + names[j];
5421                            }
5422                            if (DEBUG_PACKAGE_SCANNING) {
5423                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5424                                    Log.d(TAG, "Registered content provider: " + names[j]
5425                                            + ", className = " + p.info.name + ", isSyncable = "
5426                                            + p.info.isSyncable);
5427                            }
5428                        } else {
5429                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5430                            Slog.w(TAG, "Skipping provider name " + names[j] +
5431                                    " (in package " + pkg.applicationInfo.packageName +
5432                                    "): name already used by "
5433                                    + ((other != null && other.getComponentName() != null)
5434                                            ? other.getComponentName().getPackageName() : "?"));
5435                        }
5436                    }
5437                }
5438                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5439                    if (r == null) {
5440                        r = new StringBuilder(256);
5441                    } else {
5442                        r.append(' ');
5443                    }
5444                    r.append(p.info.name);
5445                }
5446            }
5447            if (r != null) {
5448                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5449            }
5450
5451            N = pkg.services.size();
5452            r = null;
5453            for (i=0; i<N; i++) {
5454                PackageParser.Service s = pkg.services.get(i);
5455                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5456                        s.info.processName, pkg.applicationInfo.uid);
5457                mServices.addService(s);
5458                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5459                    if (r == null) {
5460                        r = new StringBuilder(256);
5461                    } else {
5462                        r.append(' ');
5463                    }
5464                    r.append(s.info.name);
5465                }
5466            }
5467            if (r != null) {
5468                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5469            }
5470
5471            N = pkg.receivers.size();
5472            r = null;
5473            for (i=0; i<N; i++) {
5474                PackageParser.Activity a = pkg.receivers.get(i);
5475                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5476                        a.info.processName, pkg.applicationInfo.uid);
5477                mReceivers.addActivity(a, "receiver");
5478                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5479                    if (r == null) {
5480                        r = new StringBuilder(256);
5481                    } else {
5482                        r.append(' ');
5483                    }
5484                    r.append(a.info.name);
5485                }
5486            }
5487            if (r != null) {
5488                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5489            }
5490
5491            N = pkg.activities.size();
5492            r = null;
5493            for (i=0; i<N; i++) {
5494                PackageParser.Activity a = pkg.activities.get(i);
5495                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5496                        a.info.processName, pkg.applicationInfo.uid);
5497                mActivities.addActivity(a, "activity");
5498                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5499                    if (r == null) {
5500                        r = new StringBuilder(256);
5501                    } else {
5502                        r.append(' ');
5503                    }
5504                    r.append(a.info.name);
5505                }
5506            }
5507            if (r != null) {
5508                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5509            }
5510
5511            N = pkg.permissionGroups.size();
5512            r = null;
5513            for (i=0; i<N; i++) {
5514                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5515                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5516                if (cur == null) {
5517                    mPermissionGroups.put(pg.info.name, pg);
5518                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5519                        if (r == null) {
5520                            r = new StringBuilder(256);
5521                        } else {
5522                            r.append(' ');
5523                        }
5524                        r.append(pg.info.name);
5525                    }
5526                } else {
5527                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5528                            + pg.info.packageName + " ignored: original from "
5529                            + cur.info.packageName);
5530                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5531                        if (r == null) {
5532                            r = new StringBuilder(256);
5533                        } else {
5534                            r.append(' ');
5535                        }
5536                        r.append("DUP:");
5537                        r.append(pg.info.name);
5538                    }
5539                }
5540            }
5541            if (r != null) {
5542                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5543            }
5544
5545            N = pkg.permissions.size();
5546            r = null;
5547            for (i=0; i<N; i++) {
5548                PackageParser.Permission p = pkg.permissions.get(i);
5549                HashMap<String, BasePermission> permissionMap =
5550                        p.tree ? mSettings.mPermissionTrees
5551                        : mSettings.mPermissions;
5552                p.group = mPermissionGroups.get(p.info.group);
5553                if (p.info.group == null || p.group != null) {
5554                    BasePermission bp = permissionMap.get(p.info.name);
5555                    if (bp == null) {
5556                        bp = new BasePermission(p.info.name, p.info.packageName,
5557                                BasePermission.TYPE_NORMAL);
5558                        permissionMap.put(p.info.name, bp);
5559                    }
5560                    if (bp.perm == null) {
5561                        if (bp.sourcePackage != null
5562                                && !bp.sourcePackage.equals(p.info.packageName)) {
5563                            // If this is a permission that was formerly defined by a non-system
5564                            // app, but is now defined by a system app (following an upgrade),
5565                            // discard the previous declaration and consider the system's to be
5566                            // canonical.
5567                            if (isSystemApp(p.owner)) {
5568                                String msg = "New decl " + p.owner + " of permission  "
5569                                        + p.info.name + " is system";
5570                                reportSettingsProblem(Log.WARN, msg);
5571                                bp.sourcePackage = null;
5572                            }
5573                        }
5574                        if (bp.sourcePackage == null
5575                                || bp.sourcePackage.equals(p.info.packageName)) {
5576                            BasePermission tree = findPermissionTreeLP(p.info.name);
5577                            if (tree == null
5578                                    || tree.sourcePackage.equals(p.info.packageName)) {
5579                                bp.packageSetting = pkgSetting;
5580                                bp.perm = p;
5581                                bp.uid = pkg.applicationInfo.uid;
5582                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5583                                    if (r == null) {
5584                                        r = new StringBuilder(256);
5585                                    } else {
5586                                        r.append(' ');
5587                                    }
5588                                    r.append(p.info.name);
5589                                }
5590                            } else {
5591                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5592                                        + p.info.packageName + " ignored: base tree "
5593                                        + tree.name + " is from package "
5594                                        + tree.sourcePackage);
5595                            }
5596                        } else {
5597                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5598                                    + p.info.packageName + " ignored: original from "
5599                                    + bp.sourcePackage);
5600                        }
5601                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5602                        if (r == null) {
5603                            r = new StringBuilder(256);
5604                        } else {
5605                            r.append(' ');
5606                        }
5607                        r.append("DUP:");
5608                        r.append(p.info.name);
5609                    }
5610                    if (bp.perm == p) {
5611                        bp.protectionLevel = p.info.protectionLevel;
5612                    }
5613                } else {
5614                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5615                            + p.info.packageName + " ignored: no group "
5616                            + p.group);
5617                }
5618            }
5619            if (r != null) {
5620                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5621            }
5622
5623            N = pkg.instrumentation.size();
5624            r = null;
5625            for (i=0; i<N; i++) {
5626                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5627                a.info.packageName = pkg.applicationInfo.packageName;
5628                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5629                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5630                a.info.dataDir = pkg.applicationInfo.dataDir;
5631                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5632                mInstrumentation.put(a.getComponentName(), a);
5633                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5634                    if (r == null) {
5635                        r = new StringBuilder(256);
5636                    } else {
5637                        r.append(' ');
5638                    }
5639                    r.append(a.info.name);
5640                }
5641            }
5642            if (r != null) {
5643                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5644            }
5645
5646            if (pkg.protectedBroadcasts != null) {
5647                N = pkg.protectedBroadcasts.size();
5648                for (i=0; i<N; i++) {
5649                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5650                }
5651            }
5652
5653            pkgSetting.setTimeStamp(scanFileTime);
5654
5655            // Create idmap files for pairs of (packages, overlay packages).
5656            // Note: "android", ie framework-res.apk, is handled by native layers.
5657            if (pkg.mOverlayTarget != null) {
5658                // This is an overlay package.
5659                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5660                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5661                        mOverlays.put(pkg.mOverlayTarget,
5662                                new HashMap<String, PackageParser.Package>());
5663                    }
5664                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5665                    map.put(pkg.packageName, pkg);
5666                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5667                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5668                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5669                        return null;
5670                    }
5671                }
5672            } else if (mOverlays.containsKey(pkg.packageName) &&
5673                    !pkg.packageName.equals("android")) {
5674                // This is a regular package, with one or more known overlay packages.
5675                createIdmapsForPackageLI(pkg);
5676            }
5677        }
5678
5679        return pkg;
5680    }
5681
5682    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5683            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5684        String requiredInstructionSet = null;
5685        PackageSetting requirer = null;
5686        for (PackageSetting ps : packagesForUser) {
5687            if (ps.requiredCpuAbiString != null) {
5688                final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
5689                if (requiredInstructionSet != null) {
5690                    if (!instructionSet.equals(requiredInstructionSet)) {
5691                        // We have a mismatch between instruction sets (say arm vs arm64).
5692                        //
5693                        // TODO: We should rescan all the packages in a shared UID to check if
5694                        // they do contain shared libs for other ABIs in addition to the ones we've
5695                        // already extracted. For example, the package might contain both arm64-v8a
5696                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5697                        // devices.
5698                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5699                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5700                                + " requires " + instructionSet;
5701                        Slog.e(TAG, errorMessage);
5702
5703                        reportSettingsProblem(Log.WARN, errorMessage);
5704                        // Give up, don't bother making any other changes to the package settings.
5705                        return;
5706                    }
5707                } else {
5708                    requiredInstructionSet = instructionSet;
5709                    requirer = ps;
5710                }
5711            }
5712        }
5713
5714        if (requiredInstructionSet != null) {
5715            for (PackageSetting ps : packagesForUser) {
5716                if (ps.requiredCpuAbiString == null) {
5717                    ps.requiredCpuAbiString = requirer.requiredCpuAbiString;
5718                    if (ps.pkg != null) {
5719                        ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString;
5720                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString);
5721                        if (doDexOpt) {
5722                            performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
5723                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5724                        }
5725                    }
5726                }
5727            }
5728        }
5729    }
5730
5731    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5732        synchronized (mPackages) {
5733            mResolverReplaced = true;
5734            // Set up information for custom user intent resolution activity.
5735            mResolveActivity.applicationInfo = pkg.applicationInfo;
5736            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5737            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5738            mResolveActivity.processName = null;
5739            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5740            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5741                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5742            mResolveActivity.theme = 0;
5743            mResolveActivity.exported = true;
5744            mResolveActivity.enabled = true;
5745            mResolveInfo.activityInfo = mResolveActivity;
5746            mResolveInfo.priority = 0;
5747            mResolveInfo.preferredOrder = 0;
5748            mResolveInfo.match = 0;
5749            mResolveComponentName = mCustomResolverComponentName;
5750            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5751                    mResolveComponentName);
5752        }
5753    }
5754
5755    private String calculateApkRoot(final String codePathString) {
5756        final File codePath = new File(codePathString);
5757        final File codeRoot;
5758        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5759            codeRoot = Environment.getRootDirectory();
5760        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5761            codeRoot = Environment.getOemDirectory();
5762        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5763            codeRoot = Environment.getVendorDirectory();
5764        } else {
5765            // Unrecognized code path; take its top real segment as the apk root:
5766            // e.g. /something/app/blah.apk => /something
5767            try {
5768                File f = codePath.getCanonicalFile();
5769                File parent = f.getParentFile();    // non-null because codePath is a file
5770                File tmp;
5771                while ((tmp = parent.getParentFile()) != null) {
5772                    f = parent;
5773                    parent = tmp;
5774                }
5775                codeRoot = f;
5776                Slog.w(TAG, "Unrecognized code path "
5777                        + codePath + " - using " + codeRoot);
5778            } catch (IOException e) {
5779                // Can't canonicalize the lib path -- shenanigans?
5780                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5781                return Environment.getRootDirectory().getPath();
5782            }
5783        }
5784        return codeRoot.getPath();
5785    }
5786
5787    // This is the initial scan-time determination of how to handle a given
5788    // package for purposes of native library location.
5789    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5790            PackageSetting pkgSetting) {
5791        // "bundled" here means system-installed with no overriding update
5792        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5793        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5794        final File libDir;
5795        if (bundledApk) {
5796            // If "/system/lib64/apkname" exists, assume that is the per-package
5797            // native library directory to use; otherwise use "/system/lib/apkname".
5798            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5799            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5800            File packLib64 = new File(lib64, apkName);
5801            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5802        } else {
5803            libDir = mAppLibInstallDir;
5804        }
5805        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5806        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5807        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5808    }
5809
5810    // Deduces the required ABI of an upgraded system app.
5811    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
5812        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5813        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5814
5815        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
5816        // or similar.
5817        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
5818        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
5819
5820        // Assume that the bundled native libraries always correspond to the
5821        // most preferred 32 or 64 bit ABI.
5822        if (lib64.exists()) {
5823            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
5824            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
5825        } else if (lib.exists()) {
5826            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5827            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
5828        } else {
5829            // This is the case where the app has no native code.
5830            pkg.applicationInfo.requiredCpuAbi = null;
5831            pkgSetting.requiredCpuAbiString = null;
5832        }
5833    }
5834
5835    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5836            throws IOException {
5837        if (!nativeLibraryDir.isDirectory()) {
5838            nativeLibraryDir.delete();
5839
5840            if (!nativeLibraryDir.mkdir()) {
5841                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5842            }
5843
5844            try {
5845                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5846            } catch (ErrnoException e) {
5847                throw new IOException("Cannot chmod native library directory "
5848                        + nativeLibraryDir.getPath(), e);
5849            }
5850        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5851            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5852        }
5853
5854        /*
5855         * If this is an internal application or our nativeLibraryPath points to
5856         * the app-lib directory, unpack the libraries if necessary.
5857         */
5858        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5859        try {
5860            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5861            if (abi >= 0) {
5862                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5863                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5864                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5865                    return copyRet;
5866                }
5867            }
5868
5869            return abi;
5870        } finally {
5871            handle.close();
5872        }
5873    }
5874
5875    private void killApplication(String pkgName, int appId, String reason) {
5876        // Request the ActivityManager to kill the process(only for existing packages)
5877        // so that we do not end up in a confused state while the user is still using the older
5878        // version of the application while the new one gets installed.
5879        IActivityManager am = ActivityManagerNative.getDefault();
5880        if (am != null) {
5881            try {
5882                am.killApplicationWithAppId(pkgName, appId, reason);
5883            } catch (RemoteException e) {
5884            }
5885        }
5886    }
5887
5888    void removePackageLI(PackageSetting ps, boolean chatty) {
5889        if (DEBUG_INSTALL) {
5890            if (chatty)
5891                Log.d(TAG, "Removing package " + ps.name);
5892        }
5893
5894        // writer
5895        synchronized (mPackages) {
5896            mPackages.remove(ps.name);
5897            if (ps.codePathString != null) {
5898                mAppDirs.remove(ps.codePathString);
5899            }
5900
5901            final PackageParser.Package pkg = ps.pkg;
5902            if (pkg != null) {
5903                cleanPackageDataStructuresLILPw(pkg, chatty);
5904            }
5905        }
5906    }
5907
5908    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5909        if (DEBUG_INSTALL) {
5910            if (chatty)
5911                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5912        }
5913
5914        // writer
5915        synchronized (mPackages) {
5916            mPackages.remove(pkg.applicationInfo.packageName);
5917            if (pkg.mPath != null) {
5918                mAppDirs.remove(pkg.mPath);
5919            }
5920            cleanPackageDataStructuresLILPw(pkg, chatty);
5921        }
5922    }
5923
5924    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5925        int N = pkg.providers.size();
5926        StringBuilder r = null;
5927        int i;
5928        for (i=0; i<N; i++) {
5929            PackageParser.Provider p = pkg.providers.get(i);
5930            mProviders.removeProvider(p);
5931            if (p.info.authority == null) {
5932
5933                /* There was another ContentProvider with this authority when
5934                 * this app was installed so this authority is null,
5935                 * Ignore it as we don't have to unregister the provider.
5936                 */
5937                continue;
5938            }
5939            String names[] = p.info.authority.split(";");
5940            for (int j = 0; j < names.length; j++) {
5941                if (mProvidersByAuthority.get(names[j]) == p) {
5942                    mProvidersByAuthority.remove(names[j]);
5943                    if (DEBUG_REMOVE) {
5944                        if (chatty)
5945                            Log.d(TAG, "Unregistered content provider: " + names[j]
5946                                    + ", className = " + p.info.name + ", isSyncable = "
5947                                    + p.info.isSyncable);
5948                    }
5949                }
5950            }
5951            if (DEBUG_REMOVE && chatty) {
5952                if (r == null) {
5953                    r = new StringBuilder(256);
5954                } else {
5955                    r.append(' ');
5956                }
5957                r.append(p.info.name);
5958            }
5959        }
5960        if (r != null) {
5961            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5962        }
5963
5964        N = pkg.services.size();
5965        r = null;
5966        for (i=0; i<N; i++) {
5967            PackageParser.Service s = pkg.services.get(i);
5968            mServices.removeService(s);
5969            if (chatty) {
5970                if (r == null) {
5971                    r = new StringBuilder(256);
5972                } else {
5973                    r.append(' ');
5974                }
5975                r.append(s.info.name);
5976            }
5977        }
5978        if (r != null) {
5979            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5980        }
5981
5982        N = pkg.receivers.size();
5983        r = null;
5984        for (i=0; i<N; i++) {
5985            PackageParser.Activity a = pkg.receivers.get(i);
5986            mReceivers.removeActivity(a, "receiver");
5987            if (DEBUG_REMOVE && chatty) {
5988                if (r == null) {
5989                    r = new StringBuilder(256);
5990                } else {
5991                    r.append(' ');
5992                }
5993                r.append(a.info.name);
5994            }
5995        }
5996        if (r != null) {
5997            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5998        }
5999
6000        N = pkg.activities.size();
6001        r = null;
6002        for (i=0; i<N; i++) {
6003            PackageParser.Activity a = pkg.activities.get(i);
6004            mActivities.removeActivity(a, "activity");
6005            if (DEBUG_REMOVE && chatty) {
6006                if (r == null) {
6007                    r = new StringBuilder(256);
6008                } else {
6009                    r.append(' ');
6010                }
6011                r.append(a.info.name);
6012            }
6013        }
6014        if (r != null) {
6015            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6016        }
6017
6018        N = pkg.permissions.size();
6019        r = null;
6020        for (i=0; i<N; i++) {
6021            PackageParser.Permission p = pkg.permissions.get(i);
6022            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6023            if (bp == null) {
6024                bp = mSettings.mPermissionTrees.get(p.info.name);
6025            }
6026            if (bp != null && bp.perm == p) {
6027                bp.perm = null;
6028                if (DEBUG_REMOVE && chatty) {
6029                    if (r == null) {
6030                        r = new StringBuilder(256);
6031                    } else {
6032                        r.append(' ');
6033                    }
6034                    r.append(p.info.name);
6035                }
6036            }
6037        }
6038        if (r != null) {
6039            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6040        }
6041
6042        N = pkg.instrumentation.size();
6043        r = null;
6044        for (i=0; i<N; i++) {
6045            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6046            mInstrumentation.remove(a.getComponentName());
6047            if (DEBUG_REMOVE && chatty) {
6048                if (r == null) {
6049                    r = new StringBuilder(256);
6050                } else {
6051                    r.append(' ');
6052                }
6053                r.append(a.info.name);
6054            }
6055        }
6056        if (r != null) {
6057            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6058        }
6059
6060        r = null;
6061        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6062            // Only system apps can hold shared libraries.
6063            if (pkg.libraryNames != null) {
6064                for (i=0; i<pkg.libraryNames.size(); i++) {
6065                    String name = pkg.libraryNames.get(i);
6066                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6067                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6068                        mSharedLibraries.remove(name);
6069                        if (DEBUG_REMOVE && chatty) {
6070                            if (r == null) {
6071                                r = new StringBuilder(256);
6072                            } else {
6073                                r.append(' ');
6074                            }
6075                            r.append(name);
6076                        }
6077                    }
6078                }
6079            }
6080        }
6081        if (r != null) {
6082            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6083        }
6084    }
6085
6086    private static final boolean isPackageFilename(String name) {
6087        return name != null && name.endsWith(".apk");
6088    }
6089
6090    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6091        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6092            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6093                return true;
6094            }
6095        }
6096        return false;
6097    }
6098
6099    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6100    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6101    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6102
6103    private void updatePermissionsLPw(String changingPkg,
6104            PackageParser.Package pkgInfo, int flags) {
6105        // Make sure there are no dangling permission trees.
6106        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6107        while (it.hasNext()) {
6108            final BasePermission bp = it.next();
6109            if (bp.packageSetting == null) {
6110                // We may not yet have parsed the package, so just see if
6111                // we still know about its settings.
6112                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6113            }
6114            if (bp.packageSetting == null) {
6115                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6116                        + " from package " + bp.sourcePackage);
6117                it.remove();
6118            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6119                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6120                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6121                            + " from package " + bp.sourcePackage);
6122                    flags |= UPDATE_PERMISSIONS_ALL;
6123                    it.remove();
6124                }
6125            }
6126        }
6127
6128        // Make sure all dynamic permissions have been assigned to a package,
6129        // and make sure there are no dangling permissions.
6130        it = mSettings.mPermissions.values().iterator();
6131        while (it.hasNext()) {
6132            final BasePermission bp = it.next();
6133            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6134                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6135                        + bp.name + " pkg=" + bp.sourcePackage
6136                        + " info=" + bp.pendingInfo);
6137                if (bp.packageSetting == null && bp.pendingInfo != null) {
6138                    final BasePermission tree = findPermissionTreeLP(bp.name);
6139                    if (tree != null && tree.perm != null) {
6140                        bp.packageSetting = tree.packageSetting;
6141                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6142                                new PermissionInfo(bp.pendingInfo));
6143                        bp.perm.info.packageName = tree.perm.info.packageName;
6144                        bp.perm.info.name = bp.name;
6145                        bp.uid = tree.uid;
6146                    }
6147                }
6148            }
6149            if (bp.packageSetting == null) {
6150                // We may not yet have parsed the package, so just see if
6151                // we still know about its settings.
6152                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6153            }
6154            if (bp.packageSetting == null) {
6155                Slog.w(TAG, "Removing dangling permission: " + bp.name
6156                        + " from package " + bp.sourcePackage);
6157                it.remove();
6158            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6159                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6160                    Slog.i(TAG, "Removing old permission: " + bp.name
6161                            + " from package " + bp.sourcePackage);
6162                    flags |= UPDATE_PERMISSIONS_ALL;
6163                    it.remove();
6164                }
6165            }
6166        }
6167
6168        // Now update the permissions for all packages, in particular
6169        // replace the granted permissions of the system packages.
6170        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6171            for (PackageParser.Package pkg : mPackages.values()) {
6172                if (pkg != pkgInfo) {
6173                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6174                }
6175            }
6176        }
6177
6178        if (pkgInfo != null) {
6179            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6180        }
6181    }
6182
6183    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6184        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6185        if (ps == null) {
6186            return;
6187        }
6188        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6189        HashSet<String> origPermissions = gp.grantedPermissions;
6190        boolean changedPermission = false;
6191
6192        if (replace) {
6193            ps.permissionsFixed = false;
6194            if (gp == ps) {
6195                origPermissions = new HashSet<String>(gp.grantedPermissions);
6196                gp.grantedPermissions.clear();
6197                gp.gids = mGlobalGids;
6198            }
6199        }
6200
6201        if (gp.gids == null) {
6202            gp.gids = mGlobalGids;
6203        }
6204
6205        final int N = pkg.requestedPermissions.size();
6206        for (int i=0; i<N; i++) {
6207            final String name = pkg.requestedPermissions.get(i);
6208            final boolean required = pkg.requestedPermissionsRequired.get(i);
6209            final BasePermission bp = mSettings.mPermissions.get(name);
6210            if (DEBUG_INSTALL) {
6211                if (gp != ps) {
6212                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6213                }
6214            }
6215
6216            if (bp == null || bp.packageSetting == null) {
6217                Slog.w(TAG, "Unknown permission " + name
6218                        + " in package " + pkg.packageName);
6219                continue;
6220            }
6221
6222            final String perm = bp.name;
6223            boolean allowed;
6224            boolean allowedSig = false;
6225            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6226            if (level == PermissionInfo.PROTECTION_NORMAL
6227                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6228                // We grant a normal or dangerous permission if any of the following
6229                // are true:
6230                // 1) The permission is required
6231                // 2) The permission is optional, but was granted in the past
6232                // 3) The permission is optional, but was requested by an
6233                //    app in /system (not /data)
6234                //
6235                // Otherwise, reject the permission.
6236                allowed = (required || origPermissions.contains(perm)
6237                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6238            } else if (bp.packageSetting == null) {
6239                // This permission is invalid; skip it.
6240                allowed = false;
6241            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6242                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6243                if (allowed) {
6244                    allowedSig = true;
6245                }
6246            } else {
6247                allowed = false;
6248            }
6249            if (DEBUG_INSTALL) {
6250                if (gp != ps) {
6251                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6252                }
6253            }
6254            if (allowed) {
6255                if (!isSystemApp(ps) && ps.permissionsFixed) {
6256                    // If this is an existing, non-system package, then
6257                    // we can't add any new permissions to it.
6258                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6259                        // Except...  if this is a permission that was added
6260                        // to the platform (note: need to only do this when
6261                        // updating the platform).
6262                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6263                    }
6264                }
6265                if (allowed) {
6266                    if (!gp.grantedPermissions.contains(perm)) {
6267                        changedPermission = true;
6268                        gp.grantedPermissions.add(perm);
6269                        gp.gids = appendInts(gp.gids, bp.gids);
6270                    } else if (!ps.haveGids) {
6271                        gp.gids = appendInts(gp.gids, bp.gids);
6272                    }
6273                } else {
6274                    Slog.w(TAG, "Not granting permission " + perm
6275                            + " to package " + pkg.packageName
6276                            + " because it was previously installed without");
6277                }
6278            } else {
6279                if (gp.grantedPermissions.remove(perm)) {
6280                    changedPermission = true;
6281                    gp.gids = removeInts(gp.gids, bp.gids);
6282                    Slog.i(TAG, "Un-granting permission " + perm
6283                            + " from package " + pkg.packageName
6284                            + " (protectionLevel=" + bp.protectionLevel
6285                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6286                            + ")");
6287                } else {
6288                    Slog.w(TAG, "Not granting permission " + perm
6289                            + " to package " + pkg.packageName
6290                            + " (protectionLevel=" + bp.protectionLevel
6291                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6292                            + ")");
6293                }
6294            }
6295        }
6296
6297        if ((changedPermission || replace) && !ps.permissionsFixed &&
6298                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6299            // This is the first that we have heard about this package, so the
6300            // permissions we have now selected are fixed until explicitly
6301            // changed.
6302            ps.permissionsFixed = true;
6303        }
6304        ps.haveGids = true;
6305    }
6306
6307    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6308        boolean allowed = false;
6309        final int NP = PackageParser.NEW_PERMISSIONS.length;
6310        for (int ip=0; ip<NP; ip++) {
6311            final PackageParser.NewPermissionInfo npi
6312                    = PackageParser.NEW_PERMISSIONS[ip];
6313            if (npi.name.equals(perm)
6314                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6315                allowed = true;
6316                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6317                        + pkg.packageName);
6318                break;
6319            }
6320        }
6321        return allowed;
6322    }
6323
6324    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6325                                          BasePermission bp, HashSet<String> origPermissions) {
6326        boolean allowed;
6327        allowed = (compareSignatures(
6328                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6329                        == PackageManager.SIGNATURE_MATCH)
6330                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6331                        == PackageManager.SIGNATURE_MATCH);
6332        if (!allowed && (bp.protectionLevel
6333                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6334            if (isSystemApp(pkg)) {
6335                // For updated system applications, a system permission
6336                // is granted only if it had been defined by the original application.
6337                if (isUpdatedSystemApp(pkg)) {
6338                    final PackageSetting sysPs = mSettings
6339                            .getDisabledSystemPkgLPr(pkg.packageName);
6340                    final GrantedPermissions origGp = sysPs.sharedUser != null
6341                            ? sysPs.sharedUser : sysPs;
6342
6343                    if (origGp.grantedPermissions.contains(perm)) {
6344                        // If the original was granted this permission, we take
6345                        // that grant decision as read and propagate it to the
6346                        // update.
6347                        allowed = true;
6348                    } else {
6349                        // The system apk may have been updated with an older
6350                        // version of the one on the data partition, but which
6351                        // granted a new system permission that it didn't have
6352                        // before.  In this case we do want to allow the app to
6353                        // now get the new permission if the ancestral apk is
6354                        // privileged to get it.
6355                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6356                            for (int j=0;
6357                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6358                                if (perm.equals(
6359                                        sysPs.pkg.requestedPermissions.get(j))) {
6360                                    allowed = true;
6361                                    break;
6362                                }
6363                            }
6364                        }
6365                    }
6366                } else {
6367                    allowed = isPrivilegedApp(pkg);
6368                }
6369            }
6370        }
6371        if (!allowed && (bp.protectionLevel
6372                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6373            // For development permissions, a development permission
6374            // is granted only if it was already granted.
6375            allowed = origPermissions.contains(perm);
6376        }
6377        return allowed;
6378    }
6379
6380    final class ActivityIntentResolver
6381            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6382        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6383                boolean defaultOnly, int userId) {
6384            if (!sUserManager.exists(userId)) return null;
6385            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6386            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6387        }
6388
6389        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6390                int userId) {
6391            if (!sUserManager.exists(userId)) return null;
6392            mFlags = flags;
6393            return super.queryIntent(intent, resolvedType,
6394                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6395        }
6396
6397        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6398                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6399            if (!sUserManager.exists(userId)) return null;
6400            if (packageActivities == null) {
6401                return null;
6402            }
6403            mFlags = flags;
6404            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6405            final int N = packageActivities.size();
6406            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6407                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6408
6409            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6410            for (int i = 0; i < N; ++i) {
6411                intentFilters = packageActivities.get(i).intents;
6412                if (intentFilters != null && intentFilters.size() > 0) {
6413                    PackageParser.ActivityIntentInfo[] array =
6414                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6415                    intentFilters.toArray(array);
6416                    listCut.add(array);
6417                }
6418            }
6419            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6420        }
6421
6422        public final void addActivity(PackageParser.Activity a, String type) {
6423            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6424            mActivities.put(a.getComponentName(), a);
6425            if (DEBUG_SHOW_INFO)
6426                Log.v(
6427                TAG, "  " + type + " " +
6428                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6429            if (DEBUG_SHOW_INFO)
6430                Log.v(TAG, "    Class=" + a.info.name);
6431            final int NI = a.intents.size();
6432            for (int j=0; j<NI; j++) {
6433                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6434                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6435                    intent.setPriority(0);
6436                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6437                            + a.className + " with priority > 0, forcing to 0");
6438                }
6439                if (DEBUG_SHOW_INFO) {
6440                    Log.v(TAG, "    IntentFilter:");
6441                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6442                }
6443                if (!intent.debugCheck()) {
6444                    Log.w(TAG, "==> For Activity " + a.info.name);
6445                }
6446                addFilter(intent);
6447            }
6448        }
6449
6450        public final void removeActivity(PackageParser.Activity a, String type) {
6451            mActivities.remove(a.getComponentName());
6452            if (DEBUG_SHOW_INFO) {
6453                Log.v(TAG, "  " + type + " "
6454                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6455                                : a.info.name) + ":");
6456                Log.v(TAG, "    Class=" + a.info.name);
6457            }
6458            final int NI = a.intents.size();
6459            for (int j=0; j<NI; j++) {
6460                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6461                if (DEBUG_SHOW_INFO) {
6462                    Log.v(TAG, "    IntentFilter:");
6463                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6464                }
6465                removeFilter(intent);
6466            }
6467        }
6468
6469        @Override
6470        protected boolean allowFilterResult(
6471                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6472            ActivityInfo filterAi = filter.activity.info;
6473            for (int i=dest.size()-1; i>=0; i--) {
6474                ActivityInfo destAi = dest.get(i).activityInfo;
6475                if (destAi.name == filterAi.name
6476                        && destAi.packageName == filterAi.packageName) {
6477                    return false;
6478                }
6479            }
6480            return true;
6481        }
6482
6483        @Override
6484        protected ActivityIntentInfo[] newArray(int size) {
6485            return new ActivityIntentInfo[size];
6486        }
6487
6488        @Override
6489        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6490            if (!sUserManager.exists(userId)) return true;
6491            PackageParser.Package p = filter.activity.owner;
6492            if (p != null) {
6493                PackageSetting ps = (PackageSetting)p.mExtras;
6494                if (ps != null) {
6495                    // System apps are never considered stopped for purposes of
6496                    // filtering, because there may be no way for the user to
6497                    // actually re-launch them.
6498                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6499                            && ps.getStopped(userId);
6500                }
6501            }
6502            return false;
6503        }
6504
6505        @Override
6506        protected boolean isPackageForFilter(String packageName,
6507                PackageParser.ActivityIntentInfo info) {
6508            return packageName.equals(info.activity.owner.packageName);
6509        }
6510
6511        @Override
6512        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6513                int match, int userId) {
6514            if (!sUserManager.exists(userId)) return null;
6515            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6516                return null;
6517            }
6518            final PackageParser.Activity activity = info.activity;
6519            if (mSafeMode && (activity.info.applicationInfo.flags
6520                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6521                return null;
6522            }
6523            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6524            if (ps == null) {
6525                return null;
6526            }
6527            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6528                    ps.readUserState(userId), userId);
6529            if (ai == null) {
6530                return null;
6531            }
6532            final ResolveInfo res = new ResolveInfo();
6533            res.activityInfo = ai;
6534            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6535                res.filter = info;
6536            }
6537            res.priority = info.getPriority();
6538            res.preferredOrder = activity.owner.mPreferredOrder;
6539            //System.out.println("Result: " + res.activityInfo.className +
6540            //                   " = " + res.priority);
6541            res.match = match;
6542            res.isDefault = info.hasDefault;
6543            res.labelRes = info.labelRes;
6544            res.nonLocalizedLabel = info.nonLocalizedLabel;
6545            res.icon = info.icon;
6546            res.system = isSystemApp(res.activityInfo.applicationInfo);
6547            return res;
6548        }
6549
6550        @Override
6551        protected void sortResults(List<ResolveInfo> results) {
6552            Collections.sort(results, mResolvePrioritySorter);
6553        }
6554
6555        @Override
6556        protected void dumpFilter(PrintWriter out, String prefix,
6557                PackageParser.ActivityIntentInfo filter) {
6558            out.print(prefix); out.print(
6559                    Integer.toHexString(System.identityHashCode(filter.activity)));
6560                    out.print(' ');
6561                    filter.activity.printComponentShortName(out);
6562                    out.print(" filter ");
6563                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6564        }
6565
6566//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6567//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6568//            final List<ResolveInfo> retList = Lists.newArrayList();
6569//            while (i.hasNext()) {
6570//                final ResolveInfo resolveInfo = i.next();
6571//                if (isEnabledLP(resolveInfo.activityInfo)) {
6572//                    retList.add(resolveInfo);
6573//                }
6574//            }
6575//            return retList;
6576//        }
6577
6578        // Keys are String (activity class name), values are Activity.
6579        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6580                = new HashMap<ComponentName, PackageParser.Activity>();
6581        private int mFlags;
6582    }
6583
6584    private final class ServiceIntentResolver
6585            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6586        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6587                boolean defaultOnly, int userId) {
6588            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6589            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6590        }
6591
6592        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6593                int userId) {
6594            if (!sUserManager.exists(userId)) return null;
6595            mFlags = flags;
6596            return super.queryIntent(intent, resolvedType,
6597                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6598        }
6599
6600        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6601                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6602            if (!sUserManager.exists(userId)) return null;
6603            if (packageServices == null) {
6604                return null;
6605            }
6606            mFlags = flags;
6607            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6608            final int N = packageServices.size();
6609            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6610                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6611
6612            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6613            for (int i = 0; i < N; ++i) {
6614                intentFilters = packageServices.get(i).intents;
6615                if (intentFilters != null && intentFilters.size() > 0) {
6616                    PackageParser.ServiceIntentInfo[] array =
6617                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6618                    intentFilters.toArray(array);
6619                    listCut.add(array);
6620                }
6621            }
6622            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6623        }
6624
6625        public final void addService(PackageParser.Service s) {
6626            mServices.put(s.getComponentName(), s);
6627            if (DEBUG_SHOW_INFO) {
6628                Log.v(TAG, "  "
6629                        + (s.info.nonLocalizedLabel != null
6630                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6631                Log.v(TAG, "    Class=" + s.info.name);
6632            }
6633            final int NI = s.intents.size();
6634            int j;
6635            for (j=0; j<NI; j++) {
6636                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6637                if (DEBUG_SHOW_INFO) {
6638                    Log.v(TAG, "    IntentFilter:");
6639                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6640                }
6641                if (!intent.debugCheck()) {
6642                    Log.w(TAG, "==> For Service " + s.info.name);
6643                }
6644                addFilter(intent);
6645            }
6646        }
6647
6648        public final void removeService(PackageParser.Service s) {
6649            mServices.remove(s.getComponentName());
6650            if (DEBUG_SHOW_INFO) {
6651                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6652                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6653                Log.v(TAG, "    Class=" + s.info.name);
6654            }
6655            final int NI = s.intents.size();
6656            int j;
6657            for (j=0; j<NI; j++) {
6658                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6659                if (DEBUG_SHOW_INFO) {
6660                    Log.v(TAG, "    IntentFilter:");
6661                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6662                }
6663                removeFilter(intent);
6664            }
6665        }
6666
6667        @Override
6668        protected boolean allowFilterResult(
6669                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6670            ServiceInfo filterSi = filter.service.info;
6671            for (int i=dest.size()-1; i>=0; i--) {
6672                ServiceInfo destAi = dest.get(i).serviceInfo;
6673                if (destAi.name == filterSi.name
6674                        && destAi.packageName == filterSi.packageName) {
6675                    return false;
6676                }
6677            }
6678            return true;
6679        }
6680
6681        @Override
6682        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6683            return new PackageParser.ServiceIntentInfo[size];
6684        }
6685
6686        @Override
6687        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6688            if (!sUserManager.exists(userId)) return true;
6689            PackageParser.Package p = filter.service.owner;
6690            if (p != null) {
6691                PackageSetting ps = (PackageSetting)p.mExtras;
6692                if (ps != null) {
6693                    // System apps are never considered stopped for purposes of
6694                    // filtering, because there may be no way for the user to
6695                    // actually re-launch them.
6696                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6697                            && ps.getStopped(userId);
6698                }
6699            }
6700            return false;
6701        }
6702
6703        @Override
6704        protected boolean isPackageForFilter(String packageName,
6705                PackageParser.ServiceIntentInfo info) {
6706            return packageName.equals(info.service.owner.packageName);
6707        }
6708
6709        @Override
6710        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6711                int match, int userId) {
6712            if (!sUserManager.exists(userId)) return null;
6713            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6714            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6715                return null;
6716            }
6717            final PackageParser.Service service = info.service;
6718            if (mSafeMode && (service.info.applicationInfo.flags
6719                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6720                return null;
6721            }
6722            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6723            if (ps == null) {
6724                return null;
6725            }
6726            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6727                    ps.readUserState(userId), userId);
6728            if (si == null) {
6729                return null;
6730            }
6731            final ResolveInfo res = new ResolveInfo();
6732            res.serviceInfo = si;
6733            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6734                res.filter = filter;
6735            }
6736            res.priority = info.getPriority();
6737            res.preferredOrder = service.owner.mPreferredOrder;
6738            //System.out.println("Result: " + res.activityInfo.className +
6739            //                   " = " + res.priority);
6740            res.match = match;
6741            res.isDefault = info.hasDefault;
6742            res.labelRes = info.labelRes;
6743            res.nonLocalizedLabel = info.nonLocalizedLabel;
6744            res.icon = info.icon;
6745            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6746            return res;
6747        }
6748
6749        @Override
6750        protected void sortResults(List<ResolveInfo> results) {
6751            Collections.sort(results, mResolvePrioritySorter);
6752        }
6753
6754        @Override
6755        protected void dumpFilter(PrintWriter out, String prefix,
6756                PackageParser.ServiceIntentInfo filter) {
6757            out.print(prefix); out.print(
6758                    Integer.toHexString(System.identityHashCode(filter.service)));
6759                    out.print(' ');
6760                    filter.service.printComponentShortName(out);
6761                    out.print(" filter ");
6762                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6763        }
6764
6765//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6766//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6767//            final List<ResolveInfo> retList = Lists.newArrayList();
6768//            while (i.hasNext()) {
6769//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6770//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6771//                    retList.add(resolveInfo);
6772//                }
6773//            }
6774//            return retList;
6775//        }
6776
6777        // Keys are String (activity class name), values are Activity.
6778        private final HashMap<ComponentName, PackageParser.Service> mServices
6779                = new HashMap<ComponentName, PackageParser.Service>();
6780        private int mFlags;
6781    };
6782
6783    private final class ProviderIntentResolver
6784            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6785        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6786                boolean defaultOnly, int userId) {
6787            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6788            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6789        }
6790
6791        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6792                int userId) {
6793            if (!sUserManager.exists(userId))
6794                return null;
6795            mFlags = flags;
6796            return super.queryIntent(intent, resolvedType,
6797                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6798        }
6799
6800        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6801                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6802            if (!sUserManager.exists(userId))
6803                return null;
6804            if (packageProviders == null) {
6805                return null;
6806            }
6807            mFlags = flags;
6808            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6809            final int N = packageProviders.size();
6810            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6811                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6812
6813            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6814            for (int i = 0; i < N; ++i) {
6815                intentFilters = packageProviders.get(i).intents;
6816                if (intentFilters != null && intentFilters.size() > 0) {
6817                    PackageParser.ProviderIntentInfo[] array =
6818                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6819                    intentFilters.toArray(array);
6820                    listCut.add(array);
6821                }
6822            }
6823            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6824        }
6825
6826        public final void addProvider(PackageParser.Provider p) {
6827            if (mProviders.containsKey(p.getComponentName())) {
6828                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6829                return;
6830            }
6831
6832            mProviders.put(p.getComponentName(), p);
6833            if (DEBUG_SHOW_INFO) {
6834                Log.v(TAG, "  "
6835                        + (p.info.nonLocalizedLabel != null
6836                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6837                Log.v(TAG, "    Class=" + p.info.name);
6838            }
6839            final int NI = p.intents.size();
6840            int j;
6841            for (j = 0; j < NI; j++) {
6842                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6843                if (DEBUG_SHOW_INFO) {
6844                    Log.v(TAG, "    IntentFilter:");
6845                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6846                }
6847                if (!intent.debugCheck()) {
6848                    Log.w(TAG, "==> For Provider " + p.info.name);
6849                }
6850                addFilter(intent);
6851            }
6852        }
6853
6854        public final void removeProvider(PackageParser.Provider p) {
6855            mProviders.remove(p.getComponentName());
6856            if (DEBUG_SHOW_INFO) {
6857                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6858                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6859                Log.v(TAG, "    Class=" + p.info.name);
6860            }
6861            final int NI = p.intents.size();
6862            int j;
6863            for (j = 0; j < NI; j++) {
6864                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6865                if (DEBUG_SHOW_INFO) {
6866                    Log.v(TAG, "    IntentFilter:");
6867                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6868                }
6869                removeFilter(intent);
6870            }
6871        }
6872
6873        @Override
6874        protected boolean allowFilterResult(
6875                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6876            ProviderInfo filterPi = filter.provider.info;
6877            for (int i = dest.size() - 1; i >= 0; i--) {
6878                ProviderInfo destPi = dest.get(i).providerInfo;
6879                if (destPi.name == filterPi.name
6880                        && destPi.packageName == filterPi.packageName) {
6881                    return false;
6882                }
6883            }
6884            return true;
6885        }
6886
6887        @Override
6888        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6889            return new PackageParser.ProviderIntentInfo[size];
6890        }
6891
6892        @Override
6893        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6894            if (!sUserManager.exists(userId))
6895                return true;
6896            PackageParser.Package p = filter.provider.owner;
6897            if (p != null) {
6898                PackageSetting ps = (PackageSetting) p.mExtras;
6899                if (ps != null) {
6900                    // System apps are never considered stopped for purposes of
6901                    // filtering, because there may be no way for the user to
6902                    // actually re-launch them.
6903                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6904                            && ps.getStopped(userId);
6905                }
6906            }
6907            return false;
6908        }
6909
6910        @Override
6911        protected boolean isPackageForFilter(String packageName,
6912                PackageParser.ProviderIntentInfo info) {
6913            return packageName.equals(info.provider.owner.packageName);
6914        }
6915
6916        @Override
6917        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6918                int match, int userId) {
6919            if (!sUserManager.exists(userId))
6920                return null;
6921            final PackageParser.ProviderIntentInfo info = filter;
6922            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6923                return null;
6924            }
6925            final PackageParser.Provider provider = info.provider;
6926            if (mSafeMode && (provider.info.applicationInfo.flags
6927                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6928                return null;
6929            }
6930            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6931            if (ps == null) {
6932                return null;
6933            }
6934            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6935                    ps.readUserState(userId), userId);
6936            if (pi == null) {
6937                return null;
6938            }
6939            final ResolveInfo res = new ResolveInfo();
6940            res.providerInfo = pi;
6941            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6942                res.filter = filter;
6943            }
6944            res.priority = info.getPriority();
6945            res.preferredOrder = provider.owner.mPreferredOrder;
6946            res.match = match;
6947            res.isDefault = info.hasDefault;
6948            res.labelRes = info.labelRes;
6949            res.nonLocalizedLabel = info.nonLocalizedLabel;
6950            res.icon = info.icon;
6951            res.system = isSystemApp(res.providerInfo.applicationInfo);
6952            return res;
6953        }
6954
6955        @Override
6956        protected void sortResults(List<ResolveInfo> results) {
6957            Collections.sort(results, mResolvePrioritySorter);
6958        }
6959
6960        @Override
6961        protected void dumpFilter(PrintWriter out, String prefix,
6962                PackageParser.ProviderIntentInfo filter) {
6963            out.print(prefix);
6964            out.print(
6965                    Integer.toHexString(System.identityHashCode(filter.provider)));
6966            out.print(' ');
6967            filter.provider.printComponentShortName(out);
6968            out.print(" filter ");
6969            out.println(Integer.toHexString(System.identityHashCode(filter)));
6970        }
6971
6972        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6973                = new HashMap<ComponentName, PackageParser.Provider>();
6974        private int mFlags;
6975    };
6976
6977    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6978            new Comparator<ResolveInfo>() {
6979        public int compare(ResolveInfo r1, ResolveInfo r2) {
6980            int v1 = r1.priority;
6981            int v2 = r2.priority;
6982            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6983            if (v1 != v2) {
6984                return (v1 > v2) ? -1 : 1;
6985            }
6986            v1 = r1.preferredOrder;
6987            v2 = r2.preferredOrder;
6988            if (v1 != v2) {
6989                return (v1 > v2) ? -1 : 1;
6990            }
6991            if (r1.isDefault != r2.isDefault) {
6992                return r1.isDefault ? -1 : 1;
6993            }
6994            v1 = r1.match;
6995            v2 = r2.match;
6996            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6997            if (v1 != v2) {
6998                return (v1 > v2) ? -1 : 1;
6999            }
7000            if (r1.system != r2.system) {
7001                return r1.system ? -1 : 1;
7002            }
7003            return 0;
7004        }
7005    };
7006
7007    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7008            new Comparator<ProviderInfo>() {
7009        public int compare(ProviderInfo p1, ProviderInfo p2) {
7010            final int v1 = p1.initOrder;
7011            final int v2 = p2.initOrder;
7012            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7013        }
7014    };
7015
7016    static final void sendPackageBroadcast(String action, String pkg,
7017            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7018            int[] userIds) {
7019        IActivityManager am = ActivityManagerNative.getDefault();
7020        if (am != null) {
7021            try {
7022                if (userIds == null) {
7023                    userIds = am.getRunningUserIds();
7024                }
7025                for (int id : userIds) {
7026                    final Intent intent = new Intent(action,
7027                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7028                    if (extras != null) {
7029                        intent.putExtras(extras);
7030                    }
7031                    if (targetPkg != null) {
7032                        intent.setPackage(targetPkg);
7033                    }
7034                    // Modify the UID when posting to other users
7035                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7036                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7037                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7038                        intent.putExtra(Intent.EXTRA_UID, uid);
7039                    }
7040                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7041                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7042                    if (DEBUG_BROADCASTS) {
7043                        RuntimeException here = new RuntimeException("here");
7044                        here.fillInStackTrace();
7045                        Slog.d(TAG, "Sending to user " + id + ": "
7046                                + intent.toShortString(false, true, false, false)
7047                                + " " + intent.getExtras(), here);
7048                    }
7049                    am.broadcastIntent(null, intent, null, finishedReceiver,
7050                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7051                            finishedReceiver != null, false, id);
7052                }
7053            } catch (RemoteException ex) {
7054            }
7055        }
7056    }
7057
7058    /**
7059     * Check if the external storage media is available. This is true if there
7060     * is a mounted external storage medium or if the external storage is
7061     * emulated.
7062     */
7063    private boolean isExternalMediaAvailable() {
7064        return mMediaMounted || Environment.isExternalStorageEmulated();
7065    }
7066
7067    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7068        // writer
7069        synchronized (mPackages) {
7070            if (!isExternalMediaAvailable()) {
7071                // If the external storage is no longer mounted at this point,
7072                // the caller may not have been able to delete all of this
7073                // packages files and can not delete any more.  Bail.
7074                return null;
7075            }
7076            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7077            if (lastPackage != null) {
7078                pkgs.remove(lastPackage);
7079            }
7080            if (pkgs.size() > 0) {
7081                return pkgs.get(0);
7082            }
7083        }
7084        return null;
7085    }
7086
7087    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7088        if (false) {
7089            RuntimeException here = new RuntimeException("here");
7090            here.fillInStackTrace();
7091            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7092                    + " andCode=" + andCode, here);
7093        }
7094        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7095                userId, andCode ? 1 : 0, packageName));
7096    }
7097
7098    void startCleaningPackages() {
7099        // reader
7100        synchronized (mPackages) {
7101            if (!isExternalMediaAvailable()) {
7102                return;
7103            }
7104            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7105                return;
7106            }
7107        }
7108        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7109        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7110        IActivityManager am = ActivityManagerNative.getDefault();
7111        if (am != null) {
7112            try {
7113                am.startService(null, intent, null, UserHandle.USER_OWNER);
7114            } catch (RemoteException e) {
7115            }
7116        }
7117    }
7118
7119    private final class AppDirObserver extends FileObserver {
7120        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7121            super(path, mask);
7122            mRootDir = path;
7123            mIsRom = isrom;
7124            mIsPrivileged = isPrivileged;
7125        }
7126
7127        public void onEvent(int event, String path) {
7128            String removedPackage = null;
7129            int removedAppId = -1;
7130            int[] removedUsers = null;
7131            String addedPackage = null;
7132            int addedAppId = -1;
7133            int[] addedUsers = null;
7134
7135            // TODO post a message to the handler to obtain serial ordering
7136            synchronized (mInstallLock) {
7137                String fullPathStr = null;
7138                File fullPath = null;
7139                if (path != null) {
7140                    fullPath = new File(mRootDir, path);
7141                    fullPathStr = fullPath.getPath();
7142                }
7143
7144                if (DEBUG_APP_DIR_OBSERVER)
7145                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7146
7147                if (!isPackageFilename(path)) {
7148                    if (DEBUG_APP_DIR_OBSERVER)
7149                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7150                    return;
7151                }
7152
7153                // Ignore packages that are being installed or
7154                // have just been installed.
7155                if (ignoreCodePath(fullPathStr)) {
7156                    return;
7157                }
7158                PackageParser.Package p = null;
7159                PackageSetting ps = null;
7160                // reader
7161                synchronized (mPackages) {
7162                    p = mAppDirs.get(fullPathStr);
7163                    if (p != null) {
7164                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7165                        if (ps != null) {
7166                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7167                        } else {
7168                            removedUsers = sUserManager.getUserIds();
7169                        }
7170                    }
7171                    addedUsers = sUserManager.getUserIds();
7172                }
7173                if ((event&REMOVE_EVENTS) != 0) {
7174                    if (ps != null) {
7175                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7176                        removePackageLI(ps, true);
7177                        removedPackage = ps.name;
7178                        removedAppId = ps.appId;
7179                    }
7180                }
7181
7182                if ((event&ADD_EVENTS) != 0) {
7183                    if (p == null) {
7184                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7185                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7186                        if (mIsRom) {
7187                            flags |= PackageParser.PARSE_IS_SYSTEM
7188                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7189                            if (mIsPrivileged) {
7190                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7191                            }
7192                        }
7193                        p = scanPackageLI(fullPath, flags,
7194                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7195                                System.currentTimeMillis(), UserHandle.ALL);
7196                        if (p != null) {
7197                            /*
7198                             * TODO this seems dangerous as the package may have
7199                             * changed since we last acquired the mPackages
7200                             * lock.
7201                             */
7202                            // writer
7203                            synchronized (mPackages) {
7204                                updatePermissionsLPw(p.packageName, p,
7205                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7206                            }
7207                            addedPackage = p.applicationInfo.packageName;
7208                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7209                        }
7210                    }
7211                }
7212
7213                // reader
7214                synchronized (mPackages) {
7215                    mSettings.writeLPr();
7216                }
7217            }
7218
7219            if (removedPackage != null) {
7220                Bundle extras = new Bundle(1);
7221                extras.putInt(Intent.EXTRA_UID, removedAppId);
7222                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7223                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7224                        extras, null, null, removedUsers);
7225            }
7226            if (addedPackage != null) {
7227                Bundle extras = new Bundle(1);
7228                extras.putInt(Intent.EXTRA_UID, addedAppId);
7229                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7230                        extras, null, null, addedUsers);
7231            }
7232        }
7233
7234        private final String mRootDir;
7235        private final boolean mIsRom;
7236        private final boolean mIsPrivileged;
7237    }
7238
7239    /*
7240     * The old-style observer methods all just trampoline to the newer signature with
7241     * expanded install observer API.  The older API continues to work but does not
7242     * supply the additional details of the Observer2 API.
7243     */
7244
7245    /* Called when a downloaded package installation has been confirmed by the user */
7246    public void installPackage(
7247            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7248        installPackageEtc(packageURI, observer, null, flags, null);
7249    }
7250
7251    /* Called when a downloaded package installation has been confirmed by the user */
7252    public void installPackage(
7253            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7254            final String installerPackageName) {
7255        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7256                installerPackageName, null, null, null);
7257    }
7258
7259    @Override
7260    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7261            int flags, String installerPackageName, Uri verificationURI,
7262            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7263        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7264                VerificationParams.NO_UID, manifestDigest);
7265        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7266                installerPackageName, verificationParams, encryptionParams);
7267    }
7268
7269    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7270            IPackageInstallObserver observer, int flags, String installerPackageName,
7271            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7272        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7273                installerPackageName, verificationParams, encryptionParams);
7274    }
7275
7276    /*
7277     * And here are the "live" versions that take both observer arguments
7278     */
7279    public void installPackageEtc(
7280            final Uri packageURI, final IPackageInstallObserver observer,
7281            IPackageInstallObserver2 observer2, final int flags) {
7282        installPackageEtc(packageURI, observer, observer2, flags, null);
7283    }
7284
7285    public void installPackageEtc(
7286            final Uri packageURI, final IPackageInstallObserver observer,
7287            final IPackageInstallObserver2 observer2, final int flags,
7288            final String installerPackageName) {
7289        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7290                installerPackageName, null, null, null);
7291    }
7292
7293    @Override
7294    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7295            IPackageInstallObserver2 observer2,
7296            int flags, String installerPackageName, Uri verificationURI,
7297            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7298        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7299                VerificationParams.NO_UID, manifestDigest);
7300        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7301                installerPackageName, verificationParams, encryptionParams);
7302    }
7303
7304    /*
7305     * All of the installPackage...*() methods redirect to this one for the master implementation
7306     */
7307    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7308            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7309            int flags, String installerPackageName,
7310            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7311        if (observer == null && observer2 == null) {
7312            throw new IllegalArgumentException("No install observer supplied");
7313        }
7314        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7315                null);
7316
7317        final int uid = Binder.getCallingUid();
7318        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7319            try {
7320                if (observer != null) {
7321                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7322                }
7323                if (observer2 != null) {
7324                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7325                }
7326            } catch (RemoteException re) {
7327            }
7328            return;
7329        }
7330
7331        UserHandle user;
7332        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7333            user = UserHandle.ALL;
7334        } else {
7335            user = new UserHandle(UserHandle.getUserId(uid));
7336        }
7337
7338        final int filteredFlags;
7339
7340        if (uid == Process.SHELL_UID || uid == 0) {
7341            if (DEBUG_INSTALL) {
7342                Slog.v(TAG, "Install from ADB");
7343            }
7344            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7345        } else {
7346            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7347        }
7348
7349        verificationParams.setInstallerUid(uid);
7350
7351        final Message msg = mHandler.obtainMessage(INIT_COPY);
7352        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7353                installerPackageName, verificationParams, encryptionParams, user);
7354        mHandler.sendMessage(msg);
7355    }
7356
7357    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7358        Bundle extras = new Bundle(1);
7359        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7360
7361        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7362                packageName, extras, null, null, new int[] {userId});
7363        try {
7364            IActivityManager am = ActivityManagerNative.getDefault();
7365            final boolean isSystem =
7366                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7367            if (isSystem && am.isUserRunning(userId, false)) {
7368                // The just-installed/enabled app is bundled on the system, so presumed
7369                // to be able to run automatically without needing an explicit launch.
7370                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7371                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7372                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7373                        .setPackage(packageName);
7374                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7375                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7376            }
7377        } catch (RemoteException e) {
7378            // shouldn't happen
7379            Slog.w(TAG, "Unable to bootstrap installed package", e);
7380        }
7381    }
7382
7383    @Override
7384    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7385            int userId) {
7386        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7387        PackageSetting pkgSetting;
7388        final int uid = Binder.getCallingUid();
7389        if (UserHandle.getUserId(uid) != userId) {
7390            mContext.enforceCallingOrSelfPermission(
7391                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7392                    "setApplicationBlockedSetting for user " + userId);
7393        }
7394
7395        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7396            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7397            return false;
7398        }
7399
7400        long callingId = Binder.clearCallingIdentity();
7401        try {
7402            boolean sendAdded = false;
7403            boolean sendRemoved = false;
7404            // writer
7405            synchronized (mPackages) {
7406                pkgSetting = mSettings.mPackages.get(packageName);
7407                if (pkgSetting == null) {
7408                    return false;
7409                }
7410                if (pkgSetting.getBlocked(userId) != blocked) {
7411                    pkgSetting.setBlocked(blocked, userId);
7412                    mSettings.writePackageRestrictionsLPr(userId);
7413                    if (blocked) {
7414                        sendRemoved = true;
7415                    } else {
7416                        sendAdded = true;
7417                    }
7418                }
7419            }
7420            if (sendAdded) {
7421                sendPackageAddedForUser(packageName, pkgSetting, userId);
7422                return true;
7423            }
7424            if (sendRemoved) {
7425                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7426                        "blocking pkg");
7427                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7428            }
7429        } finally {
7430            Binder.restoreCallingIdentity(callingId);
7431        }
7432        return false;
7433    }
7434
7435    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7436            int userId) {
7437        final PackageRemovedInfo info = new PackageRemovedInfo();
7438        info.removedPackage = packageName;
7439        info.removedUsers = new int[] {userId};
7440        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7441        info.sendBroadcast(false, false, false);
7442    }
7443
7444    /**
7445     * Returns true if application is not found or there was an error. Otherwise it returns
7446     * the blocked state of the package for the given user.
7447     */
7448    @Override
7449    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7450        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7451        PackageSetting pkgSetting;
7452        final int uid = Binder.getCallingUid();
7453        if (UserHandle.getUserId(uid) != userId) {
7454            mContext.enforceCallingPermission(
7455                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7456                    "getApplicationBlocked for user " + userId);
7457        }
7458        long callingId = Binder.clearCallingIdentity();
7459        try {
7460            // writer
7461            synchronized (mPackages) {
7462                pkgSetting = mSettings.mPackages.get(packageName);
7463                if (pkgSetting == null) {
7464                    return true;
7465                }
7466                return pkgSetting.getBlocked(userId);
7467            }
7468        } finally {
7469            Binder.restoreCallingIdentity(callingId);
7470        }
7471    }
7472
7473    /**
7474     * @hide
7475     */
7476    @Override
7477    public int installExistingPackageAsUser(String packageName, int userId) {
7478        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7479                null);
7480        PackageSetting pkgSetting;
7481        final int uid = Binder.getCallingUid();
7482        if (UserHandle.getUserId(uid) != userId) {
7483            mContext.enforceCallingPermission(
7484                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7485                    "installExistingPackage for user " + userId);
7486        }
7487        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7488            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7489        }
7490
7491        long callingId = Binder.clearCallingIdentity();
7492        try {
7493            boolean sendAdded = false;
7494            Bundle extras = new Bundle(1);
7495
7496            // writer
7497            synchronized (mPackages) {
7498                pkgSetting = mSettings.mPackages.get(packageName);
7499                if (pkgSetting == null) {
7500                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7501                }
7502                if (!pkgSetting.getInstalled(userId)) {
7503                    pkgSetting.setInstalled(true, userId);
7504                    pkgSetting.setBlocked(false, userId);
7505                    mSettings.writePackageRestrictionsLPr(userId);
7506                    sendAdded = true;
7507                }
7508            }
7509
7510            if (sendAdded) {
7511                sendPackageAddedForUser(packageName, pkgSetting, userId);
7512            }
7513        } finally {
7514            Binder.restoreCallingIdentity(callingId);
7515        }
7516
7517        return PackageManager.INSTALL_SUCCEEDED;
7518    }
7519
7520    private boolean isUserRestricted(int userId, String restrictionKey) {
7521        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7522        if (restrictions.getBoolean(restrictionKey, false)) {
7523            Log.w(TAG, "User is restricted: " + restrictionKey);
7524            return true;
7525        }
7526        return false;
7527    }
7528
7529    @Override
7530    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7531        mContext.enforceCallingOrSelfPermission(
7532                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7533                "Only package verification agents can verify applications");
7534
7535        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7536        final PackageVerificationResponse response = new PackageVerificationResponse(
7537                verificationCode, Binder.getCallingUid());
7538        msg.arg1 = id;
7539        msg.obj = response;
7540        mHandler.sendMessage(msg);
7541    }
7542
7543    @Override
7544    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7545            long millisecondsToDelay) {
7546        mContext.enforceCallingOrSelfPermission(
7547                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7548                "Only package verification agents can extend verification timeouts");
7549
7550        final PackageVerificationState state = mPendingVerification.get(id);
7551        final PackageVerificationResponse response = new PackageVerificationResponse(
7552                verificationCodeAtTimeout, Binder.getCallingUid());
7553
7554        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7555            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7556        }
7557        if (millisecondsToDelay < 0) {
7558            millisecondsToDelay = 0;
7559        }
7560        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7561                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7562            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7563        }
7564
7565        if ((state != null) && !state.timeoutExtended()) {
7566            state.extendTimeout();
7567
7568            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7569            msg.arg1 = id;
7570            msg.obj = response;
7571            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7572        }
7573    }
7574
7575    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7576            int verificationCode, UserHandle user) {
7577        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7578        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7579        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7580        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7581        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7582
7583        mContext.sendBroadcastAsUser(intent, user,
7584                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7585    }
7586
7587    private ComponentName matchComponentForVerifier(String packageName,
7588            List<ResolveInfo> receivers) {
7589        ActivityInfo targetReceiver = null;
7590
7591        final int NR = receivers.size();
7592        for (int i = 0; i < NR; i++) {
7593            final ResolveInfo info = receivers.get(i);
7594            if (info.activityInfo == null) {
7595                continue;
7596            }
7597
7598            if (packageName.equals(info.activityInfo.packageName)) {
7599                targetReceiver = info.activityInfo;
7600                break;
7601            }
7602        }
7603
7604        if (targetReceiver == null) {
7605            return null;
7606        }
7607
7608        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7609    }
7610
7611    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7612            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7613        if (pkgInfo.verifiers.length == 0) {
7614            return null;
7615        }
7616
7617        final int N = pkgInfo.verifiers.length;
7618        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7619        for (int i = 0; i < N; i++) {
7620            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7621
7622            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7623                    receivers);
7624            if (comp == null) {
7625                continue;
7626            }
7627
7628            final int verifierUid = getUidForVerifier(verifierInfo);
7629            if (verifierUid == -1) {
7630                continue;
7631            }
7632
7633            if (DEBUG_VERIFY) {
7634                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7635                        + " with the correct signature");
7636            }
7637            sufficientVerifiers.add(comp);
7638            verificationState.addSufficientVerifier(verifierUid);
7639        }
7640
7641        return sufficientVerifiers;
7642    }
7643
7644    private int getUidForVerifier(VerifierInfo verifierInfo) {
7645        synchronized (mPackages) {
7646            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7647            if (pkg == null) {
7648                return -1;
7649            } else if (pkg.mSignatures.length != 1) {
7650                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7651                        + " has more than one signature; ignoring");
7652                return -1;
7653            }
7654
7655            /*
7656             * If the public key of the package's signature does not match
7657             * our expected public key, then this is a different package and
7658             * we should skip.
7659             */
7660
7661            final byte[] expectedPublicKey;
7662            try {
7663                final Signature verifierSig = pkg.mSignatures[0];
7664                final PublicKey publicKey = verifierSig.getPublicKey();
7665                expectedPublicKey = publicKey.getEncoded();
7666            } catch (CertificateException e) {
7667                return -1;
7668            }
7669
7670            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7671
7672            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7673                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7674                        + " does not have the expected public key; ignoring");
7675                return -1;
7676            }
7677
7678            return pkg.applicationInfo.uid;
7679        }
7680    }
7681
7682    public void finishPackageInstall(int token) {
7683        enforceSystemOrRoot("Only the system is allowed to finish installs");
7684
7685        if (DEBUG_INSTALL) {
7686            Slog.v(TAG, "BM finishing package install for " + token);
7687        }
7688
7689        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7690        mHandler.sendMessage(msg);
7691    }
7692
7693    /**
7694     * Get the verification agent timeout.
7695     *
7696     * @return verification timeout in milliseconds
7697     */
7698    private long getVerificationTimeout() {
7699        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7700                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7701                DEFAULT_VERIFICATION_TIMEOUT);
7702    }
7703
7704    /**
7705     * Get the default verification agent response code.
7706     *
7707     * @return default verification response code
7708     */
7709    private int getDefaultVerificationResponse() {
7710        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7711                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7712                DEFAULT_VERIFICATION_RESPONSE);
7713    }
7714
7715    /**
7716     * Check whether or not package verification has been enabled.
7717     *
7718     * @return true if verification should be performed
7719     */
7720    private boolean isVerificationEnabled(int flags) {
7721        if (!DEFAULT_VERIFY_ENABLE) {
7722            return false;
7723        }
7724
7725        // Check if installing from ADB
7726        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7727            // Do not run verification in a test harness environment
7728            if (ActivityManager.isRunningInTestHarness()) {
7729                return false;
7730            }
7731            // Check if the developer does not want package verification for ADB installs
7732            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7733                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7734                return false;
7735            }
7736        }
7737
7738        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7739                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7740    }
7741
7742    /**
7743     * Get the "allow unknown sources" setting.
7744     *
7745     * @return the current "allow unknown sources" setting
7746     */
7747    private int getUnknownSourcesSettings() {
7748        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7749                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7750                -1);
7751    }
7752
7753    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7754        final int uid = Binder.getCallingUid();
7755        // writer
7756        synchronized (mPackages) {
7757            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7758            if (targetPackageSetting == null) {
7759                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7760            }
7761
7762            PackageSetting installerPackageSetting;
7763            if (installerPackageName != null) {
7764                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7765                if (installerPackageSetting == null) {
7766                    throw new IllegalArgumentException("Unknown installer package: "
7767                            + installerPackageName);
7768                }
7769            } else {
7770                installerPackageSetting = null;
7771            }
7772
7773            Signature[] callerSignature;
7774            Object obj = mSettings.getUserIdLPr(uid);
7775            if (obj != null) {
7776                if (obj instanceof SharedUserSetting) {
7777                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7778                } else if (obj instanceof PackageSetting) {
7779                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7780                } else {
7781                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7782                }
7783            } else {
7784                throw new SecurityException("Unknown calling uid " + uid);
7785            }
7786
7787            // Verify: can't set installerPackageName to a package that is
7788            // not signed with the same cert as the caller.
7789            if (installerPackageSetting != null) {
7790                if (compareSignatures(callerSignature,
7791                        installerPackageSetting.signatures.mSignatures)
7792                        != PackageManager.SIGNATURE_MATCH) {
7793                    throw new SecurityException(
7794                            "Caller does not have same cert as new installer package "
7795                            + installerPackageName);
7796                }
7797            }
7798
7799            // Verify: if target already has an installer package, it must
7800            // be signed with the same cert as the caller.
7801            if (targetPackageSetting.installerPackageName != null) {
7802                PackageSetting setting = mSettings.mPackages.get(
7803                        targetPackageSetting.installerPackageName);
7804                // If the currently set package isn't valid, then it's always
7805                // okay to change it.
7806                if (setting != null) {
7807                    if (compareSignatures(callerSignature,
7808                            setting.signatures.mSignatures)
7809                            != PackageManager.SIGNATURE_MATCH) {
7810                        throw new SecurityException(
7811                                "Caller does not have same cert as old installer package "
7812                                + targetPackageSetting.installerPackageName);
7813                    }
7814                }
7815            }
7816
7817            // Okay!
7818            targetPackageSetting.installerPackageName = installerPackageName;
7819            scheduleWriteSettingsLocked();
7820        }
7821    }
7822
7823    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7824        // Queue up an async operation since the package installation may take a little while.
7825        mHandler.post(new Runnable() {
7826            public void run() {
7827                mHandler.removeCallbacks(this);
7828                 // Result object to be returned
7829                PackageInstalledInfo res = new PackageInstalledInfo();
7830                res.returnCode = currentStatus;
7831                res.uid = -1;
7832                res.pkg = null;
7833                res.removedInfo = new PackageRemovedInfo();
7834                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7835                    args.doPreInstall(res.returnCode);
7836                    synchronized (mInstallLock) {
7837                        installPackageLI(args, true, res);
7838                    }
7839                    args.doPostInstall(res.returnCode, res.uid);
7840                }
7841
7842                // A restore should be performed at this point if (a) the install
7843                // succeeded, (b) the operation is not an update, and (c) the new
7844                // package has a backupAgent defined.
7845                final boolean update = res.removedInfo.removedPackage != null;
7846                boolean doRestore = (!update
7847                        && res.pkg != null
7848                        && res.pkg.applicationInfo.backupAgentName != null);
7849
7850                // Set up the post-install work request bookkeeping.  This will be used
7851                // and cleaned up by the post-install event handling regardless of whether
7852                // there's a restore pass performed.  Token values are >= 1.
7853                int token;
7854                if (mNextInstallToken < 0) mNextInstallToken = 1;
7855                token = mNextInstallToken++;
7856
7857                PostInstallData data = new PostInstallData(args, res);
7858                mRunningInstalls.put(token, data);
7859                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7860
7861                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7862                    // Pass responsibility to the Backup Manager.  It will perform a
7863                    // restore if appropriate, then pass responsibility back to the
7864                    // Package Manager to run the post-install observer callbacks
7865                    // and broadcasts.
7866                    IBackupManager bm = IBackupManager.Stub.asInterface(
7867                            ServiceManager.getService(Context.BACKUP_SERVICE));
7868                    if (bm != null) {
7869                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7870                                + " to BM for possible restore");
7871                        try {
7872                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7873                        } catch (RemoteException e) {
7874                            // can't happen; the backup manager is local
7875                        } catch (Exception e) {
7876                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7877                            doRestore = false;
7878                        }
7879                    } else {
7880                        Slog.e(TAG, "Backup Manager not found!");
7881                        doRestore = false;
7882                    }
7883                }
7884
7885                if (!doRestore) {
7886                    // No restore possible, or the Backup Manager was mysteriously not
7887                    // available -- just fire the post-install work request directly.
7888                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7889                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7890                    mHandler.sendMessage(msg);
7891                }
7892            }
7893        });
7894    }
7895
7896    private abstract class HandlerParams {
7897        private static final int MAX_RETRIES = 4;
7898
7899        /**
7900         * Number of times startCopy() has been attempted and had a non-fatal
7901         * error.
7902         */
7903        private int mRetries = 0;
7904
7905        /** User handle for the user requesting the information or installation. */
7906        private final UserHandle mUser;
7907
7908        HandlerParams(UserHandle user) {
7909            mUser = user;
7910        }
7911
7912        UserHandle getUser() {
7913            return mUser;
7914        }
7915
7916        final boolean startCopy() {
7917            boolean res;
7918            try {
7919                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7920
7921                if (++mRetries > MAX_RETRIES) {
7922                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7923                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7924                    handleServiceError();
7925                    return false;
7926                } else {
7927                    handleStartCopy();
7928                    res = true;
7929                }
7930            } catch (RemoteException e) {
7931                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7932                mHandler.sendEmptyMessage(MCS_RECONNECT);
7933                res = false;
7934            }
7935            handleReturnCode();
7936            return res;
7937        }
7938
7939        final void serviceError() {
7940            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7941            handleServiceError();
7942            handleReturnCode();
7943        }
7944
7945        abstract void handleStartCopy() throws RemoteException;
7946        abstract void handleServiceError();
7947        abstract void handleReturnCode();
7948    }
7949
7950    class MeasureParams extends HandlerParams {
7951        private final PackageStats mStats;
7952        private boolean mSuccess;
7953
7954        private final IPackageStatsObserver mObserver;
7955
7956        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7957            super(new UserHandle(stats.userHandle));
7958            mObserver = observer;
7959            mStats = stats;
7960        }
7961
7962        @Override
7963        public String toString() {
7964            return "MeasureParams{"
7965                + Integer.toHexString(System.identityHashCode(this))
7966                + " " + mStats.packageName + "}";
7967        }
7968
7969        @Override
7970        void handleStartCopy() throws RemoteException {
7971            synchronized (mInstallLock) {
7972                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7973            }
7974
7975            if (mSuccess) {
7976                final boolean mounted;
7977                if (Environment.isExternalStorageEmulated()) {
7978                    mounted = true;
7979                } else {
7980                    final String status = Environment.getExternalStorageState();
7981                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
7982                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7983                }
7984
7985                if (mounted) {
7986                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7987
7988                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7989                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7990
7991                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
7992                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7993
7994                    // Always subtract cache size, since it's a subdirectory
7995                    mStats.externalDataSize -= mStats.externalCacheSize;
7996
7997                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7998                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7999
8000                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8001                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8002                }
8003            }
8004        }
8005
8006        @Override
8007        void handleReturnCode() {
8008            if (mObserver != null) {
8009                try {
8010                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8011                } catch (RemoteException e) {
8012                    Slog.i(TAG, "Observer no longer exists.");
8013                }
8014            }
8015        }
8016
8017        @Override
8018        void handleServiceError() {
8019            Slog.e(TAG, "Could not measure application " + mStats.packageName
8020                            + " external storage");
8021        }
8022    }
8023
8024    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8025            throws RemoteException {
8026        long result = 0;
8027        for (File path : paths) {
8028            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8029        }
8030        return result;
8031    }
8032
8033    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8034        for (File path : paths) {
8035            try {
8036                mcs.clearDirectory(path.getAbsolutePath());
8037            } catch (RemoteException e) {
8038            }
8039        }
8040    }
8041
8042    class InstallParams extends HandlerParams {
8043        final IPackageInstallObserver observer;
8044        final IPackageInstallObserver2 observer2;
8045        int flags;
8046
8047        private final Uri mPackageURI;
8048        final String installerPackageName;
8049        final VerificationParams verificationParams;
8050        private InstallArgs mArgs;
8051        private int mRet;
8052        private File mTempPackage;
8053        final ContainerEncryptionParams encryptionParams;
8054
8055        InstallParams(Uri packageURI,
8056                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8057                int flags, String installerPackageName, VerificationParams verificationParams,
8058                ContainerEncryptionParams encryptionParams, UserHandle user) {
8059            super(user);
8060            this.mPackageURI = packageURI;
8061            this.flags = flags;
8062            this.observer = observer;
8063            this.observer2 = observer2;
8064            this.installerPackageName = installerPackageName;
8065            this.verificationParams = verificationParams;
8066            this.encryptionParams = encryptionParams;
8067        }
8068
8069        @Override
8070        public String toString() {
8071            return "InstallParams{"
8072                + Integer.toHexString(System.identityHashCode(this))
8073                + " " + mPackageURI + "}";
8074        }
8075
8076        public ManifestDigest getManifestDigest() {
8077            if (verificationParams == null) {
8078                return null;
8079            }
8080            return verificationParams.getManifestDigest();
8081        }
8082
8083        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8084            String packageName = pkgLite.packageName;
8085            int installLocation = pkgLite.installLocation;
8086            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8087            // reader
8088            synchronized (mPackages) {
8089                PackageParser.Package pkg = mPackages.get(packageName);
8090                if (pkg != null) {
8091                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8092                        // Check for downgrading.
8093                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8094                            if (pkgLite.versionCode < pkg.mVersionCode) {
8095                                Slog.w(TAG, "Can't install update of " + packageName
8096                                        + " update version " + pkgLite.versionCode
8097                                        + " is older than installed version "
8098                                        + pkg.mVersionCode);
8099                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8100                            }
8101                        }
8102                        // Check for updated system application.
8103                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8104                            if (onSd) {
8105                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8106                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8107                            }
8108                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8109                        } else {
8110                            if (onSd) {
8111                                // Install flag overrides everything.
8112                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8113                            }
8114                            // If current upgrade specifies particular preference
8115                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8116                                // Application explicitly specified internal.
8117                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8118                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8119                                // App explictly prefers external. Let policy decide
8120                            } else {
8121                                // Prefer previous location
8122                                if (isExternal(pkg)) {
8123                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8124                                }
8125                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8126                            }
8127                        }
8128                    } else {
8129                        // Invalid install. Return error code
8130                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8131                    }
8132                }
8133            }
8134            // All the special cases have been taken care of.
8135            // Return result based on recommended install location.
8136            if (onSd) {
8137                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8138            }
8139            return pkgLite.recommendedInstallLocation;
8140        }
8141
8142        private long getMemoryLowThreshold() {
8143            final DeviceStorageMonitorInternal
8144                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8145            if (dsm == null) {
8146                return 0L;
8147            }
8148            return dsm.getMemoryLowThreshold();
8149        }
8150
8151        /*
8152         * Invoke remote method to get package information and install
8153         * location values. Override install location based on default
8154         * policy if needed and then create install arguments based
8155         * on the install location.
8156         */
8157        public void handleStartCopy() throws RemoteException {
8158            int ret = PackageManager.INSTALL_SUCCEEDED;
8159            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8160            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8161            PackageInfoLite pkgLite = null;
8162
8163            if (onInt && onSd) {
8164                // Check if both bits are set.
8165                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8166                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8167            } else {
8168                final long lowThreshold = getMemoryLowThreshold();
8169                if (lowThreshold == 0L) {
8170                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8171                }
8172
8173                try {
8174                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8175                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8176
8177                    final File packageFile;
8178                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8179                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8180                        if (mTempPackage != null) {
8181                            ParcelFileDescriptor out;
8182                            try {
8183                                out = ParcelFileDescriptor.open(mTempPackage,
8184                                        ParcelFileDescriptor.MODE_READ_WRITE);
8185                            } catch (FileNotFoundException e) {
8186                                out = null;
8187                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8188                            }
8189
8190                            // Make a temporary file for decryption.
8191                            ret = mContainerService
8192                                    .copyResource(mPackageURI, encryptionParams, out);
8193                            IoUtils.closeQuietly(out);
8194
8195                            packageFile = mTempPackage;
8196
8197                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8198                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8199                                            | FileUtils.S_IROTH,
8200                                    -1, -1);
8201                        } else {
8202                            packageFile = null;
8203                        }
8204                    } else {
8205                        packageFile = new File(mPackageURI.getPath());
8206                    }
8207
8208                    if (packageFile != null) {
8209                        // Remote call to find out default install location
8210                        final String packageFilePath = packageFile.getAbsolutePath();
8211                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8212                                lowThreshold);
8213
8214                        /*
8215                         * If we have too little free space, try to free cache
8216                         * before giving up.
8217                         */
8218                        if (pkgLite.recommendedInstallLocation
8219                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8220                            final long size = mContainerService.calculateInstalledSize(
8221                                    packageFilePath, isForwardLocked());
8222                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8223                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8224                                        flags, lowThreshold);
8225                            }
8226                            /*
8227                             * The cache free must have deleted the file we
8228                             * downloaded to install.
8229                             *
8230                             * TODO: fix the "freeCache" call to not delete
8231                             *       the file we care about.
8232                             */
8233                            if (pkgLite.recommendedInstallLocation
8234                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8235                                pkgLite.recommendedInstallLocation
8236                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8237                            }
8238                        }
8239                    }
8240                } finally {
8241                    mContext.revokeUriPermission(mPackageURI,
8242                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8243                }
8244            }
8245
8246            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8247                int loc = pkgLite.recommendedInstallLocation;
8248                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8249                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8250                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8251                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8252                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8253                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8254                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8255                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8256                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8257                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8258                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8259                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8260                } else {
8261                    // Override with defaults if needed.
8262                    loc = installLocationPolicy(pkgLite, flags);
8263                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8264                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8265                    } else if (!onSd && !onInt) {
8266                        // Override install location with flags
8267                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8268                            // Set the flag to install on external media.
8269                            flags |= PackageManager.INSTALL_EXTERNAL;
8270                            flags &= ~PackageManager.INSTALL_INTERNAL;
8271                        } else {
8272                            // Make sure the flag for installing on external
8273                            // media is unset
8274                            flags |= PackageManager.INSTALL_INTERNAL;
8275                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8276                        }
8277                    }
8278                }
8279            }
8280
8281            final InstallArgs args = createInstallArgs(this);
8282            mArgs = args;
8283
8284            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8285                 /*
8286                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8287                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8288                 */
8289                int userIdentifier = getUser().getIdentifier();
8290                if (userIdentifier == UserHandle.USER_ALL
8291                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8292                    userIdentifier = UserHandle.USER_OWNER;
8293                }
8294
8295                /*
8296                 * Determine if we have any installed package verifiers. If we
8297                 * do, then we'll defer to them to verify the packages.
8298                 */
8299                final int requiredUid = mRequiredVerifierPackage == null ? -1
8300                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8301                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8302                    final Intent verification = new Intent(
8303                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8304                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8305                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8306
8307                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8308                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8309                            0 /* TODO: Which userId? */);
8310
8311                    if (DEBUG_VERIFY) {
8312                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8313                                + verification.toString() + " with " + pkgLite.verifiers.length
8314                                + " optional verifiers");
8315                    }
8316
8317                    final int verificationId = mPendingVerificationToken++;
8318
8319                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8320
8321                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8322                            installerPackageName);
8323
8324                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8325
8326                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8327                            pkgLite.packageName);
8328
8329                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8330                            pkgLite.versionCode);
8331
8332                    if (verificationParams != null) {
8333                        if (verificationParams.getVerificationURI() != null) {
8334                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8335                                 verificationParams.getVerificationURI());
8336                        }
8337                        if (verificationParams.getOriginatingURI() != null) {
8338                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8339                                  verificationParams.getOriginatingURI());
8340                        }
8341                        if (verificationParams.getReferrer() != null) {
8342                            verification.putExtra(Intent.EXTRA_REFERRER,
8343                                  verificationParams.getReferrer());
8344                        }
8345                        if (verificationParams.getOriginatingUid() >= 0) {
8346                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8347                                  verificationParams.getOriginatingUid());
8348                        }
8349                        if (verificationParams.getInstallerUid() >= 0) {
8350                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8351                                  verificationParams.getInstallerUid());
8352                        }
8353                    }
8354
8355                    final PackageVerificationState verificationState = new PackageVerificationState(
8356                            requiredUid, args);
8357
8358                    mPendingVerification.append(verificationId, verificationState);
8359
8360                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8361                            receivers, verificationState);
8362
8363                    /*
8364                     * If any sufficient verifiers were listed in the package
8365                     * manifest, attempt to ask them.
8366                     */
8367                    if (sufficientVerifiers != null) {
8368                        final int N = sufficientVerifiers.size();
8369                        if (N == 0) {
8370                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8371                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8372                        } else {
8373                            for (int i = 0; i < N; i++) {
8374                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8375
8376                                final Intent sufficientIntent = new Intent(verification);
8377                                sufficientIntent.setComponent(verifierComponent);
8378
8379                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8380                            }
8381                        }
8382                    }
8383
8384                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8385                            mRequiredVerifierPackage, receivers);
8386                    if (ret == PackageManager.INSTALL_SUCCEEDED
8387                            && mRequiredVerifierPackage != null) {
8388                        /*
8389                         * Send the intent to the required verification agent,
8390                         * but only start the verification timeout after the
8391                         * target BroadcastReceivers have run.
8392                         */
8393                        verification.setComponent(requiredVerifierComponent);
8394                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8395                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8396                                new BroadcastReceiver() {
8397                                    @Override
8398                                    public void onReceive(Context context, Intent intent) {
8399                                        final Message msg = mHandler
8400                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8401                                        msg.arg1 = verificationId;
8402                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8403                                    }
8404                                }, null, 0, null, null);
8405
8406                        /*
8407                         * We don't want the copy to proceed until verification
8408                         * succeeds, so null out this field.
8409                         */
8410                        mArgs = null;
8411                    }
8412                } else {
8413                    /*
8414                     * No package verification is enabled, so immediately start
8415                     * the remote call to initiate copy using temporary file.
8416                     */
8417                    ret = args.copyApk(mContainerService, true);
8418                }
8419            }
8420
8421            mRet = ret;
8422        }
8423
8424        @Override
8425        void handleReturnCode() {
8426            // If mArgs is null, then MCS couldn't be reached. When it
8427            // reconnects, it will try again to install. At that point, this
8428            // will succeed.
8429            if (mArgs != null) {
8430                processPendingInstall(mArgs, mRet);
8431
8432                if (mTempPackage != null) {
8433                    if (!mTempPackage.delete()) {
8434                        Slog.w(TAG, "Couldn't delete temporary file: " +
8435                                mTempPackage.getAbsolutePath());
8436                    }
8437                }
8438            }
8439        }
8440
8441        @Override
8442        void handleServiceError() {
8443            mArgs = createInstallArgs(this);
8444            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8445        }
8446
8447        public boolean isForwardLocked() {
8448            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8449        }
8450
8451        public Uri getPackageUri() {
8452            if (mTempPackage != null) {
8453                return Uri.fromFile(mTempPackage);
8454            } else {
8455                return mPackageURI;
8456            }
8457        }
8458    }
8459
8460    /*
8461     * Utility class used in movePackage api.
8462     * srcArgs and targetArgs are not set for invalid flags and make
8463     * sure to do null checks when invoking methods on them.
8464     * We probably want to return ErrorPrams for both failed installs
8465     * and moves.
8466     */
8467    class MoveParams extends HandlerParams {
8468        final IPackageMoveObserver observer;
8469        final int flags;
8470        final String packageName;
8471        final InstallArgs srcArgs;
8472        final InstallArgs targetArgs;
8473        int uid;
8474        int mRet;
8475
8476        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8477                String packageName, String dataDir, String instructionSet,
8478                int uid, UserHandle user) {
8479            super(user);
8480            this.srcArgs = srcArgs;
8481            this.observer = observer;
8482            this.flags = flags;
8483            this.packageName = packageName;
8484            this.uid = uid;
8485            if (srcArgs != null) {
8486                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8487                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8488            } else {
8489                targetArgs = null;
8490            }
8491        }
8492
8493        @Override
8494        public String toString() {
8495            return "MoveParams{"
8496                + Integer.toHexString(System.identityHashCode(this))
8497                + " " + packageName + "}";
8498        }
8499
8500        public void handleStartCopy() throws RemoteException {
8501            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8502            // Check for storage space on target medium
8503            if (!targetArgs.checkFreeStorage(mContainerService)) {
8504                Log.w(TAG, "Insufficient storage to install");
8505                return;
8506            }
8507
8508            mRet = srcArgs.doPreCopy();
8509            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8510                return;
8511            }
8512
8513            mRet = targetArgs.copyApk(mContainerService, false);
8514            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8515                srcArgs.doPostCopy(uid);
8516                return;
8517            }
8518
8519            mRet = srcArgs.doPostCopy(uid);
8520            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8521                return;
8522            }
8523
8524            mRet = targetArgs.doPreInstall(mRet);
8525            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8526                return;
8527            }
8528
8529            if (DEBUG_SD_INSTALL) {
8530                StringBuilder builder = new StringBuilder();
8531                if (srcArgs != null) {
8532                    builder.append("src: ");
8533                    builder.append(srcArgs.getCodePath());
8534                }
8535                if (targetArgs != null) {
8536                    builder.append(" target : ");
8537                    builder.append(targetArgs.getCodePath());
8538                }
8539                Log.i(TAG, builder.toString());
8540            }
8541        }
8542
8543        @Override
8544        void handleReturnCode() {
8545            targetArgs.doPostInstall(mRet, uid);
8546            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8547            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8548                currentStatus = PackageManager.MOVE_SUCCEEDED;
8549            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8550                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8551            }
8552            processPendingMove(this, currentStatus);
8553        }
8554
8555        @Override
8556        void handleServiceError() {
8557            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8558        }
8559    }
8560
8561    /**
8562     * Used during creation of InstallArgs
8563     *
8564     * @param flags package installation flags
8565     * @return true if should be installed on external storage
8566     */
8567    private static boolean installOnSd(int flags) {
8568        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8569            return false;
8570        }
8571        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8572            return true;
8573        }
8574        return false;
8575    }
8576
8577    /**
8578     * Used during creation of InstallArgs
8579     *
8580     * @param flags package installation flags
8581     * @return true if should be installed as forward locked
8582     */
8583    private static boolean installForwardLocked(int flags) {
8584        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8585    }
8586
8587    private InstallArgs createInstallArgs(InstallParams params) {
8588        if (installOnSd(params.flags) || params.isForwardLocked()) {
8589            return new AsecInstallArgs(params);
8590        } else {
8591            return new FileInstallArgs(params);
8592        }
8593    }
8594
8595    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8596            String nativeLibraryPath, String instructionSet) {
8597        final boolean isInAsec;
8598        if (installOnSd(flags)) {
8599            /* Apps on SD card are always in ASEC containers. */
8600            isInAsec = true;
8601        } else if (installForwardLocked(flags)
8602                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8603            /*
8604             * Forward-locked apps are only in ASEC containers if they're the
8605             * new style
8606             */
8607            isInAsec = true;
8608        } else {
8609            isInAsec = false;
8610        }
8611
8612        if (isInAsec) {
8613            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8614                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8615        } else {
8616            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8617                    instructionSet);
8618        }
8619    }
8620
8621    // Used by package mover
8622    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8623            String instructionSet) {
8624        if (installOnSd(flags) || installForwardLocked(flags)) {
8625            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8626                    + AsecInstallArgs.RES_FILE_NAME);
8627            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8628                    installForwardLocked(flags));
8629        } else {
8630            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8631        }
8632    }
8633
8634    static abstract class InstallArgs {
8635        final IPackageInstallObserver observer;
8636        final IPackageInstallObserver2 observer2;
8637        // Always refers to PackageManager flags only
8638        final int flags;
8639        final Uri packageURI;
8640        final String installerPackageName;
8641        final ManifestDigest manifestDigest;
8642        final UserHandle user;
8643        final String instructionSet;
8644
8645        InstallArgs(Uri packageURI,
8646                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8647                int flags, String installerPackageName, ManifestDigest manifestDigest,
8648                UserHandle user, String instructionSet) {
8649            this.packageURI = packageURI;
8650            this.flags = flags;
8651            this.observer = observer;
8652            this.observer2 = observer2;
8653            this.installerPackageName = installerPackageName;
8654            this.manifestDigest = manifestDigest;
8655            this.user = user;
8656            this.instructionSet = instructionSet;
8657        }
8658
8659        abstract void createCopyFile();
8660        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8661        abstract int doPreInstall(int status);
8662        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8663
8664        abstract int doPostInstall(int status, int uid);
8665        abstract String getCodePath();
8666        abstract String getResourcePath();
8667        abstract String getNativeLibraryPath();
8668        // Need installer lock especially for dex file removal.
8669        abstract void cleanUpResourcesLI();
8670        abstract boolean doPostDeleteLI(boolean delete);
8671        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8672
8673        /**
8674         * Called before the source arguments are copied. This is used mostly
8675         * for MoveParams when it needs to read the source file to put it in the
8676         * destination.
8677         */
8678        int doPreCopy() {
8679            return PackageManager.INSTALL_SUCCEEDED;
8680        }
8681
8682        /**
8683         * Called after the source arguments are copied. This is used mostly for
8684         * MoveParams when it needs to read the source file to put it in the
8685         * destination.
8686         *
8687         * @return
8688         */
8689        int doPostCopy(int uid) {
8690            return PackageManager.INSTALL_SUCCEEDED;
8691        }
8692
8693        protected boolean isFwdLocked() {
8694            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8695        }
8696
8697        UserHandle getUser() {
8698            return user;
8699        }
8700    }
8701
8702    class FileInstallArgs extends InstallArgs {
8703        File installDir;
8704        String codeFileName;
8705        String resourceFileName;
8706        String libraryPath;
8707        boolean created = false;
8708
8709        FileInstallArgs(InstallParams params) {
8710            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8711                    params.installerPackageName, params.getManifestDigest(),
8712                    params.getUser(), null /* instruction set */);
8713        }
8714
8715        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8716                String instructionSet) {
8717            super(null, null, null, 0, null, null, null, instructionSet);
8718            File codeFile = new File(fullCodePath);
8719            installDir = codeFile.getParentFile();
8720            codeFileName = fullCodePath;
8721            resourceFileName = fullResourcePath;
8722            libraryPath = nativeLibraryPath;
8723        }
8724
8725        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8726            super(packageURI, null, null, 0, null, null, null, instructionSet);
8727            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8728            String apkName = getNextCodePath(null, pkgName, ".apk");
8729            codeFileName = new File(installDir, apkName + ".apk").getPath();
8730            resourceFileName = getResourcePathFromCodePath();
8731            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8732        }
8733
8734        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8735            final long lowThreshold;
8736
8737            final DeviceStorageMonitorInternal
8738                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8739            if (dsm == null) {
8740                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8741                lowThreshold = 0L;
8742            } else {
8743                if (dsm.isMemoryLow()) {
8744                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8745                    return false;
8746                }
8747
8748                lowThreshold = dsm.getMemoryLowThreshold();
8749            }
8750
8751            try {
8752                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8753                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8754                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8755            } finally {
8756                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8757            }
8758        }
8759
8760        String getCodePath() {
8761            return codeFileName;
8762        }
8763
8764        void createCopyFile() {
8765            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8766            codeFileName = createTempPackageFile(installDir).getPath();
8767            resourceFileName = getResourcePathFromCodePath();
8768            libraryPath = getLibraryPathFromCodePath();
8769            created = true;
8770        }
8771
8772        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8773            if (temp) {
8774                // Generate temp file name
8775                createCopyFile();
8776            }
8777            // Get a ParcelFileDescriptor to write to the output file
8778            File codeFile = new File(codeFileName);
8779            if (!created) {
8780                try {
8781                    codeFile.createNewFile();
8782                    // Set permissions
8783                    if (!setPermissions()) {
8784                        // Failed setting permissions.
8785                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8786                    }
8787                } catch (IOException e) {
8788                   Slog.w(TAG, "Failed to create file " + codeFile);
8789                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8790                }
8791            }
8792            ParcelFileDescriptor out = null;
8793            try {
8794                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8795            } catch (FileNotFoundException e) {
8796                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8797                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8798            }
8799            // Copy the resource now
8800            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8801            try {
8802                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8803                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8804                ret = imcs.copyResource(packageURI, null, out);
8805            } finally {
8806                IoUtils.closeQuietly(out);
8807                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8808            }
8809
8810            if (isFwdLocked()) {
8811                final File destResourceFile = new File(getResourcePath());
8812
8813                // Copy the public files
8814                try {
8815                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8816                } catch (IOException e) {
8817                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8818                            + " forward-locked app.");
8819                    destResourceFile.delete();
8820                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8821                }
8822            }
8823
8824            final File nativeLibraryFile = new File(getNativeLibraryPath());
8825            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8826            if (nativeLibraryFile.exists()) {
8827                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8828                nativeLibraryFile.delete();
8829            }
8830            try {
8831                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8832                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8833                    return copyRet;
8834                }
8835            } catch (IOException e) {
8836                Slog.e(TAG, "Copying native libraries failed", e);
8837                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8838            }
8839
8840            return ret;
8841        }
8842
8843        int doPreInstall(int status) {
8844            if (status != PackageManager.INSTALL_SUCCEEDED) {
8845                cleanUp();
8846            }
8847            return status;
8848        }
8849
8850        boolean doRename(int status, final String pkgName, String oldCodePath) {
8851            if (status != PackageManager.INSTALL_SUCCEEDED) {
8852                cleanUp();
8853                return false;
8854            } else {
8855                final File oldCodeFile = new File(getCodePath());
8856                final File oldResourceFile = new File(getResourcePath());
8857                final File oldLibraryFile = new File(getNativeLibraryPath());
8858
8859                // Rename APK file based on packageName
8860                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8861                final File newCodeFile = new File(installDir, apkName + ".apk");
8862                if (!oldCodeFile.renameTo(newCodeFile)) {
8863                    return false;
8864                }
8865                codeFileName = newCodeFile.getPath();
8866
8867                // Rename public resource file if it's forward-locked.
8868                final File newResFile = new File(getResourcePathFromCodePath());
8869                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8870                    return false;
8871                }
8872                resourceFileName = newResFile.getPath();
8873
8874                // Rename library path
8875                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8876                if (newLibraryFile.exists()) {
8877                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8878                    newLibraryFile.delete();
8879                }
8880                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8881                    Slog.e(TAG, "Cannot rename native library directory "
8882                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8883                    return false;
8884                }
8885                libraryPath = newLibraryFile.getPath();
8886
8887                // Attempt to set permissions
8888                if (!setPermissions()) {
8889                    return false;
8890                }
8891
8892                if (!SELinux.restorecon(newCodeFile)) {
8893                    return false;
8894                }
8895
8896                return true;
8897            }
8898        }
8899
8900        int doPostInstall(int status, int uid) {
8901            if (status != PackageManager.INSTALL_SUCCEEDED) {
8902                cleanUp();
8903            }
8904            return status;
8905        }
8906
8907        String getResourcePath() {
8908            return resourceFileName;
8909        }
8910
8911        private String getResourcePathFromCodePath() {
8912            final String codePath = getCodePath();
8913            if (isFwdLocked()) {
8914                final StringBuilder sb = new StringBuilder();
8915
8916                sb.append(mAppInstallDir.getPath());
8917                sb.append('/');
8918                sb.append(getApkName(codePath));
8919                sb.append(".zip");
8920
8921                /*
8922                 * If our APK is a temporary file, mark the resource as a
8923                 * temporary file as well so it can be cleaned up after
8924                 * catastrophic failure.
8925                 */
8926                if (codePath.endsWith(".tmp")) {
8927                    sb.append(".tmp");
8928                }
8929
8930                return sb.toString();
8931            } else {
8932                return codePath;
8933            }
8934        }
8935
8936        private String getLibraryPathFromCodePath() {
8937            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8938        }
8939
8940        @Override
8941        String getNativeLibraryPath() {
8942            if (libraryPath == null) {
8943                libraryPath = getLibraryPathFromCodePath();
8944            }
8945            return libraryPath;
8946        }
8947
8948        private boolean cleanUp() {
8949            boolean ret = true;
8950            String sourceDir = getCodePath();
8951            String publicSourceDir = getResourcePath();
8952            if (sourceDir != null) {
8953                File sourceFile = new File(sourceDir);
8954                if (!sourceFile.exists()) {
8955                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8956                    ret = false;
8957                }
8958                // Delete application's code and resources
8959                sourceFile.delete();
8960            }
8961            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8962                final File publicSourceFile = new File(publicSourceDir);
8963                if (!publicSourceFile.exists()) {
8964                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8965                }
8966                if (publicSourceFile.exists()) {
8967                    publicSourceFile.delete();
8968                }
8969            }
8970
8971            if (libraryPath != null) {
8972                File nativeLibraryFile = new File(libraryPath);
8973                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8974                if (!nativeLibraryFile.delete()) {
8975                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8976                }
8977            }
8978
8979            return ret;
8980        }
8981
8982        void cleanUpResourcesLI() {
8983            String sourceDir = getCodePath();
8984            if (cleanUp()) {
8985                if (instructionSet == null) {
8986                    throw new IllegalStateException("instructionSet == null");
8987                }
8988                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
8989                if (retCode < 0) {
8990                    Slog.w(TAG, "Couldn't remove dex file for package: "
8991                            +  " at location "
8992                            + sourceDir + ", retcode=" + retCode);
8993                    // we don't consider this to be a failure of the core package deletion
8994                }
8995            }
8996        }
8997
8998        private boolean setPermissions() {
8999            // TODO Do this in a more elegant way later on. for now just a hack
9000            if (!isFwdLocked()) {
9001                final int filePermissions =
9002                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9003                    |FileUtils.S_IROTH;
9004                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9005                if (retCode != 0) {
9006                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9007                            getCodePath()
9008                            + ". The return code was: " + retCode);
9009                    // TODO Define new internal error
9010                    return false;
9011                }
9012                return true;
9013            }
9014            return true;
9015        }
9016
9017        boolean doPostDeleteLI(boolean delete) {
9018            // XXX err, shouldn't we respect the delete flag?
9019            cleanUpResourcesLI();
9020            return true;
9021        }
9022    }
9023
9024    private boolean isAsecExternal(String cid) {
9025        final String asecPath = PackageHelper.getSdFilesystem(cid);
9026        return !asecPath.startsWith(mAsecInternalPath);
9027    }
9028
9029    /**
9030     * Extract the MountService "container ID" from the full code path of an
9031     * .apk.
9032     */
9033    static String cidFromCodePath(String fullCodePath) {
9034        int eidx = fullCodePath.lastIndexOf("/");
9035        String subStr1 = fullCodePath.substring(0, eidx);
9036        int sidx = subStr1.lastIndexOf("/");
9037        return subStr1.substring(sidx+1, eidx);
9038    }
9039
9040    class AsecInstallArgs extends InstallArgs {
9041        static final String RES_FILE_NAME = "pkg.apk";
9042        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9043
9044        String cid;
9045        String packagePath;
9046        String resourcePath;
9047        String libraryPath;
9048
9049        AsecInstallArgs(InstallParams params) {
9050            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9051                    params.installerPackageName, params.getManifestDigest(),
9052                    params.getUser(), null /* instruction set */);
9053        }
9054
9055        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9056                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9057            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9058                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9059                    null, null, null, instructionSet);
9060            // Extract cid from fullCodePath
9061            int eidx = fullCodePath.lastIndexOf("/");
9062            String subStr1 = fullCodePath.substring(0, eidx);
9063            int sidx = subStr1.lastIndexOf("/");
9064            cid = subStr1.substring(sidx+1, eidx);
9065            setCachePath(subStr1);
9066        }
9067
9068        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9069            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9070                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9071                    null, null, null, instructionSet);
9072            this.cid = cid;
9073            setCachePath(PackageHelper.getSdDir(cid));
9074        }
9075
9076        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9077                boolean isExternal, boolean isForwardLocked) {
9078            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9079                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9080                    null, null, null, instructionSet);
9081            this.cid = cid;
9082        }
9083
9084        void createCopyFile() {
9085            cid = getTempContainerId();
9086        }
9087
9088        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9089            try {
9090                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9091                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9092                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
9093            } finally {
9094                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9095            }
9096        }
9097
9098        private final boolean isExternal() {
9099            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9100        }
9101
9102        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9103            if (temp) {
9104                createCopyFile();
9105            } else {
9106                /*
9107                 * Pre-emptively destroy the container since it's destroyed if
9108                 * copying fails due to it existing anyway.
9109                 */
9110                PackageHelper.destroySdDir(cid);
9111            }
9112
9113            final String newCachePath;
9114            try {
9115                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9116                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9117                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9118                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9119            } finally {
9120                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9121            }
9122
9123            if (newCachePath != null) {
9124                setCachePath(newCachePath);
9125                return PackageManager.INSTALL_SUCCEEDED;
9126            } else {
9127                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9128            }
9129        }
9130
9131        @Override
9132        String getCodePath() {
9133            return packagePath;
9134        }
9135
9136        @Override
9137        String getResourcePath() {
9138            return resourcePath;
9139        }
9140
9141        @Override
9142        String getNativeLibraryPath() {
9143            return libraryPath;
9144        }
9145
9146        int doPreInstall(int status) {
9147            if (status != PackageManager.INSTALL_SUCCEEDED) {
9148                // Destroy container
9149                PackageHelper.destroySdDir(cid);
9150            } else {
9151                boolean mounted = PackageHelper.isContainerMounted(cid);
9152                if (!mounted) {
9153                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9154                            Process.SYSTEM_UID);
9155                    if (newCachePath != null) {
9156                        setCachePath(newCachePath);
9157                    } else {
9158                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9159                    }
9160                }
9161            }
9162            return status;
9163        }
9164
9165        boolean doRename(int status, final String pkgName,
9166                String oldCodePath) {
9167            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9168            String newCachePath = null;
9169            if (PackageHelper.isContainerMounted(cid)) {
9170                // Unmount the container
9171                if (!PackageHelper.unMountSdDir(cid)) {
9172                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9173                    return false;
9174                }
9175            }
9176            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9177                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9178                        " which might be stale. Will try to clean up.");
9179                // Clean up the stale container and proceed to recreate.
9180                if (!PackageHelper.destroySdDir(newCacheId)) {
9181                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9182                    return false;
9183                }
9184                // Successfully cleaned up stale container. Try to rename again.
9185                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9186                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9187                            + " inspite of cleaning it up.");
9188                    return false;
9189                }
9190            }
9191            if (!PackageHelper.isContainerMounted(newCacheId)) {
9192                Slog.w(TAG, "Mounting container " + newCacheId);
9193                newCachePath = PackageHelper.mountSdDir(newCacheId,
9194                        getEncryptKey(), Process.SYSTEM_UID);
9195            } else {
9196                newCachePath = PackageHelper.getSdDir(newCacheId);
9197            }
9198            if (newCachePath == null) {
9199                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9200                return false;
9201            }
9202            Log.i(TAG, "Succesfully renamed " + cid +
9203                    " to " + newCacheId +
9204                    " at new path: " + newCachePath);
9205            cid = newCacheId;
9206            setCachePath(newCachePath);
9207            return true;
9208        }
9209
9210        private void setCachePath(String newCachePath) {
9211            File cachePath = new File(newCachePath);
9212            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9213            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9214
9215            if (isFwdLocked()) {
9216                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9217            } else {
9218                resourcePath = packagePath;
9219            }
9220        }
9221
9222        int doPostInstall(int status, int uid) {
9223            if (status != PackageManager.INSTALL_SUCCEEDED) {
9224                cleanUp();
9225            } else {
9226                final int groupOwner;
9227                final String protectedFile;
9228                if (isFwdLocked()) {
9229                    groupOwner = UserHandle.getSharedAppGid(uid);
9230                    protectedFile = RES_FILE_NAME;
9231                } else {
9232                    groupOwner = -1;
9233                    protectedFile = null;
9234                }
9235
9236                if (uid < Process.FIRST_APPLICATION_UID
9237                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9238                    Slog.e(TAG, "Failed to finalize " + cid);
9239                    PackageHelper.destroySdDir(cid);
9240                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9241                }
9242
9243                boolean mounted = PackageHelper.isContainerMounted(cid);
9244                if (!mounted) {
9245                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9246                }
9247            }
9248            return status;
9249        }
9250
9251        private void cleanUp() {
9252            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9253
9254            // Destroy secure container
9255            PackageHelper.destroySdDir(cid);
9256        }
9257
9258        void cleanUpResourcesLI() {
9259            String sourceFile = getCodePath();
9260            // Remove dex file
9261            if (instructionSet == null) {
9262                throw new IllegalStateException("instructionSet == null");
9263            }
9264            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9265            if (retCode < 0) {
9266                Slog.w(TAG, "Couldn't remove dex file for package: "
9267                        + " at location "
9268                        + sourceFile.toString() + ", retcode=" + retCode);
9269                // we don't consider this to be a failure of the core package deletion
9270            }
9271            cleanUp();
9272        }
9273
9274        boolean matchContainer(String app) {
9275            if (cid.startsWith(app)) {
9276                return true;
9277            }
9278            return false;
9279        }
9280
9281        String getPackageName() {
9282            return getAsecPackageName(cid);
9283        }
9284
9285        boolean doPostDeleteLI(boolean delete) {
9286            boolean ret = false;
9287            boolean mounted = PackageHelper.isContainerMounted(cid);
9288            if (mounted) {
9289                // Unmount first
9290                ret = PackageHelper.unMountSdDir(cid);
9291            }
9292            if (ret && delete) {
9293                cleanUpResourcesLI();
9294            }
9295            return ret;
9296        }
9297
9298        @Override
9299        int doPreCopy() {
9300            if (isFwdLocked()) {
9301                if (!PackageHelper.fixSdPermissions(cid,
9302                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9303                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9304                }
9305            }
9306
9307            return PackageManager.INSTALL_SUCCEEDED;
9308        }
9309
9310        @Override
9311        int doPostCopy(int uid) {
9312            if (isFwdLocked()) {
9313                if (uid < Process.FIRST_APPLICATION_UID
9314                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9315                                RES_FILE_NAME)) {
9316                    Slog.e(TAG, "Failed to finalize " + cid);
9317                    PackageHelper.destroySdDir(cid);
9318                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9319                }
9320            }
9321
9322            return PackageManager.INSTALL_SUCCEEDED;
9323        }
9324    };
9325
9326    static String getAsecPackageName(String packageCid) {
9327        int idx = packageCid.lastIndexOf("-");
9328        if (idx == -1) {
9329            return packageCid;
9330        }
9331        return packageCid.substring(0, idx);
9332    }
9333
9334    // Utility method used to create code paths based on package name and available index.
9335    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9336        String idxStr = "";
9337        int idx = 1;
9338        // Fall back to default value of idx=1 if prefix is not
9339        // part of oldCodePath
9340        if (oldCodePath != null) {
9341            String subStr = oldCodePath;
9342            // Drop the suffix right away
9343            if (subStr.endsWith(suffix)) {
9344                subStr = subStr.substring(0, subStr.length() - suffix.length());
9345            }
9346            // If oldCodePath already contains prefix find out the
9347            // ending index to either increment or decrement.
9348            int sidx = subStr.lastIndexOf(prefix);
9349            if (sidx != -1) {
9350                subStr = subStr.substring(sidx + prefix.length());
9351                if (subStr != null) {
9352                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9353                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9354                    }
9355                    try {
9356                        idx = Integer.parseInt(subStr);
9357                        if (idx <= 1) {
9358                            idx++;
9359                        } else {
9360                            idx--;
9361                        }
9362                    } catch(NumberFormatException e) {
9363                    }
9364                }
9365            }
9366        }
9367        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9368        return prefix + idxStr;
9369    }
9370
9371    // Utility method used to ignore ADD/REMOVE events
9372    // by directory observer.
9373    private static boolean ignoreCodePath(String fullPathStr) {
9374        String apkName = getApkName(fullPathStr);
9375        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9376        if (idx != -1 && ((idx+1) < apkName.length())) {
9377            // Make sure the package ends with a numeral
9378            String version = apkName.substring(idx+1);
9379            try {
9380                Integer.parseInt(version);
9381                return true;
9382            } catch (NumberFormatException e) {}
9383        }
9384        return false;
9385    }
9386
9387    // Utility method that returns the relative package path with respect
9388    // to the installation directory. Like say for /data/data/com.test-1.apk
9389    // string com.test-1 is returned.
9390    static String getApkName(String codePath) {
9391        if (codePath == null) {
9392            return null;
9393        }
9394        int sidx = codePath.lastIndexOf("/");
9395        int eidx = codePath.lastIndexOf(".");
9396        if (eidx == -1) {
9397            eidx = codePath.length();
9398        } else if (eidx == 0) {
9399            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9400            return null;
9401        }
9402        return codePath.substring(sidx+1, eidx);
9403    }
9404
9405    class PackageInstalledInfo {
9406        String name;
9407        int uid;
9408        // The set of users that originally had this package installed.
9409        int[] origUsers;
9410        // The set of users that now have this package installed.
9411        int[] newUsers;
9412        PackageParser.Package pkg;
9413        int returnCode;
9414        PackageRemovedInfo removedInfo;
9415
9416        // In some error cases we want to convey more info back to the observer
9417        String origPackage;
9418        String origPermission;
9419    }
9420
9421    /*
9422     * Install a non-existing package.
9423     */
9424    private void installNewPackageLI(PackageParser.Package pkg,
9425            int parseFlags, int scanMode, UserHandle user,
9426            String installerPackageName, PackageInstalledInfo res) {
9427        // Remember this for later, in case we need to rollback this install
9428        String pkgName = pkg.packageName;
9429
9430        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9431        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9432        synchronized(mPackages) {
9433            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9434                // A package with the same name is already installed, though
9435                // it has been renamed to an older name.  The package we
9436                // are trying to install should be installed as an update to
9437                // the existing one, but that has not been requested, so bail.
9438                Slog.w(TAG, "Attempt to re-install " + pkgName
9439                        + " without first uninstalling package running as "
9440                        + mSettings.mRenamedPackages.get(pkgName));
9441                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9442                return;
9443            }
9444            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9445                // Don't allow installation over an existing package with the same name.
9446                Slog.w(TAG, "Attempt to re-install " + pkgName
9447                        + " without first uninstalling.");
9448                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9449                return;
9450            }
9451        }
9452        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9453        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9454                System.currentTimeMillis(), user);
9455        if (newPackage == null) {
9456            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9457            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9458                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9459            }
9460        } else {
9461            updateSettingsLI(newPackage,
9462                    installerPackageName,
9463                    null, null,
9464                    res);
9465            // delete the partially installed application. the data directory will have to be
9466            // restored if it was already existing
9467            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9468                // remove package from internal structures.  Note that we want deletePackageX to
9469                // delete the package data and cache directories that it created in
9470                // scanPackageLocked, unless those directories existed before we even tried to
9471                // install.
9472                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9473                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9474                                res.removedInfo, true);
9475            }
9476        }
9477    }
9478
9479    private void replacePackageLI(PackageParser.Package pkg,
9480            int parseFlags, int scanMode, UserHandle user,
9481            String installerPackageName, PackageInstalledInfo res) {
9482
9483        PackageParser.Package oldPackage;
9484        String pkgName = pkg.packageName;
9485        int[] allUsers;
9486        boolean[] perUserInstalled;
9487
9488        // First find the old package info and check signatures
9489        synchronized(mPackages) {
9490            oldPackage = mPackages.get(pkgName);
9491            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9492            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9493                    != PackageManager.SIGNATURE_MATCH) {
9494                Slog.w(TAG, "New package has a different signature: " + pkgName);
9495                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9496                return;
9497            }
9498
9499            // In case of rollback, remember per-user/profile install state
9500            PackageSetting ps = mSettings.mPackages.get(pkgName);
9501            allUsers = sUserManager.getUserIds();
9502            perUserInstalled = new boolean[allUsers.length];
9503            for (int i = 0; i < allUsers.length; i++) {
9504                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9505            }
9506        }
9507        boolean sysPkg = (isSystemApp(oldPackage));
9508        if (sysPkg) {
9509            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9510                    user, allUsers, perUserInstalled, installerPackageName, res);
9511        } else {
9512            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9513                    user, allUsers, perUserInstalled, installerPackageName, res);
9514        }
9515    }
9516
9517    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9518            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9519            int[] allUsers, boolean[] perUserInstalled,
9520            String installerPackageName, PackageInstalledInfo res) {
9521        PackageParser.Package newPackage = null;
9522        String pkgName = deletedPackage.packageName;
9523        boolean deletedPkg = true;
9524        boolean updatedSettings = false;
9525
9526        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9527                + deletedPackage);
9528        long origUpdateTime;
9529        if (pkg.mExtras != null) {
9530            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9531        } else {
9532            origUpdateTime = 0;
9533        }
9534
9535        // First delete the existing package while retaining the data directory
9536        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9537                res.removedInfo, true)) {
9538            // If the existing package wasn't successfully deleted
9539            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9540            deletedPkg = false;
9541        } else {
9542            // Successfully deleted the old package. Now proceed with re-installation
9543            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9544            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9545                    System.currentTimeMillis(), user);
9546            if (newPackage == null) {
9547                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9548                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9549                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9550                }
9551            } else {
9552                updateSettingsLI(newPackage,
9553                        installerPackageName,
9554                        allUsers, perUserInstalled,
9555                        res);
9556                updatedSettings = true;
9557            }
9558        }
9559
9560        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9561            // remove package from internal structures.  Note that we want deletePackageX to
9562            // delete the package data and cache directories that it created in
9563            // scanPackageLocked, unless those directories existed before we even tried to
9564            // install.
9565            if(updatedSettings) {
9566                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9567                deletePackageLI(
9568                        pkgName, null, true, allUsers, perUserInstalled,
9569                        PackageManager.DELETE_KEEP_DATA,
9570                                res.removedInfo, true);
9571            }
9572            // Since we failed to install the new package we need to restore the old
9573            // package that we deleted.
9574            if(deletedPkg) {
9575                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9576                File restoreFile = new File(deletedPackage.mPath);
9577                // Parse old package
9578                boolean oldOnSd = isExternal(deletedPackage);
9579                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9580                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9581                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9582                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9583                        | SCAN_UPDATE_TIME;
9584                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9585                        origUpdateTime, null) == null) {
9586                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9587                    return;
9588                }
9589                // Restore of old package succeeded. Update permissions.
9590                // writer
9591                synchronized (mPackages) {
9592                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9593                            UPDATE_PERMISSIONS_ALL);
9594                    // can downgrade to reader
9595                    mSettings.writeLPr();
9596                }
9597                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9598            }
9599        }
9600    }
9601
9602    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9603            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9604            int[] allUsers, boolean[] perUserInstalled,
9605            String installerPackageName, PackageInstalledInfo res) {
9606        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9607                + ", old=" + deletedPackage);
9608        PackageParser.Package newPackage = null;
9609        boolean updatedSettings = false;
9610        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9611                PackageParser.PARSE_IS_SYSTEM;
9612        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9613            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9614        }
9615        String packageName = deletedPackage.packageName;
9616        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9617        if (packageName == null) {
9618            Slog.w(TAG, "Attempt to delete null packageName.");
9619            return;
9620        }
9621        PackageParser.Package oldPkg;
9622        PackageSetting oldPkgSetting;
9623        // reader
9624        synchronized (mPackages) {
9625            oldPkg = mPackages.get(packageName);
9626            oldPkgSetting = mSettings.mPackages.get(packageName);
9627            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9628                    (oldPkgSetting == null)) {
9629                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9630                return;
9631            }
9632        }
9633
9634        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9635
9636        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9637        res.removedInfo.removedPackage = packageName;
9638        // Remove existing system package
9639        removePackageLI(oldPkgSetting, true);
9640        // writer
9641        synchronized (mPackages) {
9642            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9643                // We didn't need to disable the .apk as a current system package,
9644                // which means we are replacing another update that is already
9645                // installed.  We need to make sure to delete the older one's .apk.
9646                res.removedInfo.args = createInstallArgs(0,
9647                        deletedPackage.applicationInfo.sourceDir,
9648                        deletedPackage.applicationInfo.publicSourceDir,
9649                        deletedPackage.applicationInfo.nativeLibraryDir,
9650                        getAppInstructionSet(deletedPackage.applicationInfo));
9651            } else {
9652                res.removedInfo.args = null;
9653            }
9654        }
9655
9656        // Successfully disabled the old package. Now proceed with re-installation
9657        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9658        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9659        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9660        if (newPackage == null) {
9661            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9662            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9663                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9664            }
9665        } else {
9666            if (newPackage.mExtras != null) {
9667                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9668                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9669                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9670
9671                // is the update attempting to change shared user? that isn't going to work...
9672                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9673                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9674                            + " to " + newPkgSetting.sharedUser);
9675                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9676                    updatedSettings = true;
9677                }
9678            }
9679
9680            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9681                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9682                updatedSettings = true;
9683            }
9684        }
9685
9686        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9687            // Re installation failed. Restore old information
9688            // Remove new pkg information
9689            if (newPackage != null) {
9690                removeInstalledPackageLI(newPackage, true);
9691            }
9692            // Add back the old system package
9693            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9694            // Restore the old system information in Settings
9695            synchronized(mPackages) {
9696                if (updatedSettings) {
9697                    mSettings.enableSystemPackageLPw(packageName);
9698                    mSettings.setInstallerPackageName(packageName,
9699                            oldPkgSetting.installerPackageName);
9700                }
9701                mSettings.writeLPr();
9702            }
9703        }
9704    }
9705
9706    // Utility method used to move dex files during install.
9707    private int moveDexFilesLI(PackageParser.Package newPackage) {
9708        int retCode;
9709        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9710            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9711                    getAppInstructionSet(newPackage.applicationInfo));
9712            if (retCode != 0) {
9713                if (mNoDexOpt) {
9714                    /*
9715                     * If we're in an engineering build, programs are lazily run
9716                     * through dexopt. If the .dex file doesn't exist yet, it
9717                     * will be created when the program is run next.
9718                     */
9719                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9720                } else {
9721                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9722                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9723                }
9724            }
9725        }
9726        return PackageManager.INSTALL_SUCCEEDED;
9727    }
9728
9729    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9730            int[] allUsers, boolean[] perUserInstalled,
9731            PackageInstalledInfo res) {
9732        String pkgName = newPackage.packageName;
9733        synchronized (mPackages) {
9734            //write settings. the installStatus will be incomplete at this stage.
9735            //note that the new package setting would have already been
9736            //added to mPackages. It hasn't been persisted yet.
9737            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9738            mSettings.writeLPr();
9739        }
9740
9741        if ((res.returnCode = moveDexFilesLI(newPackage))
9742                != PackageManager.INSTALL_SUCCEEDED) {
9743            // Discontinue if moving dex files failed.
9744            return;
9745        }
9746
9747        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9748
9749        synchronized (mPackages) {
9750            updatePermissionsLPw(newPackage.packageName, newPackage,
9751                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9752                            ? UPDATE_PERMISSIONS_ALL : 0));
9753            // For system-bundled packages, we assume that installing an upgraded version
9754            // of the package implies that the user actually wants to run that new code,
9755            // so we enable the package.
9756            if (isSystemApp(newPackage)) {
9757                // NB: implicit assumption that system package upgrades apply to all users
9758                if (DEBUG_INSTALL) {
9759                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9760                }
9761                PackageSetting ps = mSettings.mPackages.get(pkgName);
9762                if (ps != null) {
9763                    if (res.origUsers != null) {
9764                        for (int userHandle : res.origUsers) {
9765                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9766                                    userHandle, installerPackageName);
9767                        }
9768                    }
9769                    // Also convey the prior install/uninstall state
9770                    if (allUsers != null && perUserInstalled != null) {
9771                        for (int i = 0; i < allUsers.length; i++) {
9772                            if (DEBUG_INSTALL) {
9773                                Slog.d(TAG, "    user " + allUsers[i]
9774                                        + " => " + perUserInstalled[i]);
9775                            }
9776                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9777                        }
9778                        // these install state changes will be persisted in the
9779                        // upcoming call to mSettings.writeLPr().
9780                    }
9781                }
9782            }
9783            res.name = pkgName;
9784            res.uid = newPackage.applicationInfo.uid;
9785            res.pkg = newPackage;
9786            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9787            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9788            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9789            //to update install status
9790            mSettings.writeLPr();
9791        }
9792    }
9793
9794    private void installPackageLI(InstallArgs args,
9795            boolean newInstall, PackageInstalledInfo res) {
9796        int pFlags = args.flags;
9797        String installerPackageName = args.installerPackageName;
9798        File tmpPackageFile = new File(args.getCodePath());
9799        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9800        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9801        boolean replace = false;
9802        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9803                | (newInstall ? SCAN_NEW_INSTALL : 0);
9804        // Result object to be returned
9805        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9806
9807        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9808        // Retrieve PackageSettings and parse package
9809        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9810                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9811                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9812        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9813        pp.setSeparateProcesses(mSeparateProcesses);
9814        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9815                null, mMetrics, parseFlags);
9816        if (pkg == null) {
9817            res.returnCode = pp.getParseError();
9818            return;
9819        }
9820        String pkgName = res.name = pkg.packageName;
9821        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9822            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9823                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9824                return;
9825            }
9826        }
9827        if (!pp.collectCertificates(pkg, parseFlags)) {
9828            res.returnCode = pp.getParseError();
9829            return;
9830        }
9831
9832        /* If the installer passed in a manifest digest, compare it now. */
9833        if (args.manifestDigest != null) {
9834            if (DEBUG_INSTALL) {
9835                final String parsedManifest = pkg.manifestDigest == null ? "null"
9836                        : pkg.manifestDigest.toString();
9837                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9838                        + parsedManifest);
9839            }
9840
9841            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9842                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9843                return;
9844            }
9845        } else if (DEBUG_INSTALL) {
9846            final String parsedManifest = pkg.manifestDigest == null
9847                    ? "null" : pkg.manifestDigest.toString();
9848            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9849        }
9850
9851        // Get rid of all references to package scan path via parser.
9852        pp = null;
9853        String oldCodePath = null;
9854        boolean systemApp = false;
9855        synchronized (mPackages) {
9856            // Check whether the newly-scanned package wants to define an already-defined perm
9857            int N = pkg.permissions.size();
9858            for (int i = 0; i < N; i++) {
9859                PackageParser.Permission perm = pkg.permissions.get(i);
9860                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
9861                if (bp != null) {
9862                    // If the defining package is signed with our cert, it's okay.  This
9863                    // also includes the "updating the same package" case, of course.
9864                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
9865                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9866                        Slog.w(TAG, "Package " + pkg.packageName
9867                                + " attempting to redeclare permission " + perm.info.name
9868                                + " already owned by " + bp.sourcePackage);
9869                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
9870                        res.origPermission = perm.info.name;
9871                        res.origPackage = bp.sourcePackage;
9872                        return;
9873                    }
9874                }
9875            }
9876
9877            // Check if installing already existing package
9878            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9879                String oldName = mSettings.mRenamedPackages.get(pkgName);
9880                if (pkg.mOriginalPackages != null
9881                        && pkg.mOriginalPackages.contains(oldName)
9882                        && mPackages.containsKey(oldName)) {
9883                    // This package is derived from an original package,
9884                    // and this device has been updating from that original
9885                    // name.  We must continue using the original name, so
9886                    // rename the new package here.
9887                    pkg.setPackageName(oldName);
9888                    pkgName = pkg.packageName;
9889                    replace = true;
9890                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9891                            + oldName + " pkgName=" + pkgName);
9892                } else if (mPackages.containsKey(pkgName)) {
9893                    // This package, under its official name, already exists
9894                    // on the device; we should replace it.
9895                    replace = true;
9896                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9897                }
9898            }
9899            PackageSetting ps = mSettings.mPackages.get(pkgName);
9900            if (ps != null) {
9901                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9902                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9903                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9904                    systemApp = (ps.pkg.applicationInfo.flags &
9905                            ApplicationInfo.FLAG_SYSTEM) != 0;
9906                }
9907                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9908            }
9909        }
9910
9911        if (systemApp && onSd) {
9912            // Disable updates to system apps on sdcard
9913            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9914            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9915            return;
9916        }
9917
9918        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9919            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9920            return;
9921        }
9922        // Set application objects path explicitly after the rename
9923        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9924        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9925        if (replace) {
9926            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9927                    installerPackageName, res);
9928        } else {
9929            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9930                    installerPackageName, res);
9931        }
9932        synchronized (mPackages) {
9933            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9934            if (ps != null) {
9935                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9936            }
9937        }
9938    }
9939
9940    private static boolean isForwardLocked(PackageParser.Package pkg) {
9941        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9942    }
9943
9944
9945    private boolean isForwardLocked(PackageSetting ps) {
9946        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9947    }
9948
9949    private static boolean isExternal(PackageParser.Package pkg) {
9950        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9951    }
9952
9953    private static boolean isExternal(PackageSetting ps) {
9954        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9955    }
9956
9957    private static boolean isSystemApp(PackageParser.Package pkg) {
9958        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9959    }
9960
9961    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9962        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9963    }
9964
9965    private static boolean isSystemApp(ApplicationInfo info) {
9966        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9967    }
9968
9969    private static boolean isSystemApp(PackageSetting ps) {
9970        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9971    }
9972
9973    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9974        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9975    }
9976
9977    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9978        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9979    }
9980
9981    private int packageFlagsToInstallFlags(PackageSetting ps) {
9982        int installFlags = 0;
9983        if (isExternal(ps)) {
9984            installFlags |= PackageManager.INSTALL_EXTERNAL;
9985        }
9986        if (isForwardLocked(ps)) {
9987            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9988        }
9989        return installFlags;
9990    }
9991
9992    private void deleteTempPackageFiles() {
9993        final FilenameFilter filter = new FilenameFilter() {
9994            public boolean accept(File dir, String name) {
9995                return name.startsWith("vmdl") && name.endsWith(".tmp");
9996            }
9997        };
9998        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9999        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10000    }
10001
10002    private static final void deleteTempPackageFilesInDirectory(File directory,
10003            FilenameFilter filter) {
10004        final String[] tmpFilesList = directory.list(filter);
10005        if (tmpFilesList == null) {
10006            return;
10007        }
10008        for (int i = 0; i < tmpFilesList.length; i++) {
10009            final File tmpFile = new File(directory, tmpFilesList[i]);
10010            tmpFile.delete();
10011        }
10012    }
10013
10014    private File createTempPackageFile(File installDir) {
10015        File tmpPackageFile;
10016        try {
10017            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10018        } catch (IOException e) {
10019            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10020            return null;
10021        }
10022        try {
10023            FileUtils.setPermissions(
10024                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10025                    -1, -1);
10026            if (!SELinux.restorecon(tmpPackageFile)) {
10027                return null;
10028            }
10029        } catch (IOException e) {
10030            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10031            return null;
10032        }
10033        return tmpPackageFile;
10034    }
10035
10036    @Override
10037    public void deletePackageAsUser(final String packageName,
10038                                    final IPackageDeleteObserver observer,
10039                                    final int userId, final int flags) {
10040        mContext.enforceCallingOrSelfPermission(
10041                android.Manifest.permission.DELETE_PACKAGES, null);
10042        final int uid = Binder.getCallingUid();
10043        if (UserHandle.getUserId(uid) != userId) {
10044            mContext.enforceCallingPermission(
10045                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10046                    "deletePackage for user " + userId);
10047        }
10048        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10049            try {
10050                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10051            } catch (RemoteException re) {
10052            }
10053            return;
10054        }
10055
10056        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10057        // Queue up an async operation since the package deletion may take a little while.
10058        mHandler.post(new Runnable() {
10059            public void run() {
10060                mHandler.removeCallbacks(this);
10061                final int returnCode = deletePackageX(packageName, userId, flags);
10062                if (observer != null) {
10063                    try {
10064                        observer.packageDeleted(packageName, returnCode);
10065                    } catch (RemoteException e) {
10066                        Log.i(TAG, "Observer no longer exists.");
10067                    } //end catch
10068                } //end if
10069            } //end run
10070        });
10071    }
10072
10073    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10074        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10075                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10076        try {
10077            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10078                    || dpm.isDeviceOwner(packageName))) {
10079                return true;
10080            }
10081        } catch (RemoteException e) {
10082        }
10083        return false;
10084    }
10085
10086    /**
10087     *  This method is an internal method that could be get invoked either
10088     *  to delete an installed package or to clean up a failed installation.
10089     *  After deleting an installed package, a broadcast is sent to notify any
10090     *  listeners that the package has been installed. For cleaning up a failed
10091     *  installation, the broadcast is not necessary since the package's
10092     *  installation wouldn't have sent the initial broadcast either
10093     *  The key steps in deleting a package are
10094     *  deleting the package information in internal structures like mPackages,
10095     *  deleting the packages base directories through installd
10096     *  updating mSettings to reflect current status
10097     *  persisting settings for later use
10098     *  sending a broadcast if necessary
10099     */
10100    private int deletePackageX(String packageName, int userId, int flags) {
10101        final PackageRemovedInfo info = new PackageRemovedInfo();
10102        final boolean res;
10103
10104        if (isPackageDeviceAdmin(packageName, userId)) {
10105            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10106            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10107        }
10108
10109        boolean removedForAllUsers = false;
10110        boolean systemUpdate = false;
10111
10112        // for the uninstall-updates case and restricted profiles, remember the per-
10113        // userhandle installed state
10114        int[] allUsers;
10115        boolean[] perUserInstalled;
10116        synchronized (mPackages) {
10117            PackageSetting ps = mSettings.mPackages.get(packageName);
10118            allUsers = sUserManager.getUserIds();
10119            perUserInstalled = new boolean[allUsers.length];
10120            for (int i = 0; i < allUsers.length; i++) {
10121                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10122            }
10123        }
10124
10125        synchronized (mInstallLock) {
10126            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10127            res = deletePackageLI(packageName,
10128                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10129                            ? UserHandle.ALL : new UserHandle(userId),
10130                    true, allUsers, perUserInstalled,
10131                    flags | REMOVE_CHATTY, info, true);
10132            systemUpdate = info.isRemovedPackageSystemUpdate;
10133            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10134                removedForAllUsers = true;
10135            }
10136            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10137                    + " removedForAllUsers=" + removedForAllUsers);
10138        }
10139
10140        if (res) {
10141            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10142
10143            // If the removed package was a system update, the old system package
10144            // was re-enabled; we need to broadcast this information
10145            if (systemUpdate) {
10146                Bundle extras = new Bundle(1);
10147                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10148                        ? info.removedAppId : info.uid);
10149                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10150
10151                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10152                        extras, null, null, null);
10153                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10154                        extras, null, null, null);
10155                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10156                        null, packageName, null, null);
10157            }
10158        }
10159        // Force a gc here.
10160        Runtime.getRuntime().gc();
10161        // Delete the resources here after sending the broadcast to let
10162        // other processes clean up before deleting resources.
10163        if (info.args != null) {
10164            synchronized (mInstallLock) {
10165                info.args.doPostDeleteLI(true);
10166            }
10167        }
10168
10169        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10170    }
10171
10172    static class PackageRemovedInfo {
10173        String removedPackage;
10174        int uid = -1;
10175        int removedAppId = -1;
10176        int[] removedUsers = null;
10177        boolean isRemovedPackageSystemUpdate = false;
10178        // Clean up resources deleted packages.
10179        InstallArgs args = null;
10180
10181        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10182            Bundle extras = new Bundle(1);
10183            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10184            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10185            if (replacing) {
10186                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10187            }
10188            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10189            if (removedPackage != null) {
10190                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10191                        extras, null, null, removedUsers);
10192                if (fullRemove && !replacing) {
10193                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10194                            extras, null, null, removedUsers);
10195                }
10196            }
10197            if (removedAppId >= 0) {
10198                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10199                        removedUsers);
10200            }
10201        }
10202    }
10203
10204    /*
10205     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10206     * flag is not set, the data directory is removed as well.
10207     * make sure this flag is set for partially installed apps. If not its meaningless to
10208     * delete a partially installed application.
10209     */
10210    private void removePackageDataLI(PackageSetting ps,
10211            int[] allUserHandles, boolean[] perUserInstalled,
10212            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10213        String packageName = ps.name;
10214        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10215        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10216        // Retrieve object to delete permissions for shared user later on
10217        final PackageSetting deletedPs;
10218        // reader
10219        synchronized (mPackages) {
10220            deletedPs = mSettings.mPackages.get(packageName);
10221            if (outInfo != null) {
10222                outInfo.removedPackage = packageName;
10223                outInfo.removedUsers = deletedPs != null
10224                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10225                        : null;
10226            }
10227        }
10228        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10229            removeDataDirsLI(packageName);
10230            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10231        }
10232        // writer
10233        synchronized (mPackages) {
10234            if (deletedPs != null) {
10235                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10236                    if (outInfo != null) {
10237                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10238                    }
10239                    if (deletedPs != null) {
10240                        updatePermissionsLPw(deletedPs.name, null, 0);
10241                        if (deletedPs.sharedUser != null) {
10242                            // remove permissions associated with package
10243                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10244                        }
10245                    }
10246                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10247                }
10248                // make sure to preserve per-user disabled state if this removal was just
10249                // a downgrade of a system app to the factory package
10250                if (allUserHandles != null && perUserInstalled != null) {
10251                    if (DEBUG_REMOVE) {
10252                        Slog.d(TAG, "Propagating install state across downgrade");
10253                    }
10254                    for (int i = 0; i < allUserHandles.length; i++) {
10255                        if (DEBUG_REMOVE) {
10256                            Slog.d(TAG, "    user " + allUserHandles[i]
10257                                    + " => " + perUserInstalled[i]);
10258                        }
10259                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10260                    }
10261                }
10262            }
10263            // can downgrade to reader
10264            if (writeSettings) {
10265                // Save settings now
10266                mSettings.writeLPr();
10267            }
10268        }
10269        if (outInfo != null) {
10270            // A user ID was deleted here. Go through all users and remove it
10271            // from KeyStore.
10272            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10273        }
10274    }
10275
10276    static boolean locationIsPrivileged(File path) {
10277        try {
10278            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10279                    .getCanonicalPath();
10280            return path.getCanonicalPath().startsWith(privilegedAppDir);
10281        } catch (IOException e) {
10282            Slog.e(TAG, "Unable to access code path " + path);
10283        }
10284        return false;
10285    }
10286
10287    /*
10288     * Tries to delete system package.
10289     */
10290    private boolean deleteSystemPackageLI(PackageSetting newPs,
10291            int[] allUserHandles, boolean[] perUserInstalled,
10292            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10293        final boolean applyUserRestrictions
10294                = (allUserHandles != null) && (perUserInstalled != null);
10295        PackageSetting disabledPs = null;
10296        // Confirm if the system package has been updated
10297        // An updated system app can be deleted. This will also have to restore
10298        // the system pkg from system partition
10299        // reader
10300        synchronized (mPackages) {
10301            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10302        }
10303        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10304                + " disabledPs=" + disabledPs);
10305        if (disabledPs == null) {
10306            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10307            return false;
10308        } else if (DEBUG_REMOVE) {
10309            Slog.d(TAG, "Deleting system pkg from data partition");
10310        }
10311        if (DEBUG_REMOVE) {
10312            if (applyUserRestrictions) {
10313                Slog.d(TAG, "Remembering install states:");
10314                for (int i = 0; i < allUserHandles.length; i++) {
10315                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10316                }
10317            }
10318        }
10319        // Delete the updated package
10320        outInfo.isRemovedPackageSystemUpdate = true;
10321        if (disabledPs.versionCode < newPs.versionCode) {
10322            // Delete data for downgrades
10323            flags &= ~PackageManager.DELETE_KEEP_DATA;
10324        } else {
10325            // Preserve data by setting flag
10326            flags |= PackageManager.DELETE_KEEP_DATA;
10327        }
10328        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10329                allUserHandles, perUserInstalled, outInfo, writeSettings);
10330        if (!ret) {
10331            return false;
10332        }
10333        // writer
10334        synchronized (mPackages) {
10335            // Reinstate the old system package
10336            mSettings.enableSystemPackageLPw(newPs.name);
10337            // Remove any native libraries from the upgraded package.
10338            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10339        }
10340        // Install the system package
10341        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10342        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10343        if (locationIsPrivileged(disabledPs.codePath)) {
10344            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10345        }
10346        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10347                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10348
10349        if (newPkg == null) {
10350            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10351                    + " with error:" + mLastScanError);
10352            return false;
10353        }
10354        // writer
10355        synchronized (mPackages) {
10356            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10357            setInternalAppNativeLibraryPath(newPkg, ps);
10358            updatePermissionsLPw(newPkg.packageName, newPkg,
10359                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10360            if (applyUserRestrictions) {
10361                if (DEBUG_REMOVE) {
10362                    Slog.d(TAG, "Propagating install state across reinstall");
10363                }
10364                for (int i = 0; i < allUserHandles.length; i++) {
10365                    if (DEBUG_REMOVE) {
10366                        Slog.d(TAG, "    user " + allUserHandles[i]
10367                                + " => " + perUserInstalled[i]);
10368                    }
10369                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10370                }
10371                // Regardless of writeSettings we need to ensure that this restriction
10372                // state propagation is persisted
10373                mSettings.writeAllUsersPackageRestrictionsLPr();
10374            }
10375            // can downgrade to reader here
10376            if (writeSettings) {
10377                mSettings.writeLPr();
10378            }
10379        }
10380        return true;
10381    }
10382
10383    private boolean deleteInstalledPackageLI(PackageSetting ps,
10384            boolean deleteCodeAndResources, int flags,
10385            int[] allUserHandles, boolean[] perUserInstalled,
10386            PackageRemovedInfo outInfo, boolean writeSettings) {
10387        if (outInfo != null) {
10388            outInfo.uid = ps.appId;
10389        }
10390
10391        // Delete package data from internal structures and also remove data if flag is set
10392        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10393
10394        // Delete application code and resources
10395        if (deleteCodeAndResources && (outInfo != null)) {
10396            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10397                    ps.resourcePathString, ps.nativeLibraryPathString,
10398                    getAppInstructionSetFromSettings(ps));
10399        }
10400        return true;
10401    }
10402
10403    /*
10404     * This method handles package deletion in general
10405     */
10406    private boolean deletePackageLI(String packageName, UserHandle user,
10407            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10408            int flags, PackageRemovedInfo outInfo,
10409            boolean writeSettings) {
10410        if (packageName == null) {
10411            Slog.w(TAG, "Attempt to delete null packageName.");
10412            return false;
10413        }
10414        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10415        PackageSetting ps;
10416        boolean dataOnly = false;
10417        int removeUser = -1;
10418        int appId = -1;
10419        synchronized (mPackages) {
10420            ps = mSettings.mPackages.get(packageName);
10421            if (ps == null) {
10422                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10423                return false;
10424            }
10425            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10426                    && user.getIdentifier() != UserHandle.USER_ALL) {
10427                // The caller is asking that the package only be deleted for a single
10428                // user.  To do this, we just mark its uninstalled state and delete
10429                // its data.  If this is a system app, we only allow this to happen if
10430                // they have set the special DELETE_SYSTEM_APP which requests different
10431                // semantics than normal for uninstalling system apps.
10432                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10433                ps.setUserState(user.getIdentifier(),
10434                        COMPONENT_ENABLED_STATE_DEFAULT,
10435                        false, //installed
10436                        true,  //stopped
10437                        true,  //notLaunched
10438                        false, //blocked
10439                        null, null, null);
10440                if (!isSystemApp(ps)) {
10441                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10442                        // Other user still have this package installed, so all
10443                        // we need to do is clear this user's data and save that
10444                        // it is uninstalled.
10445                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10446                        removeUser = user.getIdentifier();
10447                        appId = ps.appId;
10448                        mSettings.writePackageRestrictionsLPr(removeUser);
10449                    } else {
10450                        // We need to set it back to 'installed' so the uninstall
10451                        // broadcasts will be sent correctly.
10452                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10453                        ps.setInstalled(true, user.getIdentifier());
10454                    }
10455                } else {
10456                    // This is a system app, so we assume that the
10457                    // other users still have this package installed, so all
10458                    // we need to do is clear this user's data and save that
10459                    // it is uninstalled.
10460                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10461                    removeUser = user.getIdentifier();
10462                    appId = ps.appId;
10463                    mSettings.writePackageRestrictionsLPr(removeUser);
10464                }
10465            }
10466        }
10467
10468        if (removeUser >= 0) {
10469            // From above, we determined that we are deleting this only
10470            // for a single user.  Continue the work here.
10471            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10472            if (outInfo != null) {
10473                outInfo.removedPackage = packageName;
10474                outInfo.removedAppId = appId;
10475                outInfo.removedUsers = new int[] {removeUser};
10476            }
10477            mInstaller.clearUserData(packageName, removeUser);
10478            removeKeystoreDataIfNeeded(removeUser, appId);
10479            schedulePackageCleaning(packageName, removeUser, false);
10480            return true;
10481        }
10482
10483        if (dataOnly) {
10484            // Delete application data first
10485            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10486            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10487            return true;
10488        }
10489
10490        boolean ret = false;
10491        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10492        if (isSystemApp(ps)) {
10493            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10494            // When an updated system application is deleted we delete the existing resources as well and
10495            // fall back to existing code in system partition
10496            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10497                    flags, outInfo, writeSettings);
10498        } else {
10499            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10500            // Kill application pre-emptively especially for apps on sd.
10501            killApplication(packageName, ps.appId, "uninstall pkg");
10502            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10503                    allUserHandles, perUserInstalled,
10504                    outInfo, writeSettings);
10505        }
10506
10507        return ret;
10508    }
10509
10510    private final class ClearStorageConnection implements ServiceConnection {
10511        IMediaContainerService mContainerService;
10512
10513        @Override
10514        public void onServiceConnected(ComponentName name, IBinder service) {
10515            synchronized (this) {
10516                mContainerService = IMediaContainerService.Stub.asInterface(service);
10517                notifyAll();
10518            }
10519        }
10520
10521        @Override
10522        public void onServiceDisconnected(ComponentName name) {
10523        }
10524    }
10525
10526    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10527        final boolean mounted;
10528        if (Environment.isExternalStorageEmulated()) {
10529            mounted = true;
10530        } else {
10531            final String status = Environment.getExternalStorageState();
10532
10533            mounted = status.equals(Environment.MEDIA_MOUNTED)
10534                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10535        }
10536
10537        if (!mounted) {
10538            return;
10539        }
10540
10541        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10542        int[] users;
10543        if (userId == UserHandle.USER_ALL) {
10544            users = sUserManager.getUserIds();
10545        } else {
10546            users = new int[] { userId };
10547        }
10548        final ClearStorageConnection conn = new ClearStorageConnection();
10549        if (mContext.bindServiceAsUser(
10550                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10551            try {
10552                for (int curUser : users) {
10553                    long timeout = SystemClock.uptimeMillis() + 5000;
10554                    synchronized (conn) {
10555                        long now = SystemClock.uptimeMillis();
10556                        while (conn.mContainerService == null && now < timeout) {
10557                            try {
10558                                conn.wait(timeout - now);
10559                            } catch (InterruptedException e) {
10560                            }
10561                        }
10562                    }
10563                    if (conn.mContainerService == null) {
10564                        return;
10565                    }
10566
10567                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10568                    clearDirectory(conn.mContainerService,
10569                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10570                    if (allData) {
10571                        clearDirectory(conn.mContainerService,
10572                                userEnv.buildExternalStorageAppDataDirs(packageName));
10573                        clearDirectory(conn.mContainerService,
10574                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10575                    }
10576                }
10577            } finally {
10578                mContext.unbindService(conn);
10579            }
10580        }
10581    }
10582
10583    @Override
10584    public void clearApplicationUserData(final String packageName,
10585            final IPackageDataObserver observer, final int userId) {
10586        mContext.enforceCallingOrSelfPermission(
10587                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10588        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10589        // Queue up an async operation since the package deletion may take a little while.
10590        mHandler.post(new Runnable() {
10591            public void run() {
10592                mHandler.removeCallbacks(this);
10593                final boolean succeeded;
10594                synchronized (mInstallLock) {
10595                    succeeded = clearApplicationUserDataLI(packageName, userId);
10596                }
10597                clearExternalStorageDataSync(packageName, userId, true);
10598                if (succeeded) {
10599                    // invoke DeviceStorageMonitor's update method to clear any notifications
10600                    DeviceStorageMonitorInternal
10601                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10602                    if (dsm != null) {
10603                        dsm.checkMemory();
10604                    }
10605                }
10606                if(observer != null) {
10607                    try {
10608                        observer.onRemoveCompleted(packageName, succeeded);
10609                    } catch (RemoteException e) {
10610                        Log.i(TAG, "Observer no longer exists.");
10611                    }
10612                } //end if observer
10613            } //end run
10614        });
10615    }
10616
10617    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10618        if (packageName == null) {
10619            Slog.w(TAG, "Attempt to delete null packageName.");
10620            return false;
10621        }
10622        PackageParser.Package p;
10623        boolean dataOnly = false;
10624        final int appId;
10625        synchronized (mPackages) {
10626            p = mPackages.get(packageName);
10627            if (p == null) {
10628                dataOnly = true;
10629                PackageSetting ps = mSettings.mPackages.get(packageName);
10630                if ((ps == null) || (ps.pkg == null)) {
10631                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10632                    return false;
10633                }
10634                p = ps.pkg;
10635            }
10636            if (!dataOnly) {
10637                // need to check this only for fully installed applications
10638                if (p == null) {
10639                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10640                    return false;
10641                }
10642                final ApplicationInfo applicationInfo = p.applicationInfo;
10643                if (applicationInfo == null) {
10644                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10645                    return false;
10646                }
10647            }
10648            if (p != null && p.applicationInfo != null) {
10649                appId = p.applicationInfo.uid;
10650            } else {
10651                appId = -1;
10652            }
10653        }
10654        int retCode = mInstaller.clearUserData(packageName, userId);
10655        if (retCode < 0) {
10656            Slog.w(TAG, "Couldn't remove cache files for package: "
10657                    + packageName);
10658            return false;
10659        }
10660        removeKeystoreDataIfNeeded(userId, appId);
10661        return true;
10662    }
10663
10664    /**
10665     * Remove entries from the keystore daemon. Will only remove it if the
10666     * {@code appId} is valid.
10667     */
10668    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10669        if (appId < 0) {
10670            return;
10671        }
10672
10673        final KeyStore keyStore = KeyStore.getInstance();
10674        if (keyStore != null) {
10675            if (userId == UserHandle.USER_ALL) {
10676                for (final int individual : sUserManager.getUserIds()) {
10677                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10678                }
10679            } else {
10680                keyStore.clearUid(UserHandle.getUid(userId, appId));
10681            }
10682        } else {
10683            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10684        }
10685    }
10686
10687    public void deleteApplicationCacheFiles(final String packageName,
10688            final IPackageDataObserver observer) {
10689        mContext.enforceCallingOrSelfPermission(
10690                android.Manifest.permission.DELETE_CACHE_FILES, null);
10691        // Queue up an async operation since the package deletion may take a little while.
10692        final int userId = UserHandle.getCallingUserId();
10693        mHandler.post(new Runnable() {
10694            public void run() {
10695                mHandler.removeCallbacks(this);
10696                final boolean succeded;
10697                synchronized (mInstallLock) {
10698                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10699                }
10700                clearExternalStorageDataSync(packageName, userId, false);
10701                if(observer != null) {
10702                    try {
10703                        observer.onRemoveCompleted(packageName, succeded);
10704                    } catch (RemoteException e) {
10705                        Log.i(TAG, "Observer no longer exists.");
10706                    }
10707                } //end if observer
10708            } //end run
10709        });
10710    }
10711
10712    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10713        if (packageName == null) {
10714            Slog.w(TAG, "Attempt to delete null packageName.");
10715            return false;
10716        }
10717        PackageParser.Package p;
10718        synchronized (mPackages) {
10719            p = mPackages.get(packageName);
10720        }
10721        if (p == null) {
10722            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10723            return false;
10724        }
10725        final ApplicationInfo applicationInfo = p.applicationInfo;
10726        if (applicationInfo == null) {
10727            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10728            return false;
10729        }
10730        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10731        if (retCode < 0) {
10732            Slog.w(TAG, "Couldn't remove cache files for package: "
10733                       + packageName + " u" + userId);
10734            return false;
10735        }
10736        return true;
10737    }
10738
10739    public void getPackageSizeInfo(final String packageName, int userHandle,
10740            final IPackageStatsObserver observer) {
10741        mContext.enforceCallingOrSelfPermission(
10742                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10743        if (packageName == null) {
10744            throw new IllegalArgumentException("Attempt to get size of null packageName");
10745        }
10746
10747        PackageStats stats = new PackageStats(packageName, userHandle);
10748
10749        /*
10750         * Queue up an async operation since the package measurement may take a
10751         * little while.
10752         */
10753        Message msg = mHandler.obtainMessage(INIT_COPY);
10754        msg.obj = new MeasureParams(stats, observer);
10755        mHandler.sendMessage(msg);
10756    }
10757
10758    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10759            PackageStats pStats) {
10760        if (packageName == null) {
10761            Slog.w(TAG, "Attempt to get size of null packageName.");
10762            return false;
10763        }
10764        PackageParser.Package p;
10765        boolean dataOnly = false;
10766        String libDirPath = null;
10767        String asecPath = null;
10768        PackageSetting ps = null;
10769        synchronized (mPackages) {
10770            p = mPackages.get(packageName);
10771            ps = mSettings.mPackages.get(packageName);
10772            if(p == null) {
10773                dataOnly = true;
10774                if((ps == null) || (ps.pkg == null)) {
10775                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10776                    return false;
10777                }
10778                p = ps.pkg;
10779            }
10780            if (ps != null) {
10781                libDirPath = ps.nativeLibraryPathString;
10782            }
10783            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10784                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10785                if (secureContainerId != null) {
10786                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10787                }
10788            }
10789        }
10790        String publicSrcDir = null;
10791        if(!dataOnly) {
10792            final ApplicationInfo applicationInfo = p.applicationInfo;
10793            if (applicationInfo == null) {
10794                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10795                return false;
10796            }
10797            if (isForwardLocked(p)) {
10798                publicSrcDir = applicationInfo.publicSourceDir;
10799            }
10800        }
10801        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10802                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10803                pStats);
10804        if (res < 0) {
10805            return false;
10806        }
10807
10808        // Fix-up for forward-locked applications in ASEC containers.
10809        if (!isExternal(p)) {
10810            pStats.codeSize += pStats.externalCodeSize;
10811            pStats.externalCodeSize = 0L;
10812        }
10813
10814        return true;
10815    }
10816
10817
10818    public void addPackageToPreferred(String packageName) {
10819        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10820    }
10821
10822    public void removePackageFromPreferred(String packageName) {
10823        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10824    }
10825
10826    public List<PackageInfo> getPreferredPackages(int flags) {
10827        return new ArrayList<PackageInfo>();
10828    }
10829
10830    private int getUidTargetSdkVersionLockedLPr(int uid) {
10831        Object obj = mSettings.getUserIdLPr(uid);
10832        if (obj instanceof SharedUserSetting) {
10833            final SharedUserSetting sus = (SharedUserSetting) obj;
10834            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10835            final Iterator<PackageSetting> it = sus.packages.iterator();
10836            while (it.hasNext()) {
10837                final PackageSetting ps = it.next();
10838                if (ps.pkg != null) {
10839                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10840                    if (v < vers) vers = v;
10841                }
10842            }
10843            return vers;
10844        } else if (obj instanceof PackageSetting) {
10845            final PackageSetting ps = (PackageSetting) obj;
10846            if (ps.pkg != null) {
10847                return ps.pkg.applicationInfo.targetSdkVersion;
10848            }
10849        }
10850        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10851    }
10852
10853    public void addPreferredActivity(IntentFilter filter, int match,
10854            ComponentName[] set, ComponentName activity, int userId) {
10855        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10856    }
10857
10858    private void addPreferredActivityInternal(IntentFilter filter, int match,
10859            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10860        // writer
10861        int callingUid = Binder.getCallingUid();
10862        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10863        if (filter.countActions() == 0) {
10864            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10865            return;
10866        }
10867        synchronized (mPackages) {
10868            if (mContext.checkCallingOrSelfPermission(
10869                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10870                    != PackageManager.PERMISSION_GRANTED) {
10871                if (getUidTargetSdkVersionLockedLPr(callingUid)
10872                        < Build.VERSION_CODES.FROYO) {
10873                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10874                            + callingUid);
10875                    return;
10876                }
10877                mContext.enforceCallingOrSelfPermission(
10878                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10879            }
10880
10881            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10882            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10883            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10884                    new PreferredActivity(filter, match, set, activity, always));
10885            mSettings.writePackageRestrictionsLPr(userId);
10886        }
10887    }
10888
10889    public void replacePreferredActivity(IntentFilter filter, int match,
10890            ComponentName[] set, ComponentName activity) {
10891        if (filter.countActions() != 1) {
10892            throw new IllegalArgumentException(
10893                    "replacePreferredActivity expects filter to have only 1 action.");
10894        }
10895        if (filter.countDataAuthorities() != 0
10896                || filter.countDataPaths() != 0
10897                || filter.countDataSchemes() > 1
10898                || filter.countDataTypes() != 0) {
10899            throw new IllegalArgumentException(
10900                    "replacePreferredActivity expects filter to have no data authorities, " +
10901                    "paths, or types; and at most one scheme.");
10902        }
10903        synchronized (mPackages) {
10904            if (mContext.checkCallingOrSelfPermission(
10905                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10906                    != PackageManager.PERMISSION_GRANTED) {
10907                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10908                        < Build.VERSION_CODES.FROYO) {
10909                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10910                            + Binder.getCallingUid());
10911                    return;
10912                }
10913                mContext.enforceCallingOrSelfPermission(
10914                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10915            }
10916
10917            final int callingUserId = UserHandle.getCallingUserId();
10918            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10919            if (pir != null) {
10920                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10921                if (filter.countDataSchemes() == 1) {
10922                    Uri.Builder builder = new Uri.Builder();
10923                    builder.scheme(filter.getDataScheme(0));
10924                    intent.setData(builder.build());
10925                }
10926                List<PreferredActivity> matches = pir.queryIntent(
10927                        intent, null, true, callingUserId);
10928                if (DEBUG_PREFERRED) {
10929                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10930                }
10931                for (int i = 0; i < matches.size(); i++) {
10932                    PreferredActivity pa = matches.get(i);
10933                    if (DEBUG_PREFERRED) {
10934                        Slog.i(TAG, "Removing preferred activity "
10935                                + pa.mPref.mComponent + ":");
10936                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10937                    }
10938                    pir.removeFilter(pa);
10939                }
10940            }
10941            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10942        }
10943    }
10944
10945    public void clearPackagePreferredActivities(String packageName) {
10946        final int uid = Binder.getCallingUid();
10947        // writer
10948        synchronized (mPackages) {
10949            PackageParser.Package pkg = mPackages.get(packageName);
10950            if (pkg == null || pkg.applicationInfo.uid != uid) {
10951                if (mContext.checkCallingOrSelfPermission(
10952                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10953                        != PackageManager.PERMISSION_GRANTED) {
10954                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10955                            < Build.VERSION_CODES.FROYO) {
10956                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10957                                + Binder.getCallingUid());
10958                        return;
10959                    }
10960                    mContext.enforceCallingOrSelfPermission(
10961                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10962                }
10963            }
10964
10965            int user = UserHandle.getCallingUserId();
10966            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10967                mSettings.writePackageRestrictionsLPr(user);
10968                scheduleWriteSettingsLocked();
10969            }
10970        }
10971    }
10972
10973    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10974    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10975        ArrayList<PreferredActivity> removed = null;
10976        boolean changed = false;
10977        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10978            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10979            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10980            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10981                continue;
10982            }
10983            Iterator<PreferredActivity> it = pir.filterIterator();
10984            while (it.hasNext()) {
10985                PreferredActivity pa = it.next();
10986                // Mark entry for removal only if it matches the package name
10987                // and the entry is of type "always".
10988                if (packageName == null ||
10989                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10990                                && pa.mPref.mAlways)) {
10991                    if (removed == null) {
10992                        removed = new ArrayList<PreferredActivity>();
10993                    }
10994                    removed.add(pa);
10995                }
10996            }
10997            if (removed != null) {
10998                for (int j=0; j<removed.size(); j++) {
10999                    PreferredActivity pa = removed.get(j);
11000                    pir.removeFilter(pa);
11001                }
11002                changed = true;
11003            }
11004        }
11005        return changed;
11006    }
11007
11008    public void resetPreferredActivities(int userId) {
11009        mContext.enforceCallingOrSelfPermission(
11010                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11011        // writer
11012        synchronized (mPackages) {
11013            int user = UserHandle.getCallingUserId();
11014            clearPackagePreferredActivitiesLPw(null, user);
11015            mSettings.readDefaultPreferredAppsLPw(this, user);
11016            mSettings.writePackageRestrictionsLPr(user);
11017            scheduleWriteSettingsLocked();
11018        }
11019    }
11020
11021    public int getPreferredActivities(List<IntentFilter> outFilters,
11022            List<ComponentName> outActivities, String packageName) {
11023
11024        int num = 0;
11025        final int userId = UserHandle.getCallingUserId();
11026        // reader
11027        synchronized (mPackages) {
11028            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11029            if (pir != null) {
11030                final Iterator<PreferredActivity> it = pir.filterIterator();
11031                while (it.hasNext()) {
11032                    final PreferredActivity pa = it.next();
11033                    if (packageName == null
11034                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11035                                    && pa.mPref.mAlways)) {
11036                        if (outFilters != null) {
11037                            outFilters.add(new IntentFilter(pa));
11038                        }
11039                        if (outActivities != null) {
11040                            outActivities.add(pa.mPref.mComponent);
11041                        }
11042                    }
11043                }
11044            }
11045        }
11046
11047        return num;
11048    }
11049
11050    @Override
11051    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11052            int userId) {
11053        int callingUid = Binder.getCallingUid();
11054        if (callingUid != Process.SYSTEM_UID) {
11055            throw new SecurityException(
11056                    "addPersistentPreferredActivity can only be run by the system");
11057        }
11058        if (filter.countActions() == 0) {
11059            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11060            return;
11061        }
11062        synchronized (mPackages) {
11063            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11064                    " :");
11065            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11066            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11067                    new PersistentPreferredActivity(filter, activity));
11068            mSettings.writePackageRestrictionsLPr(userId);
11069        }
11070    }
11071
11072    @Override
11073    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11074        int callingUid = Binder.getCallingUid();
11075        if (callingUid != Process.SYSTEM_UID) {
11076            throw new SecurityException(
11077                    "clearPackagePersistentPreferredActivities can only be run by the system");
11078        }
11079        ArrayList<PersistentPreferredActivity> removed = null;
11080        boolean changed = false;
11081        synchronized (mPackages) {
11082            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11083                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11084                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11085                        .valueAt(i);
11086                if (userId != thisUserId) {
11087                    continue;
11088                }
11089                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11090                while (it.hasNext()) {
11091                    PersistentPreferredActivity ppa = it.next();
11092                    // Mark entry for removal only if it matches the package name.
11093                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11094                        if (removed == null) {
11095                            removed = new ArrayList<PersistentPreferredActivity>();
11096                        }
11097                        removed.add(ppa);
11098                    }
11099                }
11100                if (removed != null) {
11101                    for (int j=0; j<removed.size(); j++) {
11102                        PersistentPreferredActivity ppa = removed.get(j);
11103                        ppir.removeFilter(ppa);
11104                    }
11105                    changed = true;
11106                }
11107            }
11108
11109            if (changed) {
11110                mSettings.writePackageRestrictionsLPr(userId);
11111            }
11112        }
11113    }
11114
11115    @Override
11116    public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig,
11117            int userIdDest) {
11118        mContext.enforceCallingOrSelfPermission(
11119                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11120        if (filter.countActions() == 0) {
11121            Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions");
11122            return;
11123        }
11124        synchronized (mPackages) {
11125            mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter(
11126                    new ForwardingIntentFilter(filter, removable, userIdDest));
11127            mSettings.writePackageRestrictionsLPr(userIdOrig);
11128        }
11129    }
11130
11131    @Override
11132    public void clearForwardingIntentFilters(int userIdOrig) {
11133        mContext.enforceCallingOrSelfPermission(
11134                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11135        synchronized (mPackages) {
11136            ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig);
11137            HashSet<ForwardingIntentFilter> set =
11138                    new HashSet<ForwardingIntentFilter>(fir.filterSet());
11139            for (ForwardingIntentFilter fif : set) {
11140                if (fif.isRemovable()) fir.removeFilter(fif);
11141            }
11142            mSettings.writePackageRestrictionsLPr(userIdOrig);
11143        }
11144    }
11145
11146    @Override
11147    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11148        Intent intent = new Intent(Intent.ACTION_MAIN);
11149        intent.addCategory(Intent.CATEGORY_HOME);
11150
11151        final int callingUserId = UserHandle.getCallingUserId();
11152        List<ResolveInfo> list = queryIntentActivities(intent, null,
11153                PackageManager.GET_META_DATA, callingUserId);
11154        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11155                true, false, false, callingUserId);
11156
11157        allHomeCandidates.clear();
11158        if (list != null) {
11159            for (ResolveInfo ri : list) {
11160                allHomeCandidates.add(ri);
11161            }
11162        }
11163        return (preferred == null || preferred.activityInfo == null)
11164                ? null
11165                : new ComponentName(preferred.activityInfo.packageName,
11166                        preferred.activityInfo.name);
11167    }
11168
11169    @Override
11170    public void setApplicationEnabledSetting(String appPackageName,
11171            int newState, int flags, int userId, String callingPackage) {
11172        if (!sUserManager.exists(userId)) return;
11173        if (callingPackage == null) {
11174            callingPackage = Integer.toString(Binder.getCallingUid());
11175        }
11176        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11177    }
11178
11179    @Override
11180    public void setComponentEnabledSetting(ComponentName componentName,
11181            int newState, int flags, int userId) {
11182        if (!sUserManager.exists(userId)) return;
11183        setEnabledSetting(componentName.getPackageName(),
11184                componentName.getClassName(), newState, flags, userId, null);
11185    }
11186
11187    private void setEnabledSetting(final String packageName, String className, int newState,
11188            final int flags, int userId, String callingPackage) {
11189        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11190              || newState == COMPONENT_ENABLED_STATE_ENABLED
11191              || newState == COMPONENT_ENABLED_STATE_DISABLED
11192              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11193              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11194            throw new IllegalArgumentException("Invalid new component state: "
11195                    + newState);
11196        }
11197        PackageSetting pkgSetting;
11198        final int uid = Binder.getCallingUid();
11199        final int permission = mContext.checkCallingOrSelfPermission(
11200                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11201        enforceCrossUserPermission(uid, userId, false, "set enabled");
11202        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11203        boolean sendNow = false;
11204        boolean isApp = (className == null);
11205        String componentName = isApp ? packageName : className;
11206        int packageUid = -1;
11207        ArrayList<String> components;
11208
11209        // writer
11210        synchronized (mPackages) {
11211            pkgSetting = mSettings.mPackages.get(packageName);
11212            if (pkgSetting == null) {
11213                if (className == null) {
11214                    throw new IllegalArgumentException(
11215                            "Unknown package: " + packageName);
11216                }
11217                throw new IllegalArgumentException(
11218                        "Unknown component: " + packageName
11219                        + "/" + className);
11220            }
11221            // Allow root and verify that userId is not being specified by a different user
11222            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11223                throw new SecurityException(
11224                        "Permission Denial: attempt to change component state from pid="
11225                        + Binder.getCallingPid()
11226                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11227            }
11228            if (className == null) {
11229                // We're dealing with an application/package level state change
11230                if (pkgSetting.getEnabled(userId) == newState) {
11231                    // Nothing to do
11232                    return;
11233                }
11234                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11235                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11236                    // Don't care about who enables an app.
11237                    callingPackage = null;
11238                }
11239                pkgSetting.setEnabled(newState, userId, callingPackage);
11240                // pkgSetting.pkg.mSetEnabled = newState;
11241            } else {
11242                // We're dealing with a component level state change
11243                // First, verify that this is a valid class name.
11244                PackageParser.Package pkg = pkgSetting.pkg;
11245                if (pkg == null || !pkg.hasComponentClassName(className)) {
11246                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11247                        throw new IllegalArgumentException("Component class " + className
11248                                + " does not exist in " + packageName);
11249                    } else {
11250                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11251                                + className + " does not exist in " + packageName);
11252                    }
11253                }
11254                switch (newState) {
11255                case COMPONENT_ENABLED_STATE_ENABLED:
11256                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11257                        return;
11258                    }
11259                    break;
11260                case COMPONENT_ENABLED_STATE_DISABLED:
11261                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11262                        return;
11263                    }
11264                    break;
11265                case COMPONENT_ENABLED_STATE_DEFAULT:
11266                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11267                        return;
11268                    }
11269                    break;
11270                default:
11271                    Slog.e(TAG, "Invalid new component state: " + newState);
11272                    return;
11273                }
11274            }
11275            mSettings.writePackageRestrictionsLPr(userId);
11276            components = mPendingBroadcasts.get(userId, packageName);
11277            final boolean newPackage = components == null;
11278            if (newPackage) {
11279                components = new ArrayList<String>();
11280            }
11281            if (!components.contains(componentName)) {
11282                components.add(componentName);
11283            }
11284            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11285                sendNow = true;
11286                // Purge entry from pending broadcast list if another one exists already
11287                // since we are sending one right away.
11288                mPendingBroadcasts.remove(userId, packageName);
11289            } else {
11290                if (newPackage) {
11291                    mPendingBroadcasts.put(userId, packageName, components);
11292                }
11293                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11294                    // Schedule a message
11295                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11296                }
11297            }
11298        }
11299
11300        long callingId = Binder.clearCallingIdentity();
11301        try {
11302            if (sendNow) {
11303                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11304                sendPackageChangedBroadcast(packageName,
11305                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11306            }
11307        } finally {
11308            Binder.restoreCallingIdentity(callingId);
11309        }
11310    }
11311
11312    private void sendPackageChangedBroadcast(String packageName,
11313            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11314        if (DEBUG_INSTALL)
11315            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11316                    + componentNames);
11317        Bundle extras = new Bundle(4);
11318        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11319        String nameList[] = new String[componentNames.size()];
11320        componentNames.toArray(nameList);
11321        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11322        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11323        extras.putInt(Intent.EXTRA_UID, packageUid);
11324        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11325                new int[] {UserHandle.getUserId(packageUid)});
11326    }
11327
11328    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11329        if (!sUserManager.exists(userId)) return;
11330        final int uid = Binder.getCallingUid();
11331        final int permission = mContext.checkCallingOrSelfPermission(
11332                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11333        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11334        enforceCrossUserPermission(uid, userId, true, "stop package");
11335        // writer
11336        synchronized (mPackages) {
11337            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11338                    uid, userId)) {
11339                scheduleWritePackageRestrictionsLocked(userId);
11340            }
11341        }
11342    }
11343
11344    public String getInstallerPackageName(String packageName) {
11345        // reader
11346        synchronized (mPackages) {
11347            return mSettings.getInstallerPackageNameLPr(packageName);
11348        }
11349    }
11350
11351    @Override
11352    public int getApplicationEnabledSetting(String packageName, int userId) {
11353        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11354        int uid = Binder.getCallingUid();
11355        enforceCrossUserPermission(uid, userId, false, "get enabled");
11356        // reader
11357        synchronized (mPackages) {
11358            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11359        }
11360    }
11361
11362    @Override
11363    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11364        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11365        int uid = Binder.getCallingUid();
11366        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11367        // reader
11368        synchronized (mPackages) {
11369            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11370        }
11371    }
11372
11373    public void enterSafeMode() {
11374        enforceSystemOrRoot("Only the system can request entering safe mode");
11375
11376        if (!mSystemReady) {
11377            mSafeMode = true;
11378        }
11379    }
11380
11381    public void systemReady() {
11382        mSystemReady = true;
11383
11384        // Read the compatibilty setting when the system is ready.
11385        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11386                mContext.getContentResolver(),
11387                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11388        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11389        if (DEBUG_SETTINGS) {
11390            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11391        }
11392
11393        synchronized (mPackages) {
11394            // Verify that all of the preferred activity components actually
11395            // exist.  It is possible for applications to be updated and at
11396            // that point remove a previously declared activity component that
11397            // had been set as a preferred activity.  We try to clean this up
11398            // the next time we encounter that preferred activity, but it is
11399            // possible for the user flow to never be able to return to that
11400            // situation so here we do a sanity check to make sure we haven't
11401            // left any junk around.
11402            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11403            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11404                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11405                removed.clear();
11406                for (PreferredActivity pa : pir.filterSet()) {
11407                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11408                        removed.add(pa);
11409                    }
11410                }
11411                if (removed.size() > 0) {
11412                    for (int j=0; j<removed.size(); j++) {
11413                        PreferredActivity pa = removed.get(i);
11414                        Slog.w(TAG, "Removing dangling preferred activity: "
11415                                + pa.mPref.mComponent);
11416                        pir.removeFilter(pa);
11417                    }
11418                    mSettings.writePackageRestrictionsLPr(
11419                            mSettings.mPreferredActivities.keyAt(i));
11420                }
11421            }
11422        }
11423        sUserManager.systemReady();
11424    }
11425
11426    public boolean isSafeMode() {
11427        return mSafeMode;
11428    }
11429
11430    public boolean hasSystemUidErrors() {
11431        return mHasSystemUidErrors;
11432    }
11433
11434    static String arrayToString(int[] array) {
11435        StringBuffer buf = new StringBuffer(128);
11436        buf.append('[');
11437        if (array != null) {
11438            for (int i=0; i<array.length; i++) {
11439                if (i > 0) buf.append(", ");
11440                buf.append(array[i]);
11441            }
11442        }
11443        buf.append(']');
11444        return buf.toString();
11445    }
11446
11447    static class DumpState {
11448        public static final int DUMP_LIBS = 1 << 0;
11449
11450        public static final int DUMP_FEATURES = 1 << 1;
11451
11452        public static final int DUMP_RESOLVERS = 1 << 2;
11453
11454        public static final int DUMP_PERMISSIONS = 1 << 3;
11455
11456        public static final int DUMP_PACKAGES = 1 << 4;
11457
11458        public static final int DUMP_SHARED_USERS = 1 << 5;
11459
11460        public static final int DUMP_MESSAGES = 1 << 6;
11461
11462        public static final int DUMP_PROVIDERS = 1 << 7;
11463
11464        public static final int DUMP_VERIFIERS = 1 << 8;
11465
11466        public static final int DUMP_PREFERRED = 1 << 9;
11467
11468        public static final int DUMP_PREFERRED_XML = 1 << 10;
11469
11470        public static final int DUMP_KEYSETS = 1 << 11;
11471
11472        public static final int DUMP_VERSION = 1 << 12;
11473
11474        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11475
11476        private int mTypes;
11477
11478        private int mOptions;
11479
11480        private boolean mTitlePrinted;
11481
11482        private SharedUserSetting mSharedUser;
11483
11484        public boolean isDumping(int type) {
11485            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11486                return true;
11487            }
11488
11489            return (mTypes & type) != 0;
11490        }
11491
11492        public void setDump(int type) {
11493            mTypes |= type;
11494        }
11495
11496        public boolean isOptionEnabled(int option) {
11497            return (mOptions & option) != 0;
11498        }
11499
11500        public void setOptionEnabled(int option) {
11501            mOptions |= option;
11502        }
11503
11504        public boolean onTitlePrinted() {
11505            final boolean printed = mTitlePrinted;
11506            mTitlePrinted = true;
11507            return printed;
11508        }
11509
11510        public boolean getTitlePrinted() {
11511            return mTitlePrinted;
11512        }
11513
11514        public void setTitlePrinted(boolean enabled) {
11515            mTitlePrinted = enabled;
11516        }
11517
11518        public SharedUserSetting getSharedUser() {
11519            return mSharedUser;
11520        }
11521
11522        public void setSharedUser(SharedUserSetting user) {
11523            mSharedUser = user;
11524        }
11525    }
11526
11527    @Override
11528    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11529        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11530                != PackageManager.PERMISSION_GRANTED) {
11531            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11532                    + Binder.getCallingPid()
11533                    + ", uid=" + Binder.getCallingUid()
11534                    + " without permission "
11535                    + android.Manifest.permission.DUMP);
11536            return;
11537        }
11538
11539        DumpState dumpState = new DumpState();
11540        boolean fullPreferred = false;
11541        boolean checkin = false;
11542
11543        String packageName = null;
11544
11545        int opti = 0;
11546        while (opti < args.length) {
11547            String opt = args[opti];
11548            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11549                break;
11550            }
11551            opti++;
11552            if ("-a".equals(opt)) {
11553                // Right now we only know how to print all.
11554            } else if ("-h".equals(opt)) {
11555                pw.println("Package manager dump options:");
11556                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11557                pw.println("    --checkin: dump for a checkin");
11558                pw.println("    -f: print details of intent filters");
11559                pw.println("    -h: print this help");
11560                pw.println("  cmd may be one of:");
11561                pw.println("    l[ibraries]: list known shared libraries");
11562                pw.println("    f[ibraries]: list device features");
11563                pw.println("    r[esolvers]: dump intent resolvers");
11564                pw.println("    perm[issions]: dump permissions");
11565                pw.println("    pref[erred]: print preferred package settings");
11566                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11567                pw.println("    prov[iders]: dump content providers");
11568                pw.println("    p[ackages]: dump installed packages");
11569                pw.println("    s[hared-users]: dump shared user IDs");
11570                pw.println("    m[essages]: print collected runtime messages");
11571                pw.println("    v[erifiers]: print package verifier info");
11572                pw.println("    version: print database version info");
11573                pw.println("    <package.name>: info about given package");
11574                pw.println("    k[eysets]: print known keysets");
11575                return;
11576            } else if ("--checkin".equals(opt)) {
11577                checkin = true;
11578            } else if ("-f".equals(opt)) {
11579                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11580            } else {
11581                pw.println("Unknown argument: " + opt + "; use -h for help");
11582            }
11583        }
11584
11585        // Is the caller requesting to dump a particular piece of data?
11586        if (opti < args.length) {
11587            String cmd = args[opti];
11588            opti++;
11589            // Is this a package name?
11590            if ("android".equals(cmd) || cmd.contains(".")) {
11591                packageName = cmd;
11592                // When dumping a single package, we always dump all of its
11593                // filter information since the amount of data will be reasonable.
11594                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11595            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11596                dumpState.setDump(DumpState.DUMP_LIBS);
11597            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11598                dumpState.setDump(DumpState.DUMP_FEATURES);
11599            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11600                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11601            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11602                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11603            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11604                dumpState.setDump(DumpState.DUMP_PREFERRED);
11605            } else if ("preferred-xml".equals(cmd)) {
11606                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11607                if (opti < args.length && "--full".equals(args[opti])) {
11608                    fullPreferred = true;
11609                    opti++;
11610                }
11611            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11612                dumpState.setDump(DumpState.DUMP_PACKAGES);
11613            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11614                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11615            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11616                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11617            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11618                dumpState.setDump(DumpState.DUMP_MESSAGES);
11619            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11620                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11621            } else if ("version".equals(cmd)) {
11622                dumpState.setDump(DumpState.DUMP_VERSION);
11623            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11624                dumpState.setDump(DumpState.DUMP_KEYSETS);
11625            }
11626        }
11627
11628        if (checkin) {
11629            pw.println("vers,1");
11630        }
11631
11632        // reader
11633        synchronized (mPackages) {
11634            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11635                if (!checkin) {
11636                    if (dumpState.onTitlePrinted())
11637                        pw.println();
11638                    pw.println("Database versions:");
11639                    pw.print("  SDK Version:");
11640                    pw.print(" internal=");
11641                    pw.print(mSettings.mInternalSdkPlatform);
11642                    pw.print(" external=");
11643                    pw.println(mSettings.mExternalSdkPlatform);
11644                    pw.print("  DB Version:");
11645                    pw.print(" internal=");
11646                    pw.print(mSettings.mInternalDatabaseVersion);
11647                    pw.print(" external=");
11648                    pw.println(mSettings.mExternalDatabaseVersion);
11649                }
11650            }
11651
11652            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11653                if (!checkin) {
11654                    if (dumpState.onTitlePrinted())
11655                        pw.println();
11656                    pw.println("Verifiers:");
11657                    pw.print("  Required: ");
11658                    pw.print(mRequiredVerifierPackage);
11659                    pw.print(" (uid=");
11660                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11661                    pw.println(")");
11662                } else if (mRequiredVerifierPackage != null) {
11663                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11664                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11665                }
11666            }
11667
11668            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11669                boolean printedHeader = false;
11670                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11671                while (it.hasNext()) {
11672                    String name = it.next();
11673                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11674                    if (!checkin) {
11675                        if (!printedHeader) {
11676                            if (dumpState.onTitlePrinted())
11677                                pw.println();
11678                            pw.println("Libraries:");
11679                            printedHeader = true;
11680                        }
11681                        pw.print("  ");
11682                    } else {
11683                        pw.print("lib,");
11684                    }
11685                    pw.print(name);
11686                    if (!checkin) {
11687                        pw.print(" -> ");
11688                    }
11689                    if (ent.path != null) {
11690                        if (!checkin) {
11691                            pw.print("(jar) ");
11692                            pw.print(ent.path);
11693                        } else {
11694                            pw.print(",jar,");
11695                            pw.print(ent.path);
11696                        }
11697                    } else {
11698                        if (!checkin) {
11699                            pw.print("(apk) ");
11700                            pw.print(ent.apk);
11701                        } else {
11702                            pw.print(",apk,");
11703                            pw.print(ent.apk);
11704                        }
11705                    }
11706                    pw.println();
11707                }
11708            }
11709
11710            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11711                if (dumpState.onTitlePrinted())
11712                    pw.println();
11713                if (!checkin) {
11714                    pw.println("Features:");
11715                }
11716                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11717                while (it.hasNext()) {
11718                    String name = it.next();
11719                    if (!checkin) {
11720                        pw.print("  ");
11721                    } else {
11722                        pw.print("feat,");
11723                    }
11724                    pw.println(name);
11725                }
11726            }
11727
11728            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11729                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11730                        : "Activity Resolver Table:", "  ", packageName,
11731                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11732                    dumpState.setTitlePrinted(true);
11733                }
11734                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11735                        : "Receiver Resolver Table:", "  ", packageName,
11736                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11737                    dumpState.setTitlePrinted(true);
11738                }
11739                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11740                        : "Service Resolver Table:", "  ", packageName,
11741                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11742                    dumpState.setTitlePrinted(true);
11743                }
11744                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11745                        : "Provider Resolver Table:", "  ", packageName,
11746                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11747                    dumpState.setTitlePrinted(true);
11748                }
11749            }
11750
11751            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11752                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11753                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11754                    int user = mSettings.mPreferredActivities.keyAt(i);
11755                    if (pir.dump(pw,
11756                            dumpState.getTitlePrinted()
11757                                ? "\nPreferred Activities User " + user + ":"
11758                                : "Preferred Activities User " + user + ":", "  ",
11759                            packageName, true)) {
11760                        dumpState.setTitlePrinted(true);
11761                    }
11762                }
11763            }
11764
11765            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11766                pw.flush();
11767                FileOutputStream fout = new FileOutputStream(fd);
11768                BufferedOutputStream str = new BufferedOutputStream(fout);
11769                XmlSerializer serializer = new FastXmlSerializer();
11770                try {
11771                    serializer.setOutput(str, "utf-8");
11772                    serializer.startDocument(null, true);
11773                    serializer.setFeature(
11774                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11775                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11776                    serializer.endDocument();
11777                    serializer.flush();
11778                } catch (IllegalArgumentException e) {
11779                    pw.println("Failed writing: " + e);
11780                } catch (IllegalStateException e) {
11781                    pw.println("Failed writing: " + e);
11782                } catch (IOException e) {
11783                    pw.println("Failed writing: " + e);
11784                }
11785            }
11786
11787            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11788                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11789            }
11790
11791            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11792                boolean printedSomething = false;
11793                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11794                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11795                        continue;
11796                    }
11797                    if (!printedSomething) {
11798                        if (dumpState.onTitlePrinted())
11799                            pw.println();
11800                        pw.println("Registered ContentProviders:");
11801                        printedSomething = true;
11802                    }
11803                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11804                    pw.print("    "); pw.println(p.toString());
11805                }
11806                printedSomething = false;
11807                for (Map.Entry<String, PackageParser.Provider> entry :
11808                        mProvidersByAuthority.entrySet()) {
11809                    PackageParser.Provider p = entry.getValue();
11810                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11811                        continue;
11812                    }
11813                    if (!printedSomething) {
11814                        if (dumpState.onTitlePrinted())
11815                            pw.println();
11816                        pw.println("ContentProvider Authorities:");
11817                        printedSomething = true;
11818                    }
11819                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11820                    pw.print("    "); pw.println(p.toString());
11821                    if (p.info != null && p.info.applicationInfo != null) {
11822                        final String appInfo = p.info.applicationInfo.toString();
11823                        pw.print("      applicationInfo="); pw.println(appInfo);
11824                    }
11825                }
11826            }
11827
11828            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11829                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11830            }
11831
11832            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11833                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11834            }
11835
11836            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11837                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11838            }
11839
11840            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11841                if (dumpState.onTitlePrinted())
11842                    pw.println();
11843                mSettings.dumpReadMessagesLPr(pw, dumpState);
11844
11845                pw.println();
11846                pw.println("Package warning messages:");
11847                final File fname = getSettingsProblemFile();
11848                FileInputStream in = null;
11849                try {
11850                    in = new FileInputStream(fname);
11851                    final int avail = in.available();
11852                    final byte[] data = new byte[avail];
11853                    in.read(data);
11854                    pw.print(new String(data));
11855                } catch (FileNotFoundException e) {
11856                } catch (IOException e) {
11857                } finally {
11858                    if (in != null) {
11859                        try {
11860                            in.close();
11861                        } catch (IOException e) {
11862                        }
11863                    }
11864                }
11865            }
11866        }
11867    }
11868
11869    // ------- apps on sdcard specific code -------
11870    static final boolean DEBUG_SD_INSTALL = false;
11871
11872    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11873
11874    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11875
11876    private boolean mMediaMounted = false;
11877
11878    private String getEncryptKey() {
11879        try {
11880            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11881                    SD_ENCRYPTION_KEYSTORE_NAME);
11882            if (sdEncKey == null) {
11883                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11884                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11885                if (sdEncKey == null) {
11886                    Slog.e(TAG, "Failed to create encryption keys");
11887                    return null;
11888                }
11889            }
11890            return sdEncKey;
11891        } catch (NoSuchAlgorithmException nsae) {
11892            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11893            return null;
11894        } catch (IOException ioe) {
11895            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11896            return null;
11897        }
11898
11899    }
11900
11901    /* package */static String getTempContainerId() {
11902        int tmpIdx = 1;
11903        String list[] = PackageHelper.getSecureContainerList();
11904        if (list != null) {
11905            for (final String name : list) {
11906                // Ignore null and non-temporary container entries
11907                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11908                    continue;
11909                }
11910
11911                String subStr = name.substring(mTempContainerPrefix.length());
11912                try {
11913                    int cid = Integer.parseInt(subStr);
11914                    if (cid >= tmpIdx) {
11915                        tmpIdx = cid + 1;
11916                    }
11917                } catch (NumberFormatException e) {
11918                }
11919            }
11920        }
11921        return mTempContainerPrefix + tmpIdx;
11922    }
11923
11924    /*
11925     * Update media status on PackageManager.
11926     */
11927    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11928        int callingUid = Binder.getCallingUid();
11929        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11930            throw new SecurityException("Media status can only be updated by the system");
11931        }
11932        // reader; this apparently protects mMediaMounted, but should probably
11933        // be a different lock in that case.
11934        synchronized (mPackages) {
11935            Log.i(TAG, "Updating external media status from "
11936                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11937                    + (mediaStatus ? "mounted" : "unmounted"));
11938            if (DEBUG_SD_INSTALL)
11939                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11940                        + ", mMediaMounted=" + mMediaMounted);
11941            if (mediaStatus == mMediaMounted) {
11942                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11943                        : 0, -1);
11944                mHandler.sendMessage(msg);
11945                return;
11946            }
11947            mMediaMounted = mediaStatus;
11948        }
11949        // Queue up an async operation since the package installation may take a
11950        // little while.
11951        mHandler.post(new Runnable() {
11952            public void run() {
11953                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11954            }
11955        });
11956    }
11957
11958    /**
11959     * Called by MountService when the initial ASECs to scan are available.
11960     * Should block until all the ASEC containers are finished being scanned.
11961     */
11962    public void scanAvailableAsecs() {
11963        updateExternalMediaStatusInner(true, false, false);
11964        if (mShouldRestoreconData) {
11965            SELinuxMMAC.setRestoreconDone();
11966            mShouldRestoreconData = false;
11967        }
11968    }
11969
11970    /*
11971     * Collect information of applications on external media, map them against
11972     * existing containers and update information based on current mount status.
11973     * Please note that we always have to report status if reportStatus has been
11974     * set to true especially when unloading packages.
11975     */
11976    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11977            boolean externalStorage) {
11978        // Collection of uids
11979        int uidArr[] = null;
11980        // Collection of stale containers
11981        HashSet<String> removeCids = new HashSet<String>();
11982        // Collection of packages on external media with valid containers.
11983        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11984        // Get list of secure containers.
11985        final String list[] = PackageHelper.getSecureContainerList();
11986        if (list == null || list.length == 0) {
11987            Log.i(TAG, "No secure containers on sdcard");
11988        } else {
11989            // Process list of secure containers and categorize them
11990            // as active or stale based on their package internal state.
11991            int uidList[] = new int[list.length];
11992            int num = 0;
11993            // reader
11994            synchronized (mPackages) {
11995                for (String cid : list) {
11996                    if (DEBUG_SD_INSTALL)
11997                        Log.i(TAG, "Processing container " + cid);
11998                    String pkgName = getAsecPackageName(cid);
11999                    if (pkgName == null) {
12000                        if (DEBUG_SD_INSTALL)
12001                            Log.i(TAG, "Container : " + cid + " stale");
12002                        removeCids.add(cid);
12003                        continue;
12004                    }
12005                    if (DEBUG_SD_INSTALL)
12006                        Log.i(TAG, "Looking for pkg : " + pkgName);
12007
12008                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12009                    if (ps == null) {
12010                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12011                        removeCids.add(cid);
12012                        continue;
12013                    }
12014
12015                    /*
12016                     * Skip packages that are not external if we're unmounting
12017                     * external storage.
12018                     */
12019                    if (externalStorage && !isMounted && !isExternal(ps)) {
12020                        continue;
12021                    }
12022
12023                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12024                            getAppInstructionSetFromSettings(ps),
12025                            isForwardLocked(ps));
12026                    // The package status is changed only if the code path
12027                    // matches between settings and the container id.
12028                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12029                        if (DEBUG_SD_INSTALL) {
12030                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12031                                    + " at code path: " + ps.codePathString);
12032                        }
12033
12034                        // We do have a valid package installed on sdcard
12035                        processCids.put(args, ps.codePathString);
12036                        final int uid = ps.appId;
12037                        if (uid != -1) {
12038                            uidList[num++] = uid;
12039                        }
12040                    } else {
12041                        Log.i(TAG, "Deleting stale container for " + cid);
12042                        removeCids.add(cid);
12043                    }
12044                }
12045            }
12046
12047            if (num > 0) {
12048                // Sort uid list
12049                Arrays.sort(uidList, 0, num);
12050                // Throw away duplicates
12051                uidArr = new int[num];
12052                uidArr[0] = uidList[0];
12053                int di = 0;
12054                for (int i = 1; i < num; i++) {
12055                    if (uidList[i - 1] != uidList[i]) {
12056                        uidArr[di++] = uidList[i];
12057                    }
12058                }
12059            }
12060        }
12061        // Process packages with valid entries.
12062        if (isMounted) {
12063            if (DEBUG_SD_INSTALL)
12064                Log.i(TAG, "Loading packages");
12065            loadMediaPackages(processCids, uidArr, removeCids);
12066            startCleaningPackages();
12067        } else {
12068            if (DEBUG_SD_INSTALL)
12069                Log.i(TAG, "Unloading packages");
12070            unloadMediaPackages(processCids, uidArr, reportStatus);
12071        }
12072    }
12073
12074   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12075           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12076        int size = pkgList.size();
12077        if (size > 0) {
12078            // Send broadcasts here
12079            Bundle extras = new Bundle();
12080            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12081                    .toArray(new String[size]));
12082            if (uidArr != null) {
12083                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12084            }
12085            if (replacing) {
12086                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12087            }
12088            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12089                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12090            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12091        }
12092    }
12093
12094   /*
12095     * Look at potentially valid container ids from processCids If package
12096     * information doesn't match the one on record or package scanning fails,
12097     * the cid is added to list of removeCids. We currently don't delete stale
12098     * containers.
12099     */
12100   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12101            HashSet<String> removeCids) {
12102        ArrayList<String> pkgList = new ArrayList<String>();
12103        Set<AsecInstallArgs> keys = processCids.keySet();
12104        boolean doGc = false;
12105        for (AsecInstallArgs args : keys) {
12106            String codePath = processCids.get(args);
12107            if (DEBUG_SD_INSTALL)
12108                Log.i(TAG, "Loading container : " + args.cid);
12109            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12110            try {
12111                // Make sure there are no container errors first.
12112                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12113                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12114                            + " when installing from sdcard");
12115                    continue;
12116                }
12117                // Check code path here.
12118                if (codePath == null || !codePath.equals(args.getCodePath())) {
12119                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12120                            + " does not match one in settings " + codePath);
12121                    continue;
12122                }
12123                // Parse package
12124                int parseFlags = mDefParseFlags;
12125                if (args.isExternal()) {
12126                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12127                }
12128                if (args.isFwdLocked()) {
12129                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12130                }
12131
12132                doGc = true;
12133                synchronized (mInstallLock) {
12134                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12135                            0, 0, null);
12136                    // Scan the package
12137                    if (pkg != null) {
12138                        /*
12139                         * TODO why is the lock being held? doPostInstall is
12140                         * called in other places without the lock. This needs
12141                         * to be straightened out.
12142                         */
12143                        // writer
12144                        synchronized (mPackages) {
12145                            retCode = PackageManager.INSTALL_SUCCEEDED;
12146                            pkgList.add(pkg.packageName);
12147                            // Post process args
12148                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12149                                    pkg.applicationInfo.uid);
12150                        }
12151                    } else {
12152                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12153                    }
12154                }
12155
12156            } finally {
12157                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12158                    // Don't destroy container here. Wait till gc clears things
12159                    // up.
12160                    removeCids.add(args.cid);
12161                }
12162            }
12163        }
12164        // writer
12165        synchronized (mPackages) {
12166            // If the platform SDK has changed since the last time we booted,
12167            // we need to re-grant app permission to catch any new ones that
12168            // appear. This is really a hack, and means that apps can in some
12169            // cases get permissions that the user didn't initially explicitly
12170            // allow... it would be nice to have some better way to handle
12171            // this situation.
12172            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12173            if (regrantPermissions)
12174                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12175                        + mSdkVersion + "; regranting permissions for external storage");
12176            mSettings.mExternalSdkPlatform = mSdkVersion;
12177
12178            // Make sure group IDs have been assigned, and any permission
12179            // changes in other apps are accounted for
12180            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12181                    | (regrantPermissions
12182                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12183                            : 0));
12184
12185            mSettings.updateExternalDatabaseVersion();
12186
12187            // can downgrade to reader
12188            // Persist settings
12189            mSettings.writeLPr();
12190        }
12191        // Send a broadcast to let everyone know we are done processing
12192        if (pkgList.size() > 0) {
12193            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12194        }
12195        // Force gc to avoid any stale parser references that we might have.
12196        if (doGc) {
12197            Runtime.getRuntime().gc();
12198        }
12199        // List stale containers and destroy stale temporary containers.
12200        if (removeCids != null) {
12201            for (String cid : removeCids) {
12202                if (cid.startsWith(mTempContainerPrefix)) {
12203                    Log.i(TAG, "Destroying stale temporary container " + cid);
12204                    PackageHelper.destroySdDir(cid);
12205                } else {
12206                    Log.w(TAG, "Container " + cid + " is stale");
12207               }
12208           }
12209        }
12210    }
12211
12212   /*
12213     * Utility method to unload a list of specified containers
12214     */
12215    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12216        // Just unmount all valid containers.
12217        for (AsecInstallArgs arg : cidArgs) {
12218            synchronized (mInstallLock) {
12219                arg.doPostDeleteLI(false);
12220           }
12221       }
12222   }
12223
12224    /*
12225     * Unload packages mounted on external media. This involves deleting package
12226     * data from internal structures, sending broadcasts about diabled packages,
12227     * gc'ing to free up references, unmounting all secure containers
12228     * corresponding to packages on external media, and posting a
12229     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12230     * that we always have to post this message if status has been requested no
12231     * matter what.
12232     */
12233    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12234            final boolean reportStatus) {
12235        if (DEBUG_SD_INSTALL)
12236            Log.i(TAG, "unloading media packages");
12237        ArrayList<String> pkgList = new ArrayList<String>();
12238        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12239        final Set<AsecInstallArgs> keys = processCids.keySet();
12240        for (AsecInstallArgs args : keys) {
12241            String pkgName = args.getPackageName();
12242            if (DEBUG_SD_INSTALL)
12243                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12244            // Delete package internally
12245            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12246            synchronized (mInstallLock) {
12247                boolean res = deletePackageLI(pkgName, null, false, null, null,
12248                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12249                if (res) {
12250                    pkgList.add(pkgName);
12251                } else {
12252                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12253                    failedList.add(args);
12254                }
12255            }
12256        }
12257
12258        // reader
12259        synchronized (mPackages) {
12260            // We didn't update the settings after removing each package;
12261            // write them now for all packages.
12262            mSettings.writeLPr();
12263        }
12264
12265        // We have to absolutely send UPDATED_MEDIA_STATUS only
12266        // after confirming that all the receivers processed the ordered
12267        // broadcast when packages get disabled, force a gc to clean things up.
12268        // and unload all the containers.
12269        if (pkgList.size() > 0) {
12270            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12271                    new IIntentReceiver.Stub() {
12272                public void performReceive(Intent intent, int resultCode, String data,
12273                        Bundle extras, boolean ordered, boolean sticky,
12274                        int sendingUser) throws RemoteException {
12275                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12276                            reportStatus ? 1 : 0, 1, keys);
12277                    mHandler.sendMessage(msg);
12278                }
12279            });
12280        } else {
12281            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12282                    keys);
12283            mHandler.sendMessage(msg);
12284        }
12285    }
12286
12287    /** Binder call */
12288    @Override
12289    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12290            final int flags) {
12291        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12292        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12293        int returnCode = PackageManager.MOVE_SUCCEEDED;
12294        int currFlags = 0;
12295        int newFlags = 0;
12296        // reader
12297        synchronized (mPackages) {
12298            PackageParser.Package pkg = mPackages.get(packageName);
12299            if (pkg == null) {
12300                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12301            } else {
12302                // Disable moving fwd locked apps and system packages
12303                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12304                    Slog.w(TAG, "Cannot move system application");
12305                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12306                } else if (pkg.mOperationPending) {
12307                    Slog.w(TAG, "Attempt to move package which has pending operations");
12308                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12309                } else {
12310                    // Find install location first
12311                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12312                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12313                        Slog.w(TAG, "Ambigous flags specified for move location.");
12314                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12315                    } else {
12316                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12317                                : PackageManager.INSTALL_INTERNAL;
12318                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12319                                : PackageManager.INSTALL_INTERNAL;
12320
12321                        if (newFlags == currFlags) {
12322                            Slog.w(TAG, "No move required. Trying to move to same location");
12323                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12324                        } else {
12325                            if (isForwardLocked(pkg)) {
12326                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12327                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12328                            }
12329                        }
12330                    }
12331                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12332                        pkg.mOperationPending = true;
12333                    }
12334                }
12335            }
12336
12337            /*
12338             * TODO this next block probably shouldn't be inside the lock. We
12339             * can't guarantee these won't change after this is fired off
12340             * anyway.
12341             */
12342            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12343                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12344                        null, -1, user),
12345                        returnCode);
12346            } else {
12347                Message msg = mHandler.obtainMessage(INIT_COPY);
12348                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12349                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12350                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12351                        instructionSet);
12352                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12353                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12354                msg.obj = mp;
12355                mHandler.sendMessage(msg);
12356            }
12357        }
12358    }
12359
12360    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12361        // Queue up an async operation since the package deletion may take a
12362        // little while.
12363        mHandler.post(new Runnable() {
12364            public void run() {
12365                // TODO fix this; this does nothing.
12366                mHandler.removeCallbacks(this);
12367                int returnCode = currentStatus;
12368                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12369                    int uidArr[] = null;
12370                    ArrayList<String> pkgList = null;
12371                    synchronized (mPackages) {
12372                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12373                        if (pkg == null) {
12374                            Slog.w(TAG, " Package " + mp.packageName
12375                                    + " doesn't exist. Aborting move");
12376                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12377                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12378                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12379                                    + mp.srcArgs.getCodePath() + " to "
12380                                    + pkg.applicationInfo.sourceDir
12381                                    + " Aborting move and returning error");
12382                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12383                        } else {
12384                            uidArr = new int[] {
12385                                pkg.applicationInfo.uid
12386                            };
12387                            pkgList = new ArrayList<String>();
12388                            pkgList.add(mp.packageName);
12389                        }
12390                    }
12391                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12392                        // Send resources unavailable broadcast
12393                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12394                        // Update package code and resource paths
12395                        synchronized (mInstallLock) {
12396                            synchronized (mPackages) {
12397                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12398                                // Recheck for package again.
12399                                if (pkg == null) {
12400                                    Slog.w(TAG, " Package " + mp.packageName
12401                                            + " doesn't exist. Aborting move");
12402                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12403                                } else if (!mp.srcArgs.getCodePath().equals(
12404                                        pkg.applicationInfo.sourceDir)) {
12405                                    Slog.w(TAG, "Package " + mp.packageName
12406                                            + " code path changed from " + mp.srcArgs.getCodePath()
12407                                            + " to " + pkg.applicationInfo.sourceDir
12408                                            + " Aborting move and returning error");
12409                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12410                                } else {
12411                                    final String oldCodePath = pkg.mPath;
12412                                    final String newCodePath = mp.targetArgs.getCodePath();
12413                                    final String newResPath = mp.targetArgs.getResourcePath();
12414                                    final String newNativePath = mp.targetArgs
12415                                            .getNativeLibraryPath();
12416
12417                                    final File newNativeDir = new File(newNativePath);
12418
12419                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12420                                        // NOTE: We do not report any errors from the APK scan and library
12421                                        // copy at this point.
12422                                        NativeLibraryHelper.ApkHandle handle =
12423                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12424                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12425                                                handle, Build.SUPPORTED_ABIS);
12426                                        if (abi >= 0) {
12427                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12428                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12429                                        }
12430                                        handle.close();
12431                                    }
12432                                    final int[] users = sUserManager.getUserIds();
12433                                    for (int user : users) {
12434                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12435                                                newNativePath, user) < 0) {
12436                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12437                                        }
12438                                    }
12439
12440                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12441                                        pkg.mPath = newCodePath;
12442                                        // Move dex files around
12443                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12444                                            // Moving of dex files failed. Set
12445                                            // error code and abort move.
12446                                            pkg.mPath = pkg.mScanPath;
12447                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12448                                        }
12449                                    }
12450
12451                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12452                                        pkg.mScanPath = newCodePath;
12453                                        pkg.applicationInfo.sourceDir = newCodePath;
12454                                        pkg.applicationInfo.publicSourceDir = newResPath;
12455                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12456                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12457                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12458                                        ps.codePathString = ps.codePath.getPath();
12459                                        ps.resourcePath = new File(
12460                                                pkg.applicationInfo.publicSourceDir);
12461                                        ps.resourcePathString = ps.resourcePath.getPath();
12462                                        ps.nativeLibraryPathString = newNativePath;
12463                                        // Set the application info flag
12464                                        // correctly.
12465                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12466                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12467                                        } else {
12468                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12469                                        }
12470                                        ps.setFlags(pkg.applicationInfo.flags);
12471                                        mAppDirs.remove(oldCodePath);
12472                                        mAppDirs.put(newCodePath, pkg);
12473                                        // Persist settings
12474                                        mSettings.writeLPr();
12475                                    }
12476                                }
12477                            }
12478                        }
12479                        // Send resources available broadcast
12480                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12481                    }
12482                }
12483                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12484                    // Clean up failed installation
12485                    if (mp.targetArgs != null) {
12486                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12487                                -1);
12488                    }
12489                } else {
12490                    // Force a gc to clear things up.
12491                    Runtime.getRuntime().gc();
12492                    // Delete older code
12493                    synchronized (mInstallLock) {
12494                        mp.srcArgs.doPostDeleteLI(true);
12495                    }
12496                }
12497
12498                // Allow more operations on this file if we didn't fail because
12499                // an operation was already pending for this package.
12500                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12501                    synchronized (mPackages) {
12502                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12503                        if (pkg != null) {
12504                            pkg.mOperationPending = false;
12505                       }
12506                   }
12507                }
12508
12509                IPackageMoveObserver observer = mp.observer;
12510                if (observer != null) {
12511                    try {
12512                        observer.packageMoved(mp.packageName, returnCode);
12513                    } catch (RemoteException e) {
12514                        Log.i(TAG, "Observer no longer exists.");
12515                    }
12516                }
12517            }
12518        });
12519    }
12520
12521    public boolean setInstallLocation(int loc) {
12522        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12523                null);
12524        if (getInstallLocation() == loc) {
12525            return true;
12526        }
12527        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12528                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12529            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12530                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12531            return true;
12532        }
12533        return false;
12534   }
12535
12536    public int getInstallLocation() {
12537        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12538                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12539                PackageHelper.APP_INSTALL_AUTO);
12540    }
12541
12542    /** Called by UserManagerService */
12543    void cleanUpUserLILPw(int userHandle) {
12544        mDirtyUsers.remove(userHandle);
12545        mSettings.removeUserLPr(userHandle);
12546        mPendingBroadcasts.remove(userHandle);
12547        if (mInstaller != null) {
12548            // Technically, we shouldn't be doing this with the package lock
12549            // held.  However, this is very rare, and there is already so much
12550            // other disk I/O going on, that we'll let it slide for now.
12551            mInstaller.removeUserDataDirs(userHandle);
12552        }
12553    }
12554
12555    /** Called by UserManagerService */
12556    void createNewUserLILPw(int userHandle, File path) {
12557        if (mInstaller != null) {
12558            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12559        }
12560    }
12561
12562    @Override
12563    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12564        mContext.enforceCallingOrSelfPermission(
12565                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12566                "Only package verification agents can read the verifier device identity");
12567
12568        synchronized (mPackages) {
12569            return mSettings.getVerifierDeviceIdentityLPw();
12570        }
12571    }
12572
12573    @Override
12574    public void setPermissionEnforced(String permission, boolean enforced) {
12575        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12576        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12577            synchronized (mPackages) {
12578                if (mSettings.mReadExternalStorageEnforced == null
12579                        || mSettings.mReadExternalStorageEnforced != enforced) {
12580                    mSettings.mReadExternalStorageEnforced = enforced;
12581                    mSettings.writeLPr();
12582                }
12583            }
12584            // kill any non-foreground processes so we restart them and
12585            // grant/revoke the GID.
12586            final IActivityManager am = ActivityManagerNative.getDefault();
12587            if (am != null) {
12588                final long token = Binder.clearCallingIdentity();
12589                try {
12590                    am.killProcessesBelowForeground("setPermissionEnforcement");
12591                } catch (RemoteException e) {
12592                } finally {
12593                    Binder.restoreCallingIdentity(token);
12594                }
12595            }
12596        } else {
12597            throw new IllegalArgumentException("No selective enforcement for " + permission);
12598        }
12599    }
12600
12601    @Override
12602    @Deprecated
12603    public boolean isPermissionEnforced(String permission) {
12604        return true;
12605    }
12606
12607    @Override
12608    public boolean isStorageLow() {
12609        final long token = Binder.clearCallingIdentity();
12610        try {
12611            final DeviceStorageMonitorInternal
12612                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12613            if (dsm != null) {
12614                return dsm.isMemoryLow();
12615            } else {
12616                return false;
12617            }
12618        } finally {
12619            Binder.restoreCallingIdentity(token);
12620        }
12621    }
12622}
12623