PackageManagerService.java revision df6d6dc2aac2912e98de3fe37869d2b179eb23db
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.system.OsConstants.S_IRWXU;
27import static android.system.OsConstants.S_IRGRP;
28import static android.system.OsConstants.S_IXGRP;
29import static android.system.OsConstants.S_IROTH;
30import static android.system.OsConstants.S_IXOTH;
31import static com.android.internal.util.ArrayUtils.appendInt;
32import static com.android.internal.util.ArrayUtils.removeInt;
33
34import android.content.pm.PackageParser.*;
35import com.android.internal.app.IMediaContainerService;
36import com.android.internal.app.ResolverActivity;
37import com.android.internal.content.NativeLibraryHelper;
38import com.android.internal.content.PackageHelper;
39import com.android.internal.util.FastPrintWriter;
40import com.android.internal.util.FastXmlSerializer;
41import com.android.internal.util.XmlUtils;
42import com.android.server.EventLogTags;
43import com.android.server.IntentResolver;
44import com.android.server.ServiceThread;
45
46import com.android.server.LocalServices;
47import com.android.server.Watchdog;
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
51
52import android.app.ActivityManager;
53import android.app.ActivityManagerNative;
54import android.app.IActivityManager;
55import android.app.admin.IDevicePolicyManager;
56import android.app.backup.IBackupManager;
57import android.content.BroadcastReceiver;
58import android.content.ComponentName;
59import android.content.Context;
60import android.content.IIntentReceiver;
61import android.content.Intent;
62import android.content.IntentFilter;
63import android.content.IntentSender;
64import android.content.IntentSender.SendIntentException;
65import android.content.ServiceConnection;
66import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ContainerEncryptionParams;
69import android.content.pm.FeatureInfo;
70import android.content.pm.IPackageDataObserver;
71import android.content.pm.IPackageDeleteObserver;
72import android.content.pm.IPackageInstallObserver;
73import android.content.pm.IPackageInstallObserver2;
74import android.content.pm.IPackageManager;
75import android.content.pm.IPackageMoveObserver;
76import android.content.pm.IPackageStatsObserver;
77import android.content.pm.InstrumentationInfo;
78import android.content.pm.ManifestDigest;
79import android.content.pm.PackageCleanItem;
80import android.content.pm.PackageInfo;
81import android.content.pm.PackageInfoLite;
82import android.content.pm.PackageManager;
83import android.content.pm.PackageParser;
84import android.content.pm.PackageStats;
85import android.content.pm.PackageUserState;
86import android.content.pm.ParceledListSlice;
87import android.content.pm.PermissionGroupInfo;
88import android.content.pm.PermissionInfo;
89import android.content.pm.ProviderInfo;
90import android.content.pm.ResolveInfo;
91import android.content.pm.ServiceInfo;
92import android.content.pm.Signature;
93import android.content.pm.VerificationParams;
94import android.content.pm.VerifierDeviceIdentity;
95import android.content.pm.VerifierInfo;
96import android.content.res.Resources;
97import android.hardware.display.DisplayManager;
98import android.net.Uri;
99import android.os.Binder;
100import android.os.Build;
101import android.os.Bundle;
102import android.os.Environment;
103import android.os.Environment.UserEnvironment;
104import android.os.FileObserver;
105import android.os.FileUtils;
106import android.os.Handler;
107import android.os.IBinder;
108import android.os.Looper;
109import android.os.Message;
110import android.os.Parcel;
111import android.os.ParcelFileDescriptor;
112import android.os.Process;
113import android.os.RemoteException;
114import android.os.SELinux;
115import android.os.ServiceManager;
116import android.os.SystemClock;
117import android.os.SystemProperties;
118import android.os.UserHandle;
119import android.os.UserManager;
120import android.security.KeyStore;
121import android.security.SystemKeyStore;
122import android.system.ErrnoException;
123import android.system.Os;
124import android.system.StructStat;
125import android.text.TextUtils;
126import android.util.DisplayMetrics;
127import android.util.EventLog;
128import android.util.Log;
129import android.util.LogPrinter;
130import android.util.PrintStreamPrinter;
131import android.util.Slog;
132import android.util.SparseArray;
133import android.util.Xml;
134import android.view.Display;
135
136import java.io.BufferedOutputStream;
137import java.io.File;
138import java.io.FileDescriptor;
139import java.io.FileInputStream;
140import java.io.FileNotFoundException;
141import java.io.FileOutputStream;
142import java.io.FileReader;
143import java.io.FilenameFilter;
144import java.io.IOException;
145import java.io.PrintWriter;
146import java.security.NoSuchAlgorithmException;
147import java.security.PublicKey;
148import java.security.cert.Certificate;
149import java.security.cert.CertificateEncodingException;
150import java.security.cert.CertificateException;
151import java.text.SimpleDateFormat;
152import java.util.ArrayList;
153import java.util.Arrays;
154import java.util.Collection;
155import java.util.Collections;
156import java.util.Comparator;
157import java.util.Date;
158import java.util.HashMap;
159import java.util.HashSet;
160import java.util.Iterator;
161import java.util.List;
162import java.util.Map;
163import java.util.Set;
164
165import dalvik.system.VMRuntime;
166import libcore.io.IoUtils;
167
168import com.android.internal.R;
169import com.android.server.pm.Settings.DatabaseVersion;
170import com.android.server.storage.DeviceStorageMonitorInternal;
171
172/**
173 * Keep track of all those .apks everywhere.
174 *
175 * This is very central to the platform's security; please run the unit
176 * tests whenever making modifications here:
177 *
178mmm frameworks/base/tests/AndroidTests
179adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
180adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
181 *
182 * {@hide}
183 */
184public class PackageManagerService extends IPackageManager.Stub {
185    static final String TAG = "PackageManager";
186    static final boolean DEBUG_SETTINGS = false;
187    static final boolean DEBUG_PREFERRED = false;
188    static final boolean DEBUG_UPGRADE = false;
189    private static final boolean DEBUG_INSTALL = false;
190    private static final boolean DEBUG_REMOVE = false;
191    private static final boolean DEBUG_BROADCASTS = false;
192    private static final boolean DEBUG_SHOW_INFO = false;
193    private static final boolean DEBUG_PACKAGE_INFO = false;
194    private static final boolean DEBUG_INTENT_MATCHING = false;
195    private static final boolean DEBUG_PACKAGE_SCANNING = false;
196    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
197    private static final boolean DEBUG_VERIFY = false;
198
199    private static final int RADIO_UID = Process.PHONE_UID;
200    private static final int LOG_UID = Process.LOG_UID;
201    private static final int NFC_UID = Process.NFC_UID;
202    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
203    private static final int SHELL_UID = Process.SHELL_UID;
204
205    // Cap the size of permission trees that 3rd party apps can define
206    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
207
208    private static final int REMOVE_EVENTS =
209        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
210    private static final int ADD_EVENTS =
211        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
212
213    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
214    // Suffix used during package installation when copying/moving
215    // package apks to install directory.
216    private static final String INSTALL_PACKAGE_SUFFIX = "-";
217
218    static final int SCAN_MONITOR = 1<<0;
219    static final int SCAN_NO_DEX = 1<<1;
220    static final int SCAN_FORCE_DEX = 1<<2;
221    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
222    static final int SCAN_NEW_INSTALL = 1<<4;
223    static final int SCAN_NO_PATHS = 1<<5;
224    static final int SCAN_UPDATE_TIME = 1<<6;
225    static final int SCAN_DEFER_DEX = 1<<7;
226    static final int SCAN_BOOTING = 1<<8;
227    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
228    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
229
230    static final int REMOVE_CHATTY = 1<<16;
231
232    /**
233     * Timeout (in milliseconds) after which the watchdog should declare that
234     * our handler thread is wedged.  The usual default for such things is one
235     * minute but we sometimes do very lengthy I/O operations on this thread,
236     * such as installing multi-gigabyte applications, so ours needs to be longer.
237     */
238    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
239
240    /**
241     * Whether verification is enabled by default.
242     */
243    private static final boolean DEFAULT_VERIFY_ENABLE = true;
244
245    /**
246     * The default maximum time to wait for the verification agent to return in
247     * milliseconds.
248     */
249    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
250
251    /**
252     * The default response for package verification timeout.
253     *
254     * This can be either PackageManager.VERIFICATION_ALLOW or
255     * PackageManager.VERIFICATION_REJECT.
256     */
257    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
258
259    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
260
261    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
262            DEFAULT_CONTAINER_PACKAGE,
263            "com.android.defcontainer.DefaultContainerService");
264
265    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
266
267    private static final String LIB_DIR_NAME = "lib";
268    private static final String LIB64_DIR_NAME = "lib64";
269
270    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
271
272    static final String mTempContainerPrefix = "smdl2tmp";
273
274    private static String sPreferredInstructionSet;
275
276    final ServiceThread mHandlerThread;
277
278    private static final String IDMAP_PREFIX = "/data/resource-cache/";
279    private static final String IDMAP_SUFFIX = "@idmap";
280
281    final PackageHandler mHandler;
282
283    final int mSdkVersion = Build.VERSION.SDK_INT;
284
285    final Context mContext;
286    final boolean mFactoryTest;
287    final boolean mOnlyCore;
288    final boolean mNoDexOpt;
289    final DisplayMetrics mMetrics;
290    final int mDefParseFlags;
291    final String[] mSeparateProcesses;
292
293    // This is where all application persistent data goes.
294    final File mAppDataDir;
295
296    // This is where all application persistent data goes for secondary users.
297    final File mUserAppDataDir;
298
299    /** The location for ASEC container files on internal storage. */
300    final String mAsecInternalPath;
301
302    // This is the object monitoring the framework dir.
303    final FileObserver mFrameworkInstallObserver;
304
305    // This is the object monitoring the system app dir.
306    final FileObserver mSystemInstallObserver;
307
308    // This is the object monitoring the privileged system app dir.
309    final FileObserver mPrivilegedInstallObserver;
310
311    // This is the object monitoring the vendor app dir.
312    final FileObserver mVendorInstallObserver;
313
314    // This is the object monitoring the vendor overlay package dir.
315    final FileObserver mVendorOverlayInstallObserver;
316
317    // This is the object monitoring the OEM app dir.
318    final FileObserver mOemInstallObserver;
319
320    // This is the object monitoring mAppInstallDir.
321    final FileObserver mAppInstallObserver;
322
323    // This is the object monitoring mDrmAppPrivateInstallDir.
324    final FileObserver mDrmAppInstallObserver;
325
326    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
327    // LOCK HELD.  Can be called with mInstallLock held.
328    final Installer mInstaller;
329
330    final File mAppInstallDir;
331
332    /**
333     * Directory to which applications installed internally have native
334     * libraries copied.
335     */
336    private File mAppLibInstallDir;
337
338    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
339    // apps.
340    final File mDrmAppPrivateInstallDir;
341
342    // ----------------------------------------------------------------
343
344    // Lock for state used when installing and doing other long running
345    // operations.  Methods that must be called with this lock held have
346    // the suffix "LI".
347    final Object mInstallLock = new Object();
348
349    // These are the directories in the 3rd party applications installed dir
350    // that we have currently loaded packages from.  Keys are the application's
351    // installed zip file (absolute codePath), and values are Package.
352    final HashMap<String, PackageParser.Package> mAppDirs =
353            new HashMap<String, PackageParser.Package>();
354
355    // Information for the parser to write more useful error messages.
356    int mLastScanError;
357
358    // ----------------------------------------------------------------
359
360    // Keys are String (package name), values are Package.  This also serves
361    // as the lock for the global state.  Methods that must be called with
362    // this lock held have the prefix "LP".
363    final HashMap<String, PackageParser.Package> mPackages =
364            new HashMap<String, PackageParser.Package>();
365
366    // Tracks available target package names -> overlay package paths.
367    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
368        new HashMap<String, HashMap<String, PackageParser.Package>>();
369
370    final Settings mSettings;
371    boolean mRestoredSettings;
372
373    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
374    int[] mGlobalGids;
375
376    // These are the built-in uid -> permission mappings that were read from the
377    // etc/permissions.xml file.
378    final SparseArray<HashSet<String>> mSystemPermissions =
379            new SparseArray<HashSet<String>>();
380
381    static final class SharedLibraryEntry {
382        final String path;
383        final String apk;
384
385        SharedLibraryEntry(String _path, String _apk) {
386            path = _path;
387            apk = _apk;
388        }
389    }
390
391    // These are the built-in shared libraries that were read from the
392    // etc/permissions.xml file.
393    final HashMap<String, SharedLibraryEntry> mSharedLibraries
394            = new HashMap<String, SharedLibraryEntry>();
395
396    // Temporary for building the final shared libraries for an .apk.
397    String[] mTmpSharedLibraries = null;
398
399    // These are the features this devices supports that were read from the
400    // etc/permissions.xml file.
401    final HashMap<String, FeatureInfo> mAvailableFeatures =
402            new HashMap<String, FeatureInfo>();
403
404    // If mac_permissions.xml was found for seinfo labeling.
405    boolean mFoundPolicyFile;
406
407    // If a recursive restorecon of /data/data/<pkg> is needed.
408    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
409
410    // All available activities, for your resolving pleasure.
411    final ActivityIntentResolver mActivities =
412            new ActivityIntentResolver();
413
414    // All available receivers, for your resolving pleasure.
415    final ActivityIntentResolver mReceivers =
416            new ActivityIntentResolver();
417
418    // All available services, for your resolving pleasure.
419    final ServiceIntentResolver mServices = new ServiceIntentResolver();
420
421    // All available providers, for your resolving pleasure.
422    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
423
424    // Mapping from provider base names (first directory in content URI codePath)
425    // to the provider information.
426    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
427            new HashMap<String, PackageParser.Provider>();
428
429    // Mapping from instrumentation class names to info about them.
430    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
431            new HashMap<ComponentName, PackageParser.Instrumentation>();
432
433    // Mapping from permission names to info about them.
434    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
435            new HashMap<String, PackageParser.PermissionGroup>();
436
437    // Packages whose data we have transfered into another package, thus
438    // should no longer exist.
439    final HashSet<String> mTransferedPackages = new HashSet<String>();
440
441    // Broadcast actions that are only available to the system.
442    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
443
444    /** List of packages waiting for verification. */
445    final SparseArray<PackageVerificationState> mPendingVerification
446            = new SparseArray<PackageVerificationState>();
447
448    HashSet<PackageParser.Package> mDeferredDexOpt = null;
449
450    /** Token for keys in mPendingVerification. */
451    private int mPendingVerificationToken = 0;
452
453    boolean mSystemReady;
454    boolean mSafeMode;
455    boolean mHasSystemUidErrors;
456
457    ApplicationInfo mAndroidApplication;
458    final ActivityInfo mResolveActivity = new ActivityInfo();
459    final ResolveInfo mResolveInfo = new ResolveInfo();
460    ComponentName mResolveComponentName;
461    PackageParser.Package mPlatformPackage;
462    ComponentName mCustomResolverComponentName;
463
464    boolean mResolverReplaced = false;
465
466    // Set of pending broadcasts for aggregating enable/disable of components.
467    static class PendingPackageBroadcasts {
468        // for each user id, a map of <package name -> components within that package>
469        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
470
471        public PendingPackageBroadcasts() {
472            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
473        }
474
475        public ArrayList<String> get(int userId, String packageName) {
476            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
477            return packages.get(packageName);
478        }
479
480        public void put(int userId, String packageName, ArrayList<String> components) {
481            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
482            packages.put(packageName, components);
483        }
484
485        public void remove(int userId, String packageName) {
486            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
487            if (packages != null) {
488                packages.remove(packageName);
489            }
490        }
491
492        public void remove(int userId) {
493            mUidMap.remove(userId);
494        }
495
496        public int userIdCount() {
497            return mUidMap.size();
498        }
499
500        public int userIdAt(int n) {
501            return mUidMap.keyAt(n);
502        }
503
504        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
505            return mUidMap.get(userId);
506        }
507
508        public int size() {
509            // total number of pending broadcast entries across all userIds
510            int num = 0;
511            for (int i = 0; i< mUidMap.size(); i++) {
512                num += mUidMap.valueAt(i).size();
513            }
514            return num;
515        }
516
517        public void clear() {
518            mUidMap.clear();
519        }
520
521        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
522            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
523            if (map == null) {
524                map = new HashMap<String, ArrayList<String>>();
525                mUidMap.put(userId, map);
526            }
527            return map;
528        }
529    }
530    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
531
532    // Service Connection to remote media container service to copy
533    // package uri's from external media onto secure containers
534    // or internal storage.
535    private IMediaContainerService mContainerService = null;
536
537    static final int SEND_PENDING_BROADCAST = 1;
538    static final int MCS_BOUND = 3;
539    static final int END_COPY = 4;
540    static final int INIT_COPY = 5;
541    static final int MCS_UNBIND = 6;
542    static final int START_CLEANING_PACKAGE = 7;
543    static final int FIND_INSTALL_LOC = 8;
544    static final int POST_INSTALL = 9;
545    static final int MCS_RECONNECT = 10;
546    static final int MCS_GIVE_UP = 11;
547    static final int UPDATED_MEDIA_STATUS = 12;
548    static final int WRITE_SETTINGS = 13;
549    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
550    static final int PACKAGE_VERIFIED = 15;
551    static final int CHECK_PENDING_VERIFICATION = 16;
552
553    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
554
555    // Delay time in millisecs
556    static final int BROADCAST_DELAY = 10 * 1000;
557
558    static UserManagerService sUserManager;
559
560    // Stores a list of users whose package restrictions file needs to be updated
561    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
562
563    final private DefaultContainerConnection mDefContainerConn =
564            new DefaultContainerConnection();
565    class DefaultContainerConnection implements ServiceConnection {
566        public void onServiceConnected(ComponentName name, IBinder service) {
567            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
568            IMediaContainerService imcs =
569                IMediaContainerService.Stub.asInterface(service);
570            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
571        }
572
573        public void onServiceDisconnected(ComponentName name) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
575        }
576    };
577
578    // Recordkeeping of restore-after-install operations that are currently in flight
579    // between the Package Manager and the Backup Manager
580    class PostInstallData {
581        public InstallArgs args;
582        public PackageInstalledInfo res;
583
584        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
585            args = _a;
586            res = _r;
587        }
588    };
589    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
590    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
591
592    private final String mRequiredVerifierPackage;
593
594    class PackageHandler extends Handler {
595        private boolean mBound = false;
596        final ArrayList<HandlerParams> mPendingInstalls =
597            new ArrayList<HandlerParams>();
598
599        private boolean connectToService() {
600            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
601                    " DefaultContainerService");
602            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
603            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
604            if (mContext.bindServiceAsUser(service, mDefContainerConn,
605                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
606                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
607                mBound = true;
608                return true;
609            }
610            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
611            return false;
612        }
613
614        private void disconnectService() {
615            mContainerService = null;
616            mBound = false;
617            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
618            mContext.unbindService(mDefContainerConn);
619            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
620        }
621
622        PackageHandler(Looper looper) {
623            super(looper);
624        }
625
626        public void handleMessage(Message msg) {
627            try {
628                doHandleMessage(msg);
629            } finally {
630                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
631            }
632        }
633
634        void doHandleMessage(Message msg) {
635            switch (msg.what) {
636                case INIT_COPY: {
637                    HandlerParams params = (HandlerParams) msg.obj;
638                    int idx = mPendingInstalls.size();
639                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
640                    // If a bind was already initiated we dont really
641                    // need to do anything. The pending install
642                    // will be processed later on.
643                    if (!mBound) {
644                        // If this is the only one pending we might
645                        // have to bind to the service again.
646                        if (!connectToService()) {
647                            Slog.e(TAG, "Failed to bind to media container service");
648                            params.serviceError();
649                            return;
650                        } else {
651                            // Once we bind to the service, the first
652                            // pending request will be processed.
653                            mPendingInstalls.add(idx, params);
654                        }
655                    } else {
656                        mPendingInstalls.add(idx, params);
657                        // Already bound to the service. Just make
658                        // sure we trigger off processing the first request.
659                        if (idx == 0) {
660                            mHandler.sendEmptyMessage(MCS_BOUND);
661                        }
662                    }
663                    break;
664                }
665                case MCS_BOUND: {
666                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
667                    if (msg.obj != null) {
668                        mContainerService = (IMediaContainerService) msg.obj;
669                    }
670                    if (mContainerService == null) {
671                        // Something seriously wrong. Bail out
672                        Slog.e(TAG, "Cannot bind to media container service");
673                        for (HandlerParams params : mPendingInstalls) {
674                            // Indicate service bind error
675                            params.serviceError();
676                        }
677                        mPendingInstalls.clear();
678                    } else if (mPendingInstalls.size() > 0) {
679                        HandlerParams params = mPendingInstalls.get(0);
680                        if (params != null) {
681                            if (params.startCopy()) {
682                                // We are done...  look for more work or to
683                                // go idle.
684                                if (DEBUG_SD_INSTALL) Log.i(TAG,
685                                        "Checking for more work or unbind...");
686                                // Delete pending install
687                                if (mPendingInstalls.size() > 0) {
688                                    mPendingInstalls.remove(0);
689                                }
690                                if (mPendingInstalls.size() == 0) {
691                                    if (mBound) {
692                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
693                                                "Posting delayed MCS_UNBIND");
694                                        removeMessages(MCS_UNBIND);
695                                        Message ubmsg = obtainMessage(MCS_UNBIND);
696                                        // Unbind after a little delay, to avoid
697                                        // continual thrashing.
698                                        sendMessageDelayed(ubmsg, 10000);
699                                    }
700                                } else {
701                                    // There are more pending requests in queue.
702                                    // Just post MCS_BOUND message to trigger processing
703                                    // of next pending install.
704                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
705                                            "Posting MCS_BOUND for next work");
706                                    mHandler.sendEmptyMessage(MCS_BOUND);
707                                }
708                            }
709                        }
710                    } else {
711                        // Should never happen ideally.
712                        Slog.w(TAG, "Empty queue");
713                    }
714                    break;
715                }
716                case MCS_RECONNECT: {
717                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
718                    if (mPendingInstalls.size() > 0) {
719                        if (mBound) {
720                            disconnectService();
721                        }
722                        if (!connectToService()) {
723                            Slog.e(TAG, "Failed to bind to media container service");
724                            for (HandlerParams params : mPendingInstalls) {
725                                // Indicate service bind error
726                                params.serviceError();
727                            }
728                            mPendingInstalls.clear();
729                        }
730                    }
731                    break;
732                }
733                case MCS_UNBIND: {
734                    // If there is no actual work left, then time to unbind.
735                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
736
737                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
738                        if (mBound) {
739                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
740
741                            disconnectService();
742                        }
743                    } else if (mPendingInstalls.size() > 0) {
744                        // There are more pending requests in queue.
745                        // Just post MCS_BOUND message to trigger processing
746                        // of next pending install.
747                        mHandler.sendEmptyMessage(MCS_BOUND);
748                    }
749
750                    break;
751                }
752                case MCS_GIVE_UP: {
753                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
754                    mPendingInstalls.remove(0);
755                    break;
756                }
757                case SEND_PENDING_BROADCAST: {
758                    String packages[];
759                    ArrayList<String> components[];
760                    int size = 0;
761                    int uids[];
762                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
763                    synchronized (mPackages) {
764                        if (mPendingBroadcasts == null) {
765                            return;
766                        }
767                        size = mPendingBroadcasts.size();
768                        if (size <= 0) {
769                            // Nothing to be done. Just return
770                            return;
771                        }
772                        packages = new String[size];
773                        components = new ArrayList[size];
774                        uids = new int[size];
775                        int i = 0;  // filling out the above arrays
776
777                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
778                            int packageUserId = mPendingBroadcasts.userIdAt(n);
779                            Iterator<Map.Entry<String, ArrayList<String>>> it
780                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
781                                            .entrySet().iterator();
782                            while (it.hasNext() && i < size) {
783                                Map.Entry<String, ArrayList<String>> ent = it.next();
784                                packages[i] = ent.getKey();
785                                components[i] = ent.getValue();
786                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
787                                uids[i] = (ps != null)
788                                        ? UserHandle.getUid(packageUserId, ps.appId)
789                                        : -1;
790                                i++;
791                            }
792                        }
793                        size = i;
794                        mPendingBroadcasts.clear();
795                    }
796                    // Send broadcasts
797                    for (int i = 0; i < size; i++) {
798                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
799                    }
800                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
801                    break;
802                }
803                case START_CLEANING_PACKAGE: {
804                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
805                    final String packageName = (String)msg.obj;
806                    final int userId = msg.arg1;
807                    final boolean andCode = msg.arg2 != 0;
808                    synchronized (mPackages) {
809                        if (userId == UserHandle.USER_ALL) {
810                            int[] users = sUserManager.getUserIds();
811                            for (int user : users) {
812                                mSettings.addPackageToCleanLPw(
813                                        new PackageCleanItem(user, packageName, andCode));
814                            }
815                        } else {
816                            mSettings.addPackageToCleanLPw(
817                                    new PackageCleanItem(userId, packageName, andCode));
818                        }
819                    }
820                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
821                    startCleaningPackages();
822                } break;
823                case POST_INSTALL: {
824                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
825                    PostInstallData data = mRunningInstalls.get(msg.arg1);
826                    mRunningInstalls.delete(msg.arg1);
827                    boolean deleteOld = false;
828
829                    if (data != null) {
830                        InstallArgs args = data.args;
831                        PackageInstalledInfo res = data.res;
832
833                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
834                            res.removedInfo.sendBroadcast(false, true, false);
835                            Bundle extras = new Bundle(1);
836                            extras.putInt(Intent.EXTRA_UID, res.uid);
837                            // Determine the set of users who are adding this
838                            // package for the first time vs. those who are seeing
839                            // an update.
840                            int[] firstUsers;
841                            int[] updateUsers = new int[0];
842                            if (res.origUsers == null || res.origUsers.length == 0) {
843                                firstUsers = res.newUsers;
844                            } else {
845                                firstUsers = new int[0];
846                                for (int i=0; i<res.newUsers.length; i++) {
847                                    int user = res.newUsers[i];
848                                    boolean isNew = true;
849                                    for (int j=0; j<res.origUsers.length; j++) {
850                                        if (res.origUsers[j] == user) {
851                                            isNew = false;
852                                            break;
853                                        }
854                                    }
855                                    if (isNew) {
856                                        int[] newFirst = new int[firstUsers.length+1];
857                                        System.arraycopy(firstUsers, 0, newFirst, 0,
858                                                firstUsers.length);
859                                        newFirst[firstUsers.length] = user;
860                                        firstUsers = newFirst;
861                                    } else {
862                                        int[] newUpdate = new int[updateUsers.length+1];
863                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
864                                                updateUsers.length);
865                                        newUpdate[updateUsers.length] = user;
866                                        updateUsers = newUpdate;
867                                    }
868                                }
869                            }
870                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
871                                    res.pkg.applicationInfo.packageName,
872                                    extras, null, null, firstUsers);
873                            final boolean update = res.removedInfo.removedPackage != null;
874                            if (update) {
875                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
876                            }
877                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
878                                    res.pkg.applicationInfo.packageName,
879                                    extras, null, null, updateUsers);
880                            if (update) {
881                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
882                                        res.pkg.applicationInfo.packageName,
883                                        extras, null, null, updateUsers);
884                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
885                                        null, null,
886                                        res.pkg.applicationInfo.packageName, null, updateUsers);
887
888                                // treat asec-hosted packages like removable media on upgrade
889                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
890                                    if (DEBUG_INSTALL) {
891                                        Slog.i(TAG, "upgrading pkg " + res.pkg
892                                                + " is ASEC-hosted -> AVAILABLE");
893                                    }
894                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
895                                    ArrayList<String> pkgList = new ArrayList<String>(1);
896                                    pkgList.add(res.pkg.applicationInfo.packageName);
897                                    sendResourcesChangedBroadcast(true, true,
898                                            pkgList,uidArray, null);
899                                }
900                            }
901                            if (res.removedInfo.args != null) {
902                                // Remove the replaced package's older resources safely now
903                                deleteOld = true;
904                            }
905
906                            // Log current value of "unknown sources" setting
907                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
908                                getUnknownSourcesSettings());
909                        }
910                        // Force a gc to clear up things
911                        Runtime.getRuntime().gc();
912                        // We delete after a gc for applications  on sdcard.
913                        if (deleteOld) {
914                            synchronized (mInstallLock) {
915                                res.removedInfo.args.doPostDeleteLI(true);
916                            }
917                        }
918                        if (args.observer != null) {
919                            try {
920                                args.observer.packageInstalled(res.name, res.returnCode);
921                            } catch (RemoteException e) {
922                                Slog.i(TAG, "Observer no longer exists.");
923                            }
924                        }
925                        if (args.observer2 != null) {
926                            try {
927                                Bundle extras = extrasForInstallResult(res);
928                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
929                            } catch (RemoteException e) {
930                                Slog.i(TAG, "Observer no longer exists.");
931                            }
932                        }
933                    } else {
934                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
935                    }
936                } break;
937                case UPDATED_MEDIA_STATUS: {
938                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
939                    boolean reportStatus = msg.arg1 == 1;
940                    boolean doGc = msg.arg2 == 1;
941                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
942                    if (doGc) {
943                        // Force a gc to clear up stale containers.
944                        Runtime.getRuntime().gc();
945                    }
946                    if (msg.obj != null) {
947                        @SuppressWarnings("unchecked")
948                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
949                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
950                        // Unload containers
951                        unloadAllContainers(args);
952                    }
953                    if (reportStatus) {
954                        try {
955                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
956                            PackageHelper.getMountService().finishMediaUpdate();
957                        } catch (RemoteException e) {
958                            Log.e(TAG, "MountService not running?");
959                        }
960                    }
961                } break;
962                case WRITE_SETTINGS: {
963                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
964                    synchronized (mPackages) {
965                        removeMessages(WRITE_SETTINGS);
966                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
967                        mSettings.writeLPr();
968                        mDirtyUsers.clear();
969                    }
970                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
971                } break;
972                case WRITE_PACKAGE_RESTRICTIONS: {
973                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
974                    synchronized (mPackages) {
975                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
976                        for (int userId : mDirtyUsers) {
977                            mSettings.writePackageRestrictionsLPr(userId);
978                        }
979                        mDirtyUsers.clear();
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                } break;
983                case CHECK_PENDING_VERIFICATION: {
984                    final int verificationId = msg.arg1;
985                    final PackageVerificationState state = mPendingVerification.get(verificationId);
986
987                    if ((state != null) && !state.timeoutExtended()) {
988                        final InstallArgs args = state.getInstallArgs();
989                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
990                        mPendingVerification.remove(verificationId);
991
992                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
993
994                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
995                            Slog.i(TAG, "Continuing with installation of "
996                                    + args.packageURI.toString());
997                            state.setVerifierResponse(Binder.getCallingUid(),
998                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
999                            broadcastPackageVerified(verificationId, args.packageURI,
1000                                    PackageManager.VERIFICATION_ALLOW,
1001                                    state.getInstallArgs().getUser());
1002                            try {
1003                                ret = args.copyApk(mContainerService, true);
1004                            } catch (RemoteException e) {
1005                                Slog.e(TAG, "Could not contact the ContainerService");
1006                            }
1007                        } else {
1008                            broadcastPackageVerified(verificationId, args.packageURI,
1009                                    PackageManager.VERIFICATION_REJECT,
1010                                    state.getInstallArgs().getUser());
1011                        }
1012
1013                        processPendingInstall(args, ret);
1014                        mHandler.sendEmptyMessage(MCS_UNBIND);
1015                    }
1016                    break;
1017                }
1018                case PACKAGE_VERIFIED: {
1019                    final int verificationId = msg.arg1;
1020
1021                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1022                    if (state == null) {
1023                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1024                        break;
1025                    }
1026
1027                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1028
1029                    state.setVerifierResponse(response.callerUid, response.code);
1030
1031                    if (state.isVerificationComplete()) {
1032                        mPendingVerification.remove(verificationId);
1033
1034                        final InstallArgs args = state.getInstallArgs();
1035
1036                        int ret;
1037                        if (state.isInstallAllowed()) {
1038                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1039                            broadcastPackageVerified(verificationId, args.packageURI,
1040                                    response.code, state.getInstallArgs().getUser());
1041                            try {
1042                                ret = args.copyApk(mContainerService, true);
1043                            } catch (RemoteException e) {
1044                                Slog.e(TAG, "Could not contact the ContainerService");
1045                            }
1046                        } else {
1047                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1048                        }
1049
1050                        processPendingInstall(args, ret);
1051
1052                        mHandler.sendEmptyMessage(MCS_UNBIND);
1053                    }
1054
1055                    break;
1056                }
1057            }
1058        }
1059    }
1060
1061    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1062        Bundle extras = null;
1063        switch (res.returnCode) {
1064            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1065                extras = new Bundle();
1066                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1067                        res.origPermission);
1068                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1069                        res.origPackage);
1070                break;
1071            }
1072        }
1073        return extras;
1074    }
1075
1076    void scheduleWriteSettingsLocked() {
1077        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1078            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1079        }
1080    }
1081
1082    void scheduleWritePackageRestrictionsLocked(int userId) {
1083        if (!sUserManager.exists(userId)) return;
1084        mDirtyUsers.add(userId);
1085        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1086            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1087        }
1088    }
1089
1090    public static final IPackageManager main(Context context, Installer installer,
1091            boolean factoryTest, boolean onlyCore) {
1092        PackageManagerService m = new PackageManagerService(context, installer,
1093                factoryTest, onlyCore);
1094        ServiceManager.addService("package", m);
1095        return m;
1096    }
1097
1098    static String[] splitString(String str, char sep) {
1099        int count = 1;
1100        int i = 0;
1101        while ((i=str.indexOf(sep, i)) >= 0) {
1102            count++;
1103            i++;
1104        }
1105
1106        String[] res = new String[count];
1107        i=0;
1108        count = 0;
1109        int lastI=0;
1110        while ((i=str.indexOf(sep, i)) >= 0) {
1111            res[count] = str.substring(lastI, i);
1112            count++;
1113            i++;
1114            lastI = i;
1115        }
1116        res[count] = str.substring(lastI, str.length());
1117        return res;
1118    }
1119
1120    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1121        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1122                Context.DISPLAY_SERVICE);
1123        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1124    }
1125
1126    public PackageManagerService(Context context, Installer installer,
1127            boolean factoryTest, boolean onlyCore) {
1128        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1129                SystemClock.uptimeMillis());
1130
1131        if (mSdkVersion <= 0) {
1132            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1133        }
1134
1135        mContext = context;
1136        mFactoryTest = factoryTest;
1137        mOnlyCore = onlyCore;
1138        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1139        mMetrics = new DisplayMetrics();
1140        mSettings = new Settings(context);
1141        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1142                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1143        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1144                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1145        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1146                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1147        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1148                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1149        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1150                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1151        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1152                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1153
1154        String separateProcesses = SystemProperties.get("debug.separate_processes");
1155        if (separateProcesses != null && separateProcesses.length() > 0) {
1156            if ("*".equals(separateProcesses)) {
1157                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1158                mSeparateProcesses = null;
1159                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1160            } else {
1161                mDefParseFlags = 0;
1162                mSeparateProcesses = separateProcesses.split(",");
1163                Slog.w(TAG, "Running with debug.separate_processes: "
1164                        + separateProcesses);
1165            }
1166        } else {
1167            mDefParseFlags = 0;
1168            mSeparateProcesses = null;
1169        }
1170
1171        mInstaller = installer;
1172
1173        getDefaultDisplayMetrics(context, mMetrics);
1174
1175        synchronized (mInstallLock) {
1176        // writer
1177        synchronized (mPackages) {
1178            mHandlerThread = new ServiceThread(TAG,
1179                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1180            mHandlerThread.start();
1181            mHandler = new PackageHandler(mHandlerThread.getLooper());
1182            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1183
1184            File dataDir = Environment.getDataDirectory();
1185            mAppDataDir = new File(dataDir, "data");
1186            mAppInstallDir = new File(dataDir, "app");
1187            mAppLibInstallDir = new File(dataDir, "app-lib");
1188            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1189            mUserAppDataDir = new File(dataDir, "user");
1190            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1191
1192            sUserManager = new UserManagerService(context, this,
1193                    mInstallLock, mPackages);
1194
1195            // Read permissions and features from system
1196            readPermissions(Environment.buildPath(
1197                    Environment.getRootDirectory(), "etc", "permissions"), false);
1198            // Only read features from OEM
1199            readPermissions(Environment.buildPath(
1200                    Environment.getOemDirectory(), "etc", "permissions"), true);
1201
1202            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1203
1204            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1205                    mSdkVersion, mOnlyCore);
1206
1207            String customResolverActivity = Resources.getSystem().getString(
1208                    R.string.config_customResolverActivity);
1209            if (TextUtils.isEmpty(customResolverActivity)) {
1210                customResolverActivity = null;
1211            } else {
1212                mCustomResolverComponentName = ComponentName.unflattenFromString(
1213                        customResolverActivity);
1214            }
1215
1216            long startTime = SystemClock.uptimeMillis();
1217
1218            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1219                    startTime);
1220
1221            // Set flag to monitor and not change apk file paths when
1222            // scanning install directories.
1223            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1224            if (mNoDexOpt) {
1225                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1226                scanMode |= SCAN_NO_DEX;
1227            }
1228
1229            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1230
1231            /**
1232             * Add everything in the in the boot class path to the
1233             * list of process files because dexopt will have been run
1234             * if necessary during zygote startup.
1235             */
1236            String bootClassPath = System.getProperty("java.boot.class.path");
1237            if (bootClassPath != null) {
1238                String[] paths = splitString(bootClassPath, ':');
1239                for (int i=0; i<paths.length; i++) {
1240                    alreadyDexOpted.add(paths[i]);
1241                }
1242            } else {
1243                Slog.w(TAG, "No BOOTCLASSPATH found!");
1244            }
1245
1246            boolean didDexOpt = false;
1247
1248            final List<String> instructionSets = getAllInstructionSets();
1249
1250            /**
1251             * Ensure all external libraries have had dexopt run on them.
1252             */
1253            if (mSharedLibraries.size() > 0) {
1254                // NOTE: For now, we're compiling these system "shared libraries"
1255                // (and framework jars) into all available architectures. It's possible
1256                // to compile them only when we come across an app that uses them (there's
1257                // already logic for that in scanPackageLI) but that adds some complexity.
1258                for (String instructionSet : instructionSets) {
1259                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1260                        final String lib = libEntry.path;
1261                        if (lib == null) {
1262                            continue;
1263                        }
1264
1265                        try {
1266                            if (dalvik.system.DexFile.isDexOptNeededInternal(
1267                                    lib, null, instructionSet, false)) {
1268                                alreadyDexOpted.add(lib);
1269
1270                                // The list of "shared libraries" we have at this point is
1271                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1272                                didDexOpt = true;
1273                            }
1274                        } catch (FileNotFoundException e) {
1275                            Slog.w(TAG, "Library not found: " + lib);
1276                        } catch (IOException e) {
1277                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1278                                    + e.getMessage());
1279                        }
1280                    }
1281                }
1282            }
1283
1284            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1285
1286            // Gross hack for now: we know this file doesn't contain any
1287            // code, so don't dexopt it to avoid the resulting log spew.
1288            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1289
1290            // Gross hack for now: we know this file is only part of
1291            // the boot class path for art, so don't dexopt it to
1292            // avoid the resulting log spew.
1293            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1294
1295            /**
1296             * And there are a number of commands implemented in Java, which
1297             * we currently need to do the dexopt on so that they can be
1298             * run from a non-root shell.
1299             */
1300            String[] frameworkFiles = frameworkDir.list();
1301            if (frameworkFiles != null) {
1302                // TODO: We could compile these only for the most preferred ABI. We should
1303                // first double check that the dex files for these commands are not referenced
1304                // by other system apps.
1305                for (String instructionSet : instructionSets) {
1306                    for (int i=0; i<frameworkFiles.length; i++) {
1307                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1308                        String path = libPath.getPath();
1309                        // Skip the file if we already did it.
1310                        if (alreadyDexOpted.contains(path)) {
1311                            continue;
1312                        }
1313                        // Skip the file if it is not a type we want to dexopt.
1314                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1315                            continue;
1316                        }
1317                        try {
1318                            if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1319                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1320                                didDexOpt = true;
1321                            }
1322                        } catch (FileNotFoundException e) {
1323                            Slog.w(TAG, "Jar not found: " + path);
1324                        } catch (IOException e) {
1325                            Slog.w(TAG, "Exception reading jar: " + path, e);
1326                        }
1327                    }
1328                }
1329            }
1330
1331            if (didDexOpt) {
1332                File dalvikCacheDir = new File(dataDir, "dalvik-cache");
1333
1334                // If we had to do a dexopt of one of the previous
1335                // things, then something on the system has changed.
1336                // Consider this significant, and wipe away all other
1337                // existing dexopt files to ensure we don't leave any
1338                // dangling around.
1339                String[] files = dalvikCacheDir.list();
1340                if (files != null) {
1341                    for (int i=0; i<files.length; i++) {
1342                        String fn = files[i];
1343                        if (fn.startsWith("data@app@")
1344                                || fn.startsWith("data@app-private@")) {
1345                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1346                            (new File(dalvikCacheDir, fn)).delete();
1347                        }
1348                    }
1349                }
1350            }
1351
1352            // Collect vendor overlay packages.
1353            // (Do this before scanning any apps.)
1354            // For security and version matching reason, only consider
1355            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1356            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1357            mVendorOverlayInstallObserver = new AppDirObserver(
1358                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1359            mVendorOverlayInstallObserver.startWatching();
1360            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1361                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1362
1363            // Find base frameworks (resource packages without code).
1364            mFrameworkInstallObserver = new AppDirObserver(
1365                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1366            mFrameworkInstallObserver.startWatching();
1367            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1368                    | PackageParser.PARSE_IS_SYSTEM_DIR
1369                    | PackageParser.PARSE_IS_PRIVILEGED,
1370                    scanMode | SCAN_NO_DEX, 0);
1371
1372            // Collected privileged system packages.
1373            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1374            mPrivilegedInstallObserver = new AppDirObserver(
1375                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1376            mPrivilegedInstallObserver.startWatching();
1377                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1378                        | PackageParser.PARSE_IS_SYSTEM_DIR
1379                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1380
1381            // Collect ordinary system packages.
1382            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1383            mSystemInstallObserver = new AppDirObserver(
1384                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1385            mSystemInstallObserver.startWatching();
1386            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1387                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1388
1389            // Collect all vendor packages.
1390            File vendorAppDir = new File("/vendor/app");
1391            try {
1392                vendorAppDir = vendorAppDir.getCanonicalFile();
1393            } catch (IOException e) {
1394                // failed to look up canonical path, continue with original one
1395            }
1396            mVendorInstallObserver = new AppDirObserver(
1397                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1398            mVendorInstallObserver.startWatching();
1399            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1400                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1401
1402            // Collect all OEM packages.
1403            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1404            mOemInstallObserver = new AppDirObserver(
1405                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1406            mOemInstallObserver.startWatching();
1407            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1408                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1409
1410            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1411            mInstaller.moveFiles();
1412
1413            // Prune any system packages that no longer exist.
1414            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1415            if (!mOnlyCore) {
1416                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1417                while (psit.hasNext()) {
1418                    PackageSetting ps = psit.next();
1419
1420                    /*
1421                     * If this is not a system app, it can't be a
1422                     * disable system app.
1423                     */
1424                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1425                        continue;
1426                    }
1427
1428                    /*
1429                     * If the package is scanned, it's not erased.
1430                     */
1431                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1432                    if (scannedPkg != null) {
1433                        /*
1434                         * If the system app is both scanned and in the
1435                         * disabled packages list, then it must have been
1436                         * added via OTA. Remove it from the currently
1437                         * scanned package so the previously user-installed
1438                         * application can be scanned.
1439                         */
1440                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1441                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1442                                    + "; removing system app");
1443                            removePackageLI(ps, true);
1444                        }
1445
1446                        continue;
1447                    }
1448
1449                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1450                        psit.remove();
1451                        String msg = "System package " + ps.name
1452                                + " no longer exists; wiping its data";
1453                        reportSettingsProblem(Log.WARN, msg);
1454                        removeDataDirsLI(ps.name);
1455                    } else {
1456                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1457                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1458                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1459                        }
1460                    }
1461                }
1462            }
1463
1464            //look for any incomplete package installations
1465            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1466            //clean up list
1467            for(int i = 0; i < deletePkgsList.size(); i++) {
1468                //clean up here
1469                cleanupInstallFailedPackage(deletePkgsList.get(i));
1470            }
1471            //delete tmp files
1472            deleteTempPackageFiles();
1473
1474            // Remove any shared userIDs that have no associated packages
1475            mSettings.pruneSharedUsersLPw();
1476
1477            if (!mOnlyCore) {
1478                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1479                        SystemClock.uptimeMillis());
1480                mAppInstallObserver = new AppDirObserver(
1481                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1482                mAppInstallObserver.startWatching();
1483                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1484
1485                mDrmAppInstallObserver = new AppDirObserver(
1486                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1487                mDrmAppInstallObserver.startWatching();
1488                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1489                        scanMode, 0);
1490
1491                /**
1492                 * Remove disable package settings for any updated system
1493                 * apps that were removed via an OTA. If they're not a
1494                 * previously-updated app, remove them completely.
1495                 * Otherwise, just revoke their system-level permissions.
1496                 */
1497                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1498                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1499                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1500
1501                    String msg;
1502                    if (deletedPkg == null) {
1503                        msg = "Updated system package " + deletedAppName
1504                                + " no longer exists; wiping its data";
1505                        removeDataDirsLI(deletedAppName);
1506                    } else {
1507                        msg = "Updated system app + " + deletedAppName
1508                                + " no longer present; removing system privileges for "
1509                                + deletedAppName;
1510
1511                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1512
1513                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1514                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1515                    }
1516                    reportSettingsProblem(Log.WARN, msg);
1517                }
1518            } else {
1519                mAppInstallObserver = null;
1520                mDrmAppInstallObserver = null;
1521            }
1522
1523            // Now that we know all of the shared libraries, update all clients to have
1524            // the correct library paths.
1525            updateAllSharedLibrariesLPw();
1526
1527
1528            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1529                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1530                        false /* force dexopt */, false /* defer dexopt */);
1531            }
1532
1533            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1534                    SystemClock.uptimeMillis());
1535            Slog.i(TAG, "Time to scan packages: "
1536                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1537                    + " seconds");
1538
1539            // If the platform SDK has changed since the last time we booted,
1540            // we need to re-grant app permission to catch any new ones that
1541            // appear.  This is really a hack, and means that apps can in some
1542            // cases get permissions that the user didn't initially explicitly
1543            // allow...  it would be nice to have some better way to handle
1544            // this situation.
1545            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1546                    != mSdkVersion;
1547            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1548                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1549                    + "; regranting permissions for internal storage");
1550            mSettings.mInternalSdkPlatform = mSdkVersion;
1551
1552            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1553                    | (regrantPermissions
1554                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1555                            : 0));
1556
1557            // If this is the first boot, and it is a normal boot, then
1558            // we need to initialize the default preferred apps.
1559            if (!mRestoredSettings && !onlyCore) {
1560                mSettings.readDefaultPreferredAppsLPw(this, 0);
1561            }
1562
1563            // All the changes are done during package scanning.
1564            mSettings.updateInternalDatabaseVersion();
1565
1566            // can downgrade to reader
1567            mSettings.writeLPr();
1568
1569            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1570                    SystemClock.uptimeMillis());
1571
1572            // Now after opening every single application zip, make sure they
1573            // are all flushed.  Not really needed, but keeps things nice and
1574            // tidy.
1575            Runtime.getRuntime().gc();
1576
1577            mRequiredVerifierPackage = getRequiredVerifierLPr();
1578        } // synchronized (mPackages)
1579        } // synchronized (mInstallLock)
1580    }
1581
1582    public boolean isFirstBoot() {
1583        return !mRestoredSettings;
1584    }
1585
1586    public boolean isOnlyCoreApps() {
1587        return mOnlyCore;
1588    }
1589
1590    private String getRequiredVerifierLPr() {
1591        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1592        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1593                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1594
1595        String requiredVerifier = null;
1596
1597        final int N = receivers.size();
1598        for (int i = 0; i < N; i++) {
1599            final ResolveInfo info = receivers.get(i);
1600
1601            if (info.activityInfo == null) {
1602                continue;
1603            }
1604
1605            final String packageName = info.activityInfo.packageName;
1606
1607            final PackageSetting ps = mSettings.mPackages.get(packageName);
1608            if (ps == null) {
1609                continue;
1610            }
1611
1612            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1613            if (!gp.grantedPermissions
1614                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1615                continue;
1616            }
1617
1618            if (requiredVerifier != null) {
1619                throw new RuntimeException("There can be only one required verifier");
1620            }
1621
1622            requiredVerifier = packageName;
1623        }
1624
1625        return requiredVerifier;
1626    }
1627
1628    @Override
1629    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1630            throws RemoteException {
1631        try {
1632            return super.onTransact(code, data, reply, flags);
1633        } catch (RuntimeException e) {
1634            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1635                Slog.wtf(TAG, "Package Manager Crash", e);
1636            }
1637            throw e;
1638        }
1639    }
1640
1641    void cleanupInstallFailedPackage(PackageSetting ps) {
1642        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1643        removeDataDirsLI(ps.name);
1644        if (ps.codePath != null) {
1645            if (!ps.codePath.delete()) {
1646                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1647            }
1648        }
1649        if (ps.resourcePath != null) {
1650            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1651                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1652            }
1653        }
1654        mSettings.removePackageLPw(ps.name);
1655    }
1656
1657    void readPermissions(File libraryDir, boolean onlyFeatures) {
1658        // Read permissions from .../etc/permission directory.
1659        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1660            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1661            return;
1662        }
1663        if (!libraryDir.canRead()) {
1664            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1665            return;
1666        }
1667
1668        // Iterate over the files in the directory and scan .xml files
1669        for (File f : libraryDir.listFiles()) {
1670            // We'll read platform.xml last
1671            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1672                continue;
1673            }
1674
1675            if (!f.getPath().endsWith(".xml")) {
1676                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1677                continue;
1678            }
1679            if (!f.canRead()) {
1680                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1681                continue;
1682            }
1683
1684            readPermissionsFromXml(f, onlyFeatures);
1685        }
1686
1687        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1688        final File permFile = new File(Environment.getRootDirectory(),
1689                "etc/permissions/platform.xml");
1690        readPermissionsFromXml(permFile, onlyFeatures);
1691    }
1692
1693    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1694        FileReader permReader = null;
1695        try {
1696            permReader = new FileReader(permFile);
1697        } catch (FileNotFoundException e) {
1698            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1699            return;
1700        }
1701
1702        try {
1703            XmlPullParser parser = Xml.newPullParser();
1704            parser.setInput(permReader);
1705
1706            XmlUtils.beginDocument(parser, "permissions");
1707
1708            while (true) {
1709                XmlUtils.nextElement(parser);
1710                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1711                    break;
1712                }
1713
1714                String name = parser.getName();
1715                if ("group".equals(name) && !onlyFeatures) {
1716                    String gidStr = parser.getAttributeValue(null, "gid");
1717                    if (gidStr != null) {
1718                        int gid = Process.getGidForName(gidStr);
1719                        mGlobalGids = appendInt(mGlobalGids, gid);
1720                    } else {
1721                        Slog.w(TAG, "<group> without gid at "
1722                                + parser.getPositionDescription());
1723                    }
1724
1725                    XmlUtils.skipCurrentTag(parser);
1726                    continue;
1727                } else if ("permission".equals(name) && !onlyFeatures) {
1728                    String perm = parser.getAttributeValue(null, "name");
1729                    if (perm == null) {
1730                        Slog.w(TAG, "<permission> without name at "
1731                                + parser.getPositionDescription());
1732                        XmlUtils.skipCurrentTag(parser);
1733                        continue;
1734                    }
1735                    perm = perm.intern();
1736                    readPermission(parser, perm);
1737
1738                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1739                    String perm = parser.getAttributeValue(null, "name");
1740                    if (perm == null) {
1741                        Slog.w(TAG, "<assign-permission> without name at "
1742                                + parser.getPositionDescription());
1743                        XmlUtils.skipCurrentTag(parser);
1744                        continue;
1745                    }
1746                    String uidStr = parser.getAttributeValue(null, "uid");
1747                    if (uidStr == null) {
1748                        Slog.w(TAG, "<assign-permission> without uid at "
1749                                + parser.getPositionDescription());
1750                        XmlUtils.skipCurrentTag(parser);
1751                        continue;
1752                    }
1753                    int uid = Process.getUidForName(uidStr);
1754                    if (uid < 0) {
1755                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1756                                + uidStr + "\" at "
1757                                + parser.getPositionDescription());
1758                        XmlUtils.skipCurrentTag(parser);
1759                        continue;
1760                    }
1761                    perm = perm.intern();
1762                    HashSet<String> perms = mSystemPermissions.get(uid);
1763                    if (perms == null) {
1764                        perms = new HashSet<String>();
1765                        mSystemPermissions.put(uid, perms);
1766                    }
1767                    perms.add(perm);
1768                    XmlUtils.skipCurrentTag(parser);
1769
1770                } else if ("library".equals(name) && !onlyFeatures) {
1771                    String lname = parser.getAttributeValue(null, "name");
1772                    String lfile = parser.getAttributeValue(null, "file");
1773                    if (lname == null) {
1774                        Slog.w(TAG, "<library> without name at "
1775                                + parser.getPositionDescription());
1776                    } else if (lfile == null) {
1777                        Slog.w(TAG, "<library> without file at "
1778                                + parser.getPositionDescription());
1779                    } else {
1780                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1781                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1782                    }
1783                    XmlUtils.skipCurrentTag(parser);
1784                    continue;
1785
1786                } else if ("feature".equals(name)) {
1787                    String fname = parser.getAttributeValue(null, "name");
1788                    if (fname == null) {
1789                        Slog.w(TAG, "<feature> without name at "
1790                                + parser.getPositionDescription());
1791                    } else {
1792                        //Log.i(TAG, "Got feature " + fname);
1793                        FeatureInfo fi = new FeatureInfo();
1794                        fi.name = fname;
1795                        mAvailableFeatures.put(fname, fi);
1796                    }
1797                    XmlUtils.skipCurrentTag(parser);
1798                    continue;
1799
1800                } else {
1801                    XmlUtils.skipCurrentTag(parser);
1802                    continue;
1803                }
1804
1805            }
1806            permReader.close();
1807        } catch (XmlPullParserException e) {
1808            Slog.w(TAG, "Got execption parsing permissions.", e);
1809        } catch (IOException e) {
1810            Slog.w(TAG, "Got execption parsing permissions.", e);
1811        }
1812    }
1813
1814    void readPermission(XmlPullParser parser, String name)
1815            throws IOException, XmlPullParserException {
1816
1817        name = name.intern();
1818
1819        BasePermission bp = mSettings.mPermissions.get(name);
1820        if (bp == null) {
1821            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1822            mSettings.mPermissions.put(name, bp);
1823        }
1824        int outerDepth = parser.getDepth();
1825        int type;
1826        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1827               && (type != XmlPullParser.END_TAG
1828                       || parser.getDepth() > outerDepth)) {
1829            if (type == XmlPullParser.END_TAG
1830                    || type == XmlPullParser.TEXT) {
1831                continue;
1832            }
1833
1834            String tagName = parser.getName();
1835            if ("group".equals(tagName)) {
1836                String gidStr = parser.getAttributeValue(null, "gid");
1837                if (gidStr != null) {
1838                    int gid = Process.getGidForName(gidStr);
1839                    bp.gids = appendInt(bp.gids, gid);
1840                } else {
1841                    Slog.w(TAG, "<group> without gid at "
1842                            + parser.getPositionDescription());
1843                }
1844            }
1845            XmlUtils.skipCurrentTag(parser);
1846        }
1847    }
1848
1849    static int[] appendInts(int[] cur, int[] add) {
1850        if (add == null) return cur;
1851        if (cur == null) return add;
1852        final int N = add.length;
1853        for (int i=0; i<N; i++) {
1854            cur = appendInt(cur, add[i]);
1855        }
1856        return cur;
1857    }
1858
1859    static int[] removeInts(int[] cur, int[] rem) {
1860        if (rem == null) return cur;
1861        if (cur == null) return cur;
1862        final int N = rem.length;
1863        for (int i=0; i<N; i++) {
1864            cur = removeInt(cur, rem[i]);
1865        }
1866        return cur;
1867    }
1868
1869    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1870        if (!sUserManager.exists(userId)) return null;
1871        final PackageSetting ps = (PackageSetting) p.mExtras;
1872        if (ps == null) {
1873            return null;
1874        }
1875        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1876        final PackageUserState state = ps.readUserState(userId);
1877        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1878                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1879                state, userId);
1880    }
1881
1882    public boolean isPackageAvailable(String packageName, int userId) {
1883        if (!sUserManager.exists(userId)) return false;
1884        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1885        synchronized (mPackages) {
1886            PackageParser.Package p = mPackages.get(packageName);
1887            if (p != null) {
1888                final PackageSetting ps = (PackageSetting) p.mExtras;
1889                if (ps != null) {
1890                    final PackageUserState state = ps.readUserState(userId);
1891                    if (state != null) {
1892                        return PackageParser.isAvailable(state);
1893                    }
1894                }
1895            }
1896        }
1897        return false;
1898    }
1899
1900    @Override
1901    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1902        if (!sUserManager.exists(userId)) return null;
1903        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1904        // reader
1905        synchronized (mPackages) {
1906            PackageParser.Package p = mPackages.get(packageName);
1907            if (DEBUG_PACKAGE_INFO)
1908                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1909            if (p != null) {
1910                return generatePackageInfo(p, flags, userId);
1911            }
1912            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1913                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1914            }
1915        }
1916        return null;
1917    }
1918
1919    public String[] currentToCanonicalPackageNames(String[] names) {
1920        String[] out = new String[names.length];
1921        // reader
1922        synchronized (mPackages) {
1923            for (int i=names.length-1; i>=0; i--) {
1924                PackageSetting ps = mSettings.mPackages.get(names[i]);
1925                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1926            }
1927        }
1928        return out;
1929    }
1930
1931    public String[] canonicalToCurrentPackageNames(String[] names) {
1932        String[] out = new String[names.length];
1933        // reader
1934        synchronized (mPackages) {
1935            for (int i=names.length-1; i>=0; i--) {
1936                String cur = mSettings.mRenamedPackages.get(names[i]);
1937                out[i] = cur != null ? cur : names[i];
1938            }
1939        }
1940        return out;
1941    }
1942
1943    @Override
1944    public int getPackageUid(String packageName, int userId) {
1945        if (!sUserManager.exists(userId)) return -1;
1946        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1947        // reader
1948        synchronized (mPackages) {
1949            PackageParser.Package p = mPackages.get(packageName);
1950            if(p != null) {
1951                return UserHandle.getUid(userId, p.applicationInfo.uid);
1952            }
1953            PackageSetting ps = mSettings.mPackages.get(packageName);
1954            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1955                return -1;
1956            }
1957            p = ps.pkg;
1958            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1959        }
1960    }
1961
1962    @Override
1963    public int[] getPackageGids(String packageName) {
1964        // reader
1965        synchronized (mPackages) {
1966            PackageParser.Package p = mPackages.get(packageName);
1967            if (DEBUG_PACKAGE_INFO)
1968                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1969            if (p != null) {
1970                final PackageSetting ps = (PackageSetting)p.mExtras;
1971                return ps.getGids();
1972            }
1973        }
1974        // stupid thing to indicate an error.
1975        return new int[0];
1976    }
1977
1978    static final PermissionInfo generatePermissionInfo(
1979            BasePermission bp, int flags) {
1980        if (bp.perm != null) {
1981            return PackageParser.generatePermissionInfo(bp.perm, flags);
1982        }
1983        PermissionInfo pi = new PermissionInfo();
1984        pi.name = bp.name;
1985        pi.packageName = bp.sourcePackage;
1986        pi.nonLocalizedLabel = bp.name;
1987        pi.protectionLevel = bp.protectionLevel;
1988        return pi;
1989    }
1990
1991    public PermissionInfo getPermissionInfo(String name, int flags) {
1992        // reader
1993        synchronized (mPackages) {
1994            final BasePermission p = mSettings.mPermissions.get(name);
1995            if (p != null) {
1996                return generatePermissionInfo(p, flags);
1997            }
1998            return null;
1999        }
2000    }
2001
2002    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2003        // reader
2004        synchronized (mPackages) {
2005            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2006            for (BasePermission p : mSettings.mPermissions.values()) {
2007                if (group == null) {
2008                    if (p.perm == null || p.perm.info.group == null) {
2009                        out.add(generatePermissionInfo(p, flags));
2010                    }
2011                } else {
2012                    if (p.perm != null && group.equals(p.perm.info.group)) {
2013                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2014                    }
2015                }
2016            }
2017
2018            if (out.size() > 0) {
2019                return out;
2020            }
2021            return mPermissionGroups.containsKey(group) ? out : null;
2022        }
2023    }
2024
2025    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2026        // reader
2027        synchronized (mPackages) {
2028            return PackageParser.generatePermissionGroupInfo(
2029                    mPermissionGroups.get(name), flags);
2030        }
2031    }
2032
2033    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2034        // reader
2035        synchronized (mPackages) {
2036            final int N = mPermissionGroups.size();
2037            ArrayList<PermissionGroupInfo> out
2038                    = new ArrayList<PermissionGroupInfo>(N);
2039            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2040                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2041            }
2042            return out;
2043        }
2044    }
2045
2046    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2047            int userId) {
2048        if (!sUserManager.exists(userId)) return null;
2049        PackageSetting ps = mSettings.mPackages.get(packageName);
2050        if (ps != null) {
2051            if (ps.pkg == null) {
2052                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2053                        flags, userId);
2054                if (pInfo != null) {
2055                    return pInfo.applicationInfo;
2056                }
2057                return null;
2058            }
2059            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2060                    ps.readUserState(userId), userId);
2061        }
2062        return null;
2063    }
2064
2065    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2066            int userId) {
2067        if (!sUserManager.exists(userId)) return null;
2068        PackageSetting ps = mSettings.mPackages.get(packageName);
2069        if (ps != null) {
2070            PackageParser.Package pkg = ps.pkg;
2071            if (pkg == null) {
2072                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2073                    return null;
2074                }
2075                pkg = new PackageParser.Package(packageName);
2076                pkg.applicationInfo.packageName = packageName;
2077                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2078                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2079                pkg.applicationInfo.sourceDir = ps.codePathString;
2080                pkg.applicationInfo.dataDir =
2081                        getDataPathForPackage(packageName, 0).getPath();
2082                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2083                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2084            }
2085            return generatePackageInfo(pkg, flags, userId);
2086        }
2087        return null;
2088    }
2089
2090    @Override
2091    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2092        if (!sUserManager.exists(userId)) return null;
2093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2094        // writer
2095        synchronized (mPackages) {
2096            PackageParser.Package p = mPackages.get(packageName);
2097            if (DEBUG_PACKAGE_INFO) Log.v(
2098                    TAG, "getApplicationInfo " + packageName
2099                    + ": " + p);
2100            if (p != null) {
2101                PackageSetting ps = mSettings.mPackages.get(packageName);
2102                if (ps == null) return null;
2103                // Note: isEnabledLP() does not apply here - always return info
2104                return PackageParser.generateApplicationInfo(
2105                        p, flags, ps.readUserState(userId), userId);
2106            }
2107            if ("android".equals(packageName)||"system".equals(packageName)) {
2108                return mAndroidApplication;
2109            }
2110            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2111                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2112            }
2113        }
2114        return null;
2115    }
2116
2117
2118    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2119        mContext.enforceCallingOrSelfPermission(
2120                android.Manifest.permission.CLEAR_APP_CACHE, null);
2121        // Queue up an async operation since clearing cache may take a little while.
2122        mHandler.post(new Runnable() {
2123            public void run() {
2124                mHandler.removeCallbacks(this);
2125                int retCode = -1;
2126                synchronized (mInstallLock) {
2127                    retCode = mInstaller.freeCache(freeStorageSize);
2128                    if (retCode < 0) {
2129                        Slog.w(TAG, "Couldn't clear application caches");
2130                    }
2131                }
2132                if (observer != null) {
2133                    try {
2134                        observer.onRemoveCompleted(null, (retCode >= 0));
2135                    } catch (RemoteException e) {
2136                        Slog.w(TAG, "RemoveException when invoking call back");
2137                    }
2138                }
2139            }
2140        });
2141    }
2142
2143    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2144        mContext.enforceCallingOrSelfPermission(
2145                android.Manifest.permission.CLEAR_APP_CACHE, null);
2146        // Queue up an async operation since clearing cache may take a little while.
2147        mHandler.post(new Runnable() {
2148            public void run() {
2149                mHandler.removeCallbacks(this);
2150                int retCode = -1;
2151                synchronized (mInstallLock) {
2152                    retCode = mInstaller.freeCache(freeStorageSize);
2153                    if (retCode < 0) {
2154                        Slog.w(TAG, "Couldn't clear application caches");
2155                    }
2156                }
2157                if(pi != null) {
2158                    try {
2159                        // Callback via pending intent
2160                        int code = (retCode >= 0) ? 1 : 0;
2161                        pi.sendIntent(null, code, null,
2162                                null, null);
2163                    } catch (SendIntentException e1) {
2164                        Slog.i(TAG, "Failed to send pending intent");
2165                    }
2166                }
2167            }
2168        });
2169    }
2170
2171    @Override
2172    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2173        if (!sUserManager.exists(userId)) return null;
2174        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177
2178            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2179            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2180                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2181                if (ps == null) return null;
2182                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2183                        userId);
2184            }
2185            if (mResolveComponentName.equals(component)) {
2186                return mResolveActivity;
2187            }
2188        }
2189        return null;
2190    }
2191
2192    @Override
2193    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2194            String resolvedType) {
2195        synchronized (mPackages) {
2196            PackageParser.Activity a = mActivities.mActivities.get(component);
2197            if (a == null) {
2198                return false;
2199            }
2200            for (int i=0; i<a.intents.size(); i++) {
2201                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2202                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2203                    return true;
2204                }
2205            }
2206            return false;
2207        }
2208    }
2209
2210    @Override
2211    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2212        if (!sUserManager.exists(userId)) return null;
2213        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2214        synchronized (mPackages) {
2215            PackageParser.Activity a = mReceivers.mActivities.get(component);
2216            if (DEBUG_PACKAGE_INFO) Log.v(
2217                TAG, "getReceiverInfo " + component + ": " + a);
2218            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2219                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2220                if (ps == null) return null;
2221                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2222                        userId);
2223            }
2224        }
2225        return null;
2226    }
2227
2228    @Override
2229    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2232        synchronized (mPackages) {
2233            PackageParser.Service s = mServices.mServices.get(component);
2234            if (DEBUG_PACKAGE_INFO) Log.v(
2235                TAG, "getServiceInfo " + component + ": " + s);
2236            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2237                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2238                if (ps == null) return null;
2239                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2240                        userId);
2241            }
2242        }
2243        return null;
2244    }
2245
2246    @Override
2247    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2248        if (!sUserManager.exists(userId)) return null;
2249        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2250        synchronized (mPackages) {
2251            PackageParser.Provider p = mProviders.mProviders.get(component);
2252            if (DEBUG_PACKAGE_INFO) Log.v(
2253                TAG, "getProviderInfo " + component + ": " + p);
2254            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2255                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2256                if (ps == null) return null;
2257                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2258                        userId);
2259            }
2260        }
2261        return null;
2262    }
2263
2264    public String[] getSystemSharedLibraryNames() {
2265        Set<String> libSet;
2266        synchronized (mPackages) {
2267            libSet = mSharedLibraries.keySet();
2268            int size = libSet.size();
2269            if (size > 0) {
2270                String[] libs = new String[size];
2271                libSet.toArray(libs);
2272                return libs;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    public FeatureInfo[] getSystemAvailableFeatures() {
2279        Collection<FeatureInfo> featSet;
2280        synchronized (mPackages) {
2281            featSet = mAvailableFeatures.values();
2282            int size = featSet.size();
2283            if (size > 0) {
2284                FeatureInfo[] features = new FeatureInfo[size+1];
2285                featSet.toArray(features);
2286                FeatureInfo fi = new FeatureInfo();
2287                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2288                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2289                features[size] = fi;
2290                return features;
2291            }
2292        }
2293        return null;
2294    }
2295
2296    public boolean hasSystemFeature(String name) {
2297        synchronized (mPackages) {
2298            return mAvailableFeatures.containsKey(name);
2299        }
2300    }
2301
2302    private void checkValidCaller(int uid, int userId) {
2303        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2304            return;
2305
2306        throw new SecurityException("Caller uid=" + uid
2307                + " is not privileged to communicate with user=" + userId);
2308    }
2309
2310    public int checkPermission(String permName, String pkgName) {
2311        synchronized (mPackages) {
2312            PackageParser.Package p = mPackages.get(pkgName);
2313            if (p != null && p.mExtras != null) {
2314                PackageSetting ps = (PackageSetting)p.mExtras;
2315                if (ps.sharedUser != null) {
2316                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2317                        return PackageManager.PERMISSION_GRANTED;
2318                    }
2319                } else if (ps.grantedPermissions.contains(permName)) {
2320                    return PackageManager.PERMISSION_GRANTED;
2321                }
2322            }
2323        }
2324        return PackageManager.PERMISSION_DENIED;
2325    }
2326
2327    public int checkUidPermission(String permName, int uid) {
2328        synchronized (mPackages) {
2329            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2330            if (obj != null) {
2331                GrantedPermissions gp = (GrantedPermissions)obj;
2332                if (gp.grantedPermissions.contains(permName)) {
2333                    return PackageManager.PERMISSION_GRANTED;
2334                }
2335            } else {
2336                HashSet<String> perms = mSystemPermissions.get(uid);
2337                if (perms != null && perms.contains(permName)) {
2338                    return PackageManager.PERMISSION_GRANTED;
2339                }
2340            }
2341        }
2342        return PackageManager.PERMISSION_DENIED;
2343    }
2344
2345    /**
2346     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2347     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2348     * @param message the message to log on security exception
2349     * @return
2350     */
2351    private void enforceCrossUserPermission(int callingUid, int userId,
2352            boolean requireFullPermission, String message) {
2353        if (userId < 0) {
2354            throw new IllegalArgumentException("Invalid userId " + userId);
2355        }
2356        if (userId == UserHandle.getUserId(callingUid)) return;
2357        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2358            if (requireFullPermission) {
2359                mContext.enforceCallingOrSelfPermission(
2360                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2361            } else {
2362                try {
2363                    mContext.enforceCallingOrSelfPermission(
2364                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2365                } catch (SecurityException se) {
2366                    mContext.enforceCallingOrSelfPermission(
2367                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2368                }
2369            }
2370        }
2371    }
2372
2373    private BasePermission findPermissionTreeLP(String permName) {
2374        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2375            if (permName.startsWith(bp.name) &&
2376                    permName.length() > bp.name.length() &&
2377                    permName.charAt(bp.name.length()) == '.') {
2378                return bp;
2379            }
2380        }
2381        return null;
2382    }
2383
2384    private BasePermission checkPermissionTreeLP(String permName) {
2385        if (permName != null) {
2386            BasePermission bp = findPermissionTreeLP(permName);
2387            if (bp != null) {
2388                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2389                    return bp;
2390                }
2391                throw new SecurityException("Calling uid "
2392                        + Binder.getCallingUid()
2393                        + " is not allowed to add to permission tree "
2394                        + bp.name + " owned by uid " + bp.uid);
2395            }
2396        }
2397        throw new SecurityException("No permission tree found for " + permName);
2398    }
2399
2400    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2401        if (s1 == null) {
2402            return s2 == null;
2403        }
2404        if (s2 == null) {
2405            return false;
2406        }
2407        if (s1.getClass() != s2.getClass()) {
2408            return false;
2409        }
2410        return s1.equals(s2);
2411    }
2412
2413    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2414        if (pi1.icon != pi2.icon) return false;
2415        if (pi1.logo != pi2.logo) return false;
2416        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2417        if (!compareStrings(pi1.name, pi2.name)) return false;
2418        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2419        // We'll take care of setting this one.
2420        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2421        // These are not currently stored in settings.
2422        //if (!compareStrings(pi1.group, pi2.group)) return false;
2423        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2424        //if (pi1.labelRes != pi2.labelRes) return false;
2425        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2426        return true;
2427    }
2428
2429    int permissionInfoFootprint(PermissionInfo info) {
2430        int size = info.name.length();
2431        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2432        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2433        return size;
2434    }
2435
2436    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2437        int size = 0;
2438        for (BasePermission perm : mSettings.mPermissions.values()) {
2439            if (perm.uid == tree.uid) {
2440                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2441            }
2442        }
2443        return size;
2444    }
2445
2446    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2447        // We calculate the max size of permissions defined by this uid and throw
2448        // if that plus the size of 'info' would exceed our stated maximum.
2449        if (tree.uid != Process.SYSTEM_UID) {
2450            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2451            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2452                throw new SecurityException("Permission tree size cap exceeded");
2453            }
2454        }
2455    }
2456
2457    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2458        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2459            throw new SecurityException("Label must be specified in permission");
2460        }
2461        BasePermission tree = checkPermissionTreeLP(info.name);
2462        BasePermission bp = mSettings.mPermissions.get(info.name);
2463        boolean added = bp == null;
2464        boolean changed = true;
2465        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2466        if (added) {
2467            enforcePermissionCapLocked(info, tree);
2468            bp = new BasePermission(info.name, tree.sourcePackage,
2469                    BasePermission.TYPE_DYNAMIC);
2470        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2471            throw new SecurityException(
2472                    "Not allowed to modify non-dynamic permission "
2473                    + info.name);
2474        } else {
2475            if (bp.protectionLevel == fixedLevel
2476                    && bp.perm.owner.equals(tree.perm.owner)
2477                    && bp.uid == tree.uid
2478                    && comparePermissionInfos(bp.perm.info, info)) {
2479                changed = false;
2480            }
2481        }
2482        bp.protectionLevel = fixedLevel;
2483        info = new PermissionInfo(info);
2484        info.protectionLevel = fixedLevel;
2485        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2486        bp.perm.info.packageName = tree.perm.info.packageName;
2487        bp.uid = tree.uid;
2488        if (added) {
2489            mSettings.mPermissions.put(info.name, bp);
2490        }
2491        if (changed) {
2492            if (!async) {
2493                mSettings.writeLPr();
2494            } else {
2495                scheduleWriteSettingsLocked();
2496            }
2497        }
2498        return added;
2499    }
2500
2501    public boolean addPermission(PermissionInfo info) {
2502        synchronized (mPackages) {
2503            return addPermissionLocked(info, false);
2504        }
2505    }
2506
2507    public boolean addPermissionAsync(PermissionInfo info) {
2508        synchronized (mPackages) {
2509            return addPermissionLocked(info, true);
2510        }
2511    }
2512
2513    public void removePermission(String name) {
2514        synchronized (mPackages) {
2515            checkPermissionTreeLP(name);
2516            BasePermission bp = mSettings.mPermissions.get(name);
2517            if (bp != null) {
2518                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2519                    throw new SecurityException(
2520                            "Not allowed to modify non-dynamic permission "
2521                            + name);
2522                }
2523                mSettings.mPermissions.remove(name);
2524                mSettings.writeLPr();
2525            }
2526        }
2527    }
2528
2529    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2530        int index = pkg.requestedPermissions.indexOf(bp.name);
2531        if (index == -1) {
2532            throw new SecurityException("Package " + pkg.packageName
2533                    + " has not requested permission " + bp.name);
2534        }
2535        boolean isNormal =
2536                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2537                        == PermissionInfo.PROTECTION_NORMAL);
2538        boolean isDangerous =
2539                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2540                        == PermissionInfo.PROTECTION_DANGEROUS);
2541        boolean isDevelopment =
2542                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2543
2544        if (!isNormal && !isDangerous && !isDevelopment) {
2545            throw new SecurityException("Permission " + bp.name
2546                    + " is not a changeable permission type");
2547        }
2548
2549        if (isNormal || isDangerous) {
2550            if (pkg.requestedPermissionsRequired.get(index)) {
2551                throw new SecurityException("Can't change " + bp.name
2552                        + ". It is required by the application");
2553            }
2554        }
2555    }
2556
2557    public void grantPermission(String packageName, String permissionName) {
2558        mContext.enforceCallingOrSelfPermission(
2559                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2560        synchronized (mPackages) {
2561            final PackageParser.Package pkg = mPackages.get(packageName);
2562            if (pkg == null) {
2563                throw new IllegalArgumentException("Unknown package: " + packageName);
2564            }
2565            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2566            if (bp == null) {
2567                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2568            }
2569
2570            checkGrantRevokePermissions(pkg, bp);
2571
2572            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2573            if (ps == null) {
2574                return;
2575            }
2576            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2577            if (gp.grantedPermissions.add(permissionName)) {
2578                if (ps.haveGids) {
2579                    gp.gids = appendInts(gp.gids, bp.gids);
2580                }
2581                mSettings.writeLPr();
2582            }
2583        }
2584    }
2585
2586    public void revokePermission(String packageName, String permissionName) {
2587        int changedAppId = -1;
2588
2589        synchronized (mPackages) {
2590            final PackageParser.Package pkg = mPackages.get(packageName);
2591            if (pkg == null) {
2592                throw new IllegalArgumentException("Unknown package: " + packageName);
2593            }
2594            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2595                mContext.enforceCallingOrSelfPermission(
2596                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2597            }
2598            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2599            if (bp == null) {
2600                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2601            }
2602
2603            checkGrantRevokePermissions(pkg, bp);
2604
2605            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2606            if (ps == null) {
2607                return;
2608            }
2609            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2610            if (gp.grantedPermissions.remove(permissionName)) {
2611                gp.grantedPermissions.remove(permissionName);
2612                if (ps.haveGids) {
2613                    gp.gids = removeInts(gp.gids, bp.gids);
2614                }
2615                mSettings.writeLPr();
2616                changedAppId = ps.appId;
2617            }
2618        }
2619
2620        if (changedAppId >= 0) {
2621            // We changed the perm on someone, kill its processes.
2622            IActivityManager am = ActivityManagerNative.getDefault();
2623            if (am != null) {
2624                final int callingUserId = UserHandle.getCallingUserId();
2625                final long ident = Binder.clearCallingIdentity();
2626                try {
2627                    //XXX we should only revoke for the calling user's app permissions,
2628                    // but for now we impact all users.
2629                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2630                    //        "revoke " + permissionName);
2631                    int[] users = sUserManager.getUserIds();
2632                    for (int user : users) {
2633                        am.killUid(UserHandle.getUid(user, changedAppId),
2634                                "revoke " + permissionName);
2635                    }
2636                } catch (RemoteException e) {
2637                } finally {
2638                    Binder.restoreCallingIdentity(ident);
2639                }
2640            }
2641        }
2642    }
2643
2644    public boolean isProtectedBroadcast(String actionName) {
2645        synchronized (mPackages) {
2646            return mProtectedBroadcasts.contains(actionName);
2647        }
2648    }
2649
2650    public int checkSignatures(String pkg1, String pkg2) {
2651        synchronized (mPackages) {
2652            final PackageParser.Package p1 = mPackages.get(pkg1);
2653            final PackageParser.Package p2 = mPackages.get(pkg2);
2654            if (p1 == null || p1.mExtras == null
2655                    || p2 == null || p2.mExtras == null) {
2656                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2657            }
2658            return compareSignatures(p1.mSignatures, p2.mSignatures);
2659        }
2660    }
2661
2662    public int checkUidSignatures(int uid1, int uid2) {
2663        // Map to base uids.
2664        uid1 = UserHandle.getAppId(uid1);
2665        uid2 = UserHandle.getAppId(uid2);
2666        // reader
2667        synchronized (mPackages) {
2668            Signature[] s1;
2669            Signature[] s2;
2670            Object obj = mSettings.getUserIdLPr(uid1);
2671            if (obj != null) {
2672                if (obj instanceof SharedUserSetting) {
2673                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2674                } else if (obj instanceof PackageSetting) {
2675                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2676                } else {
2677                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2678                }
2679            } else {
2680                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2681            }
2682            obj = mSettings.getUserIdLPr(uid2);
2683            if (obj != null) {
2684                if (obj instanceof SharedUserSetting) {
2685                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2686                } else if (obj instanceof PackageSetting) {
2687                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2688                } else {
2689                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2690                }
2691            } else {
2692                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2693            }
2694            return compareSignatures(s1, s2);
2695        }
2696    }
2697
2698    /**
2699     * Compares two sets of signatures. Returns:
2700     * <br />
2701     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2702     * <br />
2703     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2704     * <br />
2705     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2706     * <br />
2707     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2708     * <br />
2709     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2710     */
2711    static int compareSignatures(Signature[] s1, Signature[] s2) {
2712        if (s1 == null) {
2713            return s2 == null
2714                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2715                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2716        }
2717
2718        if (s2 == null) {
2719            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2720        }
2721
2722        if (s1.length != s2.length) {
2723            return PackageManager.SIGNATURE_NO_MATCH;
2724        }
2725
2726        // Since both signature sets are of size 1, we can compare without HashSets.
2727        if (s1.length == 1) {
2728            return s1[0].equals(s2[0]) ?
2729                    PackageManager.SIGNATURE_MATCH :
2730                    PackageManager.SIGNATURE_NO_MATCH;
2731        }
2732
2733        HashSet<Signature> set1 = new HashSet<Signature>();
2734        for (Signature sig : s1) {
2735            set1.add(sig);
2736        }
2737        HashSet<Signature> set2 = new HashSet<Signature>();
2738        for (Signature sig : s2) {
2739            set2.add(sig);
2740        }
2741        // Make sure s2 contains all signatures in s1.
2742        if (set1.equals(set2)) {
2743            return PackageManager.SIGNATURE_MATCH;
2744        }
2745        return PackageManager.SIGNATURE_NO_MATCH;
2746    }
2747
2748    /**
2749     * If the database version for this type of package (internal storage or
2750     * external storage) is less than the version where package signatures
2751     * were updated, return true.
2752     */
2753    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2754        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2755                DatabaseVersion.SIGNATURE_END_ENTITY))
2756                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2757                        DatabaseVersion.SIGNATURE_END_ENTITY));
2758    }
2759
2760    /**
2761     * Used for backward compatibility to make sure any packages with
2762     * certificate chains get upgraded to the new style. {@code existingSigs}
2763     * will be in the old format (since they were stored on disk from before the
2764     * system upgrade) and {@code scannedSigs} will be in the newer format.
2765     */
2766    private int compareSignaturesCompat(PackageSignatures existingSigs,
2767            PackageParser.Package scannedPkg) {
2768        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2769            return PackageManager.SIGNATURE_NO_MATCH;
2770        }
2771
2772        HashSet<Signature> existingSet = new HashSet<Signature>();
2773        for (Signature sig : existingSigs.mSignatures) {
2774            existingSet.add(sig);
2775        }
2776        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2777        for (Signature sig : scannedPkg.mSignatures) {
2778            try {
2779                Signature[] chainSignatures = sig.getChainSignatures();
2780                for (Signature chainSig : chainSignatures) {
2781                    scannedCompatSet.add(chainSig);
2782                }
2783            } catch (CertificateEncodingException e) {
2784                scannedCompatSet.add(sig);
2785            }
2786        }
2787        /*
2788         * Make sure the expanded scanned set contains all signatures in the
2789         * existing one.
2790         */
2791        if (scannedCompatSet.equals(existingSet)) {
2792            // Migrate the old signatures to the new scheme.
2793            existingSigs.assignSignatures(scannedPkg.mSignatures);
2794            // The new KeySets will be re-added later in the scanning process.
2795            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2796            return PackageManager.SIGNATURE_MATCH;
2797        }
2798        return PackageManager.SIGNATURE_NO_MATCH;
2799    }
2800
2801    public String[] getPackagesForUid(int uid) {
2802        uid = UserHandle.getAppId(uid);
2803        // reader
2804        synchronized (mPackages) {
2805            Object obj = mSettings.getUserIdLPr(uid);
2806            if (obj instanceof SharedUserSetting) {
2807                final SharedUserSetting sus = (SharedUserSetting) obj;
2808                final int N = sus.packages.size();
2809                final String[] res = new String[N];
2810                final Iterator<PackageSetting> it = sus.packages.iterator();
2811                int i = 0;
2812                while (it.hasNext()) {
2813                    res[i++] = it.next().name;
2814                }
2815                return res;
2816            } else if (obj instanceof PackageSetting) {
2817                final PackageSetting ps = (PackageSetting) obj;
2818                return new String[] { ps.name };
2819            }
2820        }
2821        return null;
2822    }
2823
2824    public String getNameForUid(int uid) {
2825        // reader
2826        synchronized (mPackages) {
2827            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2828            if (obj instanceof SharedUserSetting) {
2829                final SharedUserSetting sus = (SharedUserSetting) obj;
2830                return sus.name + ":" + sus.userId;
2831            } else if (obj instanceof PackageSetting) {
2832                final PackageSetting ps = (PackageSetting) obj;
2833                return ps.name;
2834            }
2835        }
2836        return null;
2837    }
2838
2839    public int getUidForSharedUser(String sharedUserName) {
2840        if(sharedUserName == null) {
2841            return -1;
2842        }
2843        // reader
2844        synchronized (mPackages) {
2845            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2846            if (suid == null) {
2847                return -1;
2848            }
2849            return suid.userId;
2850        }
2851    }
2852
2853    public int getFlagsForUid(int uid) {
2854        synchronized (mPackages) {
2855            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2856            if (obj instanceof SharedUserSetting) {
2857                final SharedUserSetting sus = (SharedUserSetting) obj;
2858                return sus.pkgFlags;
2859            } else if (obj instanceof PackageSetting) {
2860                final PackageSetting ps = (PackageSetting) obj;
2861                return ps.pkgFlags;
2862            }
2863        }
2864        return 0;
2865    }
2866
2867    @Override
2868    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2869            int flags, int userId) {
2870        if (!sUserManager.exists(userId)) return null;
2871        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2872        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2873        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2874    }
2875
2876    @Override
2877    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2878            IntentFilter filter, int match, ComponentName activity) {
2879        final int userId = UserHandle.getCallingUserId();
2880        if (DEBUG_PREFERRED) {
2881            Log.v(TAG, "setLastChosenActivity intent=" + intent
2882                + " resolvedType=" + resolvedType
2883                + " flags=" + flags
2884                + " filter=" + filter
2885                + " match=" + match
2886                + " activity=" + activity);
2887            filter.dump(new PrintStreamPrinter(System.out), "    ");
2888        }
2889        intent.setComponent(null);
2890        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2891        // Find any earlier preferred or last chosen entries and nuke them
2892        findPreferredActivity(intent, resolvedType,
2893                flags, query, 0, false, true, false, userId);
2894        // Add the new activity as the last chosen for this filter
2895        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2896    }
2897
2898    @Override
2899    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2900        final int userId = UserHandle.getCallingUserId();
2901        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2902        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2903        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2904                false, false, false, userId);
2905    }
2906
2907    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2908            int flags, List<ResolveInfo> query, int userId) {
2909        if (query != null) {
2910            final int N = query.size();
2911            if (N == 1) {
2912                return query.get(0);
2913            } else if (N > 1) {
2914                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2915                // If there is more than one activity with the same priority,
2916                // then let the user decide between them.
2917                ResolveInfo r0 = query.get(0);
2918                ResolveInfo r1 = query.get(1);
2919                if (DEBUG_INTENT_MATCHING || debug) {
2920                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2921                            + r1.activityInfo.name + "=" + r1.priority);
2922                }
2923                // If the first activity has a higher priority, or a different
2924                // default, then it is always desireable to pick it.
2925                if (r0.priority != r1.priority
2926                        || r0.preferredOrder != r1.preferredOrder
2927                        || r0.isDefault != r1.isDefault) {
2928                    return query.get(0);
2929                }
2930                // If we have saved a preference for a preferred activity for
2931                // this Intent, use that.
2932                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2933                        flags, query, r0.priority, true, false, debug, userId);
2934                if (ri != null) {
2935                    return ri;
2936                }
2937                if (userId != 0) {
2938                    ri = new ResolveInfo(mResolveInfo);
2939                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2940                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2941                            ri.activityInfo.applicationInfo);
2942                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2943                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2944                    return ri;
2945                }
2946                return mResolveInfo;
2947            }
2948        }
2949        return null;
2950    }
2951
2952    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2953            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2954        final int N = query.size();
2955        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2956                .get(userId);
2957        // Get the list of persistent preferred activities that handle the intent
2958        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2959        List<PersistentPreferredActivity> pprefs = ppir != null
2960                ? ppir.queryIntent(intent, resolvedType,
2961                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2962                : null;
2963        if (pprefs != null && pprefs.size() > 0) {
2964            final int M = pprefs.size();
2965            for (int i=0; i<M; i++) {
2966                final PersistentPreferredActivity ppa = pprefs.get(i);
2967                if (DEBUG_PREFERRED || debug) {
2968                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2969                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2970                            + "\n  component=" + ppa.mComponent);
2971                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2972                }
2973                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2974                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2975                if (DEBUG_PREFERRED || debug) {
2976                    Slog.v(TAG, "Found persistent preferred activity:");
2977                    if (ai != null) {
2978                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2979                    } else {
2980                        Slog.v(TAG, "  null");
2981                    }
2982                }
2983                if (ai == null) {
2984                    // This previously registered persistent preferred activity
2985                    // component is no longer known. Ignore it and do NOT remove it.
2986                    continue;
2987                }
2988                for (int j=0; j<N; j++) {
2989                    final ResolveInfo ri = query.get(j);
2990                    if (!ri.activityInfo.applicationInfo.packageName
2991                            .equals(ai.applicationInfo.packageName)) {
2992                        continue;
2993                    }
2994                    if (!ri.activityInfo.name.equals(ai.name)) {
2995                        continue;
2996                    }
2997                    //  Found a persistent preference that can handle the intent.
2998                    if (DEBUG_PREFERRED || debug) {
2999                        Slog.v(TAG, "Returning persistent preferred activity: " +
3000                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3001                    }
3002                    return ri;
3003                }
3004            }
3005        }
3006        return null;
3007    }
3008
3009    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3010            List<ResolveInfo> query, int priority, boolean always,
3011            boolean removeMatches, boolean debug, int userId) {
3012        if (!sUserManager.exists(userId)) return null;
3013        // writer
3014        synchronized (mPackages) {
3015            if (intent.getSelector() != null) {
3016                intent = intent.getSelector();
3017            }
3018            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3019
3020            // Try to find a matching persistent preferred activity.
3021            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3022                    debug, userId);
3023
3024            // If a persistent preferred activity matched, use it.
3025            if (pri != null) {
3026                return pri;
3027            }
3028
3029            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3030            // Get the list of preferred activities that handle the intent
3031            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3032            List<PreferredActivity> prefs = pir != null
3033                    ? pir.queryIntent(intent, resolvedType,
3034                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3035                    : null;
3036            if (prefs != null && prefs.size() > 0) {
3037                // First figure out how good the original match set is.
3038                // We will only allow preferred activities that came
3039                // from the same match quality.
3040                int match = 0;
3041
3042                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3043
3044                final int N = query.size();
3045                for (int j=0; j<N; j++) {
3046                    final ResolveInfo ri = query.get(j);
3047                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3048                            + ": 0x" + Integer.toHexString(match));
3049                    if (ri.match > match) {
3050                        match = ri.match;
3051                    }
3052                }
3053
3054                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3055                        + Integer.toHexString(match));
3056
3057                match &= IntentFilter.MATCH_CATEGORY_MASK;
3058                final int M = prefs.size();
3059                for (int i=0; i<M; i++) {
3060                    final PreferredActivity pa = prefs.get(i);
3061                    if (DEBUG_PREFERRED || debug) {
3062                        Slog.v(TAG, "Checking PreferredActivity ds="
3063                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3064                                + "\n  component=" + pa.mPref.mComponent);
3065                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3066                    }
3067                    if (pa.mPref.mMatch != match) {
3068                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3069                                + Integer.toHexString(pa.mPref.mMatch));
3070                        continue;
3071                    }
3072                    // If it's not an "always" type preferred activity and that's what we're
3073                    // looking for, skip it.
3074                    if (always && !pa.mPref.mAlways) {
3075                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3076                        continue;
3077                    }
3078                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3079                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3080                    if (DEBUG_PREFERRED || debug) {
3081                        Slog.v(TAG, "Found preferred activity:");
3082                        if (ai != null) {
3083                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3084                        } else {
3085                            Slog.v(TAG, "  null");
3086                        }
3087                    }
3088                    if (ai == null) {
3089                        // This previously registered preferred activity
3090                        // component is no longer known.  Most likely an update
3091                        // to the app was installed and in the new version this
3092                        // component no longer exists.  Clean it up by removing
3093                        // it from the preferred activities list, and skip it.
3094                        Slog.w(TAG, "Removing dangling preferred activity: "
3095                                + pa.mPref.mComponent);
3096                        pir.removeFilter(pa);
3097                        continue;
3098                    }
3099                    for (int j=0; j<N; j++) {
3100                        final ResolveInfo ri = query.get(j);
3101                        if (!ri.activityInfo.applicationInfo.packageName
3102                                .equals(ai.applicationInfo.packageName)) {
3103                            continue;
3104                        }
3105                        if (!ri.activityInfo.name.equals(ai.name)) {
3106                            continue;
3107                        }
3108
3109                        if (removeMatches) {
3110                            pir.removeFilter(pa);
3111                            if (DEBUG_PREFERRED) {
3112                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3113                            }
3114                            break;
3115                        }
3116
3117                        // Okay we found a previously set preferred or last chosen app.
3118                        // If the result set is different from when this
3119                        // was created, we need to clear it and re-ask the
3120                        // user their preference, if we're looking for an "always" type entry.
3121                        if (always && !pa.mPref.sameSet(query, priority)) {
3122                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3123                                    + intent + " type " + resolvedType);
3124                            if (DEBUG_PREFERRED) {
3125                                Slog.v(TAG, "Removing preferred activity since set changed "
3126                                        + pa.mPref.mComponent);
3127                            }
3128                            pir.removeFilter(pa);
3129                            // Re-add the filter as a "last chosen" entry (!always)
3130                            PreferredActivity lastChosen = new PreferredActivity(
3131                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3132                            pir.addFilter(lastChosen);
3133                            mSettings.writePackageRestrictionsLPr(userId);
3134                            return null;
3135                        }
3136
3137                        // Yay! Either the set matched or we're looking for the last chosen
3138                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3139                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3140                        mSettings.writePackageRestrictionsLPr(userId);
3141                        return ri;
3142                    }
3143                }
3144            }
3145            mSettings.writePackageRestrictionsLPr(userId);
3146        }
3147        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3148        return null;
3149    }
3150
3151    @Override
3152    public List<ResolveInfo> queryIntentActivities(Intent intent,
3153            String resolvedType, int flags, int userId) {
3154        if (!sUserManager.exists(userId)) return Collections.emptyList();
3155        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3156        ComponentName comp = intent.getComponent();
3157        if (comp == null) {
3158            if (intent.getSelector() != null) {
3159                intent = intent.getSelector();
3160                comp = intent.getComponent();
3161            }
3162        }
3163
3164        if (comp != null) {
3165            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3166            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3167            if (ai != null) {
3168                final ResolveInfo ri = new ResolveInfo();
3169                ri.activityInfo = ai;
3170                list.add(ri);
3171            }
3172            return list;
3173        }
3174
3175        // reader
3176        synchronized (mPackages) {
3177            final String pkgName = intent.getPackage();
3178            if (pkgName == null) {
3179                return mActivities.queryIntent(intent, resolvedType, flags, userId);
3180            }
3181            final PackageParser.Package pkg = mPackages.get(pkgName);
3182            if (pkg != null) {
3183                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3184                        pkg.activities, userId);
3185            }
3186            return new ArrayList<ResolveInfo>();
3187        }
3188    }
3189
3190    @Override
3191    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3192            Intent[] specifics, String[] specificTypes, Intent intent,
3193            String resolvedType, int flags, int userId) {
3194        if (!sUserManager.exists(userId)) return Collections.emptyList();
3195        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3196                "query intent activity options");
3197        final String resultsAction = intent.getAction();
3198
3199        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3200                | PackageManager.GET_RESOLVED_FILTER, userId);
3201
3202        if (DEBUG_INTENT_MATCHING) {
3203            Log.v(TAG, "Query " + intent + ": " + results);
3204        }
3205
3206        int specificsPos = 0;
3207        int N;
3208
3209        // todo: note that the algorithm used here is O(N^2).  This
3210        // isn't a problem in our current environment, but if we start running
3211        // into situations where we have more than 5 or 10 matches then this
3212        // should probably be changed to something smarter...
3213
3214        // First we go through and resolve each of the specific items
3215        // that were supplied, taking care of removing any corresponding
3216        // duplicate items in the generic resolve list.
3217        if (specifics != null) {
3218            for (int i=0; i<specifics.length; i++) {
3219                final Intent sintent = specifics[i];
3220                if (sintent == null) {
3221                    continue;
3222                }
3223
3224                if (DEBUG_INTENT_MATCHING) {
3225                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3226                }
3227
3228                String action = sintent.getAction();
3229                if (resultsAction != null && resultsAction.equals(action)) {
3230                    // If this action was explicitly requested, then don't
3231                    // remove things that have it.
3232                    action = null;
3233                }
3234
3235                ResolveInfo ri = null;
3236                ActivityInfo ai = null;
3237
3238                ComponentName comp = sintent.getComponent();
3239                if (comp == null) {
3240                    ri = resolveIntent(
3241                        sintent,
3242                        specificTypes != null ? specificTypes[i] : null,
3243                            flags, userId);
3244                    if (ri == null) {
3245                        continue;
3246                    }
3247                    if (ri == mResolveInfo) {
3248                        // ACK!  Must do something better with this.
3249                    }
3250                    ai = ri.activityInfo;
3251                    comp = new ComponentName(ai.applicationInfo.packageName,
3252                            ai.name);
3253                } else {
3254                    ai = getActivityInfo(comp, flags, userId);
3255                    if (ai == null) {
3256                        continue;
3257                    }
3258                }
3259
3260                // Look for any generic query activities that are duplicates
3261                // of this specific one, and remove them from the results.
3262                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3263                N = results.size();
3264                int j;
3265                for (j=specificsPos; j<N; j++) {
3266                    ResolveInfo sri = results.get(j);
3267                    if ((sri.activityInfo.name.equals(comp.getClassName())
3268                            && sri.activityInfo.applicationInfo.packageName.equals(
3269                                    comp.getPackageName()))
3270                        || (action != null && sri.filter.matchAction(action))) {
3271                        results.remove(j);
3272                        if (DEBUG_INTENT_MATCHING) Log.v(
3273                            TAG, "Removing duplicate item from " + j
3274                            + " due to specific " + specificsPos);
3275                        if (ri == null) {
3276                            ri = sri;
3277                        }
3278                        j--;
3279                        N--;
3280                    }
3281                }
3282
3283                // Add this specific item to its proper place.
3284                if (ri == null) {
3285                    ri = new ResolveInfo();
3286                    ri.activityInfo = ai;
3287                }
3288                results.add(specificsPos, ri);
3289                ri.specificIndex = i;
3290                specificsPos++;
3291            }
3292        }
3293
3294        // Now we go through the remaining generic results and remove any
3295        // duplicate actions that are found here.
3296        N = results.size();
3297        for (int i=specificsPos; i<N-1; i++) {
3298            final ResolveInfo rii = results.get(i);
3299            if (rii.filter == null) {
3300                continue;
3301            }
3302
3303            // Iterate over all of the actions of this result's intent
3304            // filter...  typically this should be just one.
3305            final Iterator<String> it = rii.filter.actionsIterator();
3306            if (it == null) {
3307                continue;
3308            }
3309            while (it.hasNext()) {
3310                final String action = it.next();
3311                if (resultsAction != null && resultsAction.equals(action)) {
3312                    // If this action was explicitly requested, then don't
3313                    // remove things that have it.
3314                    continue;
3315                }
3316                for (int j=i+1; j<N; j++) {
3317                    final ResolveInfo rij = results.get(j);
3318                    if (rij.filter != null && rij.filter.hasAction(action)) {
3319                        results.remove(j);
3320                        if (DEBUG_INTENT_MATCHING) Log.v(
3321                            TAG, "Removing duplicate item from " + j
3322                            + " due to action " + action + " at " + i);
3323                        j--;
3324                        N--;
3325                    }
3326                }
3327            }
3328
3329            // If the caller didn't request filter information, drop it now
3330            // so we don't have to marshall/unmarshall it.
3331            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3332                rii.filter = null;
3333            }
3334        }
3335
3336        // Filter out the caller activity if so requested.
3337        if (caller != null) {
3338            N = results.size();
3339            for (int i=0; i<N; i++) {
3340                ActivityInfo ainfo = results.get(i).activityInfo;
3341                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3342                        && caller.getClassName().equals(ainfo.name)) {
3343                    results.remove(i);
3344                    break;
3345                }
3346            }
3347        }
3348
3349        // If the caller didn't request filter information,
3350        // drop them now so we don't have to
3351        // marshall/unmarshall it.
3352        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3353            N = results.size();
3354            for (int i=0; i<N; i++) {
3355                results.get(i).filter = null;
3356            }
3357        }
3358
3359        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3360        return results;
3361    }
3362
3363    @Override
3364    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3365            int userId) {
3366        if (!sUserManager.exists(userId)) return Collections.emptyList();
3367        ComponentName comp = intent.getComponent();
3368        if (comp == null) {
3369            if (intent.getSelector() != null) {
3370                intent = intent.getSelector();
3371                comp = intent.getComponent();
3372            }
3373        }
3374        if (comp != null) {
3375            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3376            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3377            if (ai != null) {
3378                ResolveInfo ri = new ResolveInfo();
3379                ri.activityInfo = ai;
3380                list.add(ri);
3381            }
3382            return list;
3383        }
3384
3385        // reader
3386        synchronized (mPackages) {
3387            String pkgName = intent.getPackage();
3388            if (pkgName == null) {
3389                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3390            }
3391            final PackageParser.Package pkg = mPackages.get(pkgName);
3392            if (pkg != null) {
3393                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3394                        userId);
3395            }
3396            return null;
3397        }
3398    }
3399
3400    @Override
3401    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3402        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3403        if (!sUserManager.exists(userId)) return null;
3404        if (query != null) {
3405            if (query.size() >= 1) {
3406                // If there is more than one service with the same priority,
3407                // just arbitrarily pick the first one.
3408                return query.get(0);
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3416            int userId) {
3417        if (!sUserManager.exists(userId)) return Collections.emptyList();
3418        ComponentName comp = intent.getComponent();
3419        if (comp == null) {
3420            if (intent.getSelector() != null) {
3421                intent = intent.getSelector();
3422                comp = intent.getComponent();
3423            }
3424        }
3425        if (comp != null) {
3426            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3427            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3428            if (si != null) {
3429                final ResolveInfo ri = new ResolveInfo();
3430                ri.serviceInfo = si;
3431                list.add(ri);
3432            }
3433            return list;
3434        }
3435
3436        // reader
3437        synchronized (mPackages) {
3438            String pkgName = intent.getPackage();
3439            if (pkgName == null) {
3440                return mServices.queryIntent(intent, resolvedType, flags, userId);
3441            }
3442            final PackageParser.Package pkg = mPackages.get(pkgName);
3443            if (pkg != null) {
3444                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3445                        userId);
3446            }
3447            return null;
3448        }
3449    }
3450
3451    @Override
3452    public List<ResolveInfo> queryIntentContentProviders(
3453            Intent intent, String resolvedType, int flags, int userId) {
3454        if (!sUserManager.exists(userId)) return Collections.emptyList();
3455        ComponentName comp = intent.getComponent();
3456        if (comp == null) {
3457            if (intent.getSelector() != null) {
3458                intent = intent.getSelector();
3459                comp = intent.getComponent();
3460            }
3461        }
3462        if (comp != null) {
3463            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3464            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3465            if (pi != null) {
3466                final ResolveInfo ri = new ResolveInfo();
3467                ri.providerInfo = pi;
3468                list.add(ri);
3469            }
3470            return list;
3471        }
3472
3473        // reader
3474        synchronized (mPackages) {
3475            String pkgName = intent.getPackage();
3476            if (pkgName == null) {
3477                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3478            }
3479            final PackageParser.Package pkg = mPackages.get(pkgName);
3480            if (pkg != null) {
3481                return mProviders.queryIntentForPackage(
3482                        intent, resolvedType, flags, pkg.providers, userId);
3483            }
3484            return null;
3485        }
3486    }
3487
3488    @Override
3489    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3490        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3491
3492        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3493
3494        // writer
3495        synchronized (mPackages) {
3496            ArrayList<PackageInfo> list;
3497            if (listUninstalled) {
3498                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3499                for (PackageSetting ps : mSettings.mPackages.values()) {
3500                    PackageInfo pi;
3501                    if (ps.pkg != null) {
3502                        pi = generatePackageInfo(ps.pkg, flags, userId);
3503                    } else {
3504                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3505                    }
3506                    if (pi != null) {
3507                        list.add(pi);
3508                    }
3509                }
3510            } else {
3511                list = new ArrayList<PackageInfo>(mPackages.size());
3512                for (PackageParser.Package p : mPackages.values()) {
3513                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3514                    if (pi != null) {
3515                        list.add(pi);
3516                    }
3517                }
3518            }
3519
3520            return new ParceledListSlice<PackageInfo>(list);
3521        }
3522    }
3523
3524    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3525            String[] permissions, boolean[] tmp, int flags, int userId) {
3526        int numMatch = 0;
3527        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3528        for (int i=0; i<permissions.length; i++) {
3529            if (gp.grantedPermissions.contains(permissions[i])) {
3530                tmp[i] = true;
3531                numMatch++;
3532            } else {
3533                tmp[i] = false;
3534            }
3535        }
3536        if (numMatch == 0) {
3537            return;
3538        }
3539        PackageInfo pi;
3540        if (ps.pkg != null) {
3541            pi = generatePackageInfo(ps.pkg, flags, userId);
3542        } else {
3543            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3544        }
3545        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3546            if (numMatch == permissions.length) {
3547                pi.requestedPermissions = permissions;
3548            } else {
3549                pi.requestedPermissions = new String[numMatch];
3550                numMatch = 0;
3551                for (int i=0; i<permissions.length; i++) {
3552                    if (tmp[i]) {
3553                        pi.requestedPermissions[numMatch] = permissions[i];
3554                        numMatch++;
3555                    }
3556                }
3557            }
3558        }
3559        list.add(pi);
3560    }
3561
3562    @Override
3563    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3564            String[] permissions, int flags, int userId) {
3565        if (!sUserManager.exists(userId)) return null;
3566        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3567
3568        // writer
3569        synchronized (mPackages) {
3570            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3571            boolean[] tmpBools = new boolean[permissions.length];
3572            if (listUninstalled) {
3573                for (PackageSetting ps : mSettings.mPackages.values()) {
3574                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3575                }
3576            } else {
3577                for (PackageParser.Package pkg : mPackages.values()) {
3578                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3579                    if (ps != null) {
3580                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3581                                userId);
3582                    }
3583                }
3584            }
3585
3586            return new ParceledListSlice<PackageInfo>(list);
3587        }
3588    }
3589
3590    @Override
3591    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return null;
3593        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3594
3595        // writer
3596        synchronized (mPackages) {
3597            ArrayList<ApplicationInfo> list;
3598            if (listUninstalled) {
3599                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3600                for (PackageSetting ps : mSettings.mPackages.values()) {
3601                    ApplicationInfo ai;
3602                    if (ps.pkg != null) {
3603                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3604                                ps.readUserState(userId), userId);
3605                    } else {
3606                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3607                    }
3608                    if (ai != null) {
3609                        list.add(ai);
3610                    }
3611                }
3612            } else {
3613                list = new ArrayList<ApplicationInfo>(mPackages.size());
3614                for (PackageParser.Package p : mPackages.values()) {
3615                    if (p.mExtras != null) {
3616                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3617                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3618                        if (ai != null) {
3619                            list.add(ai);
3620                        }
3621                    }
3622                }
3623            }
3624
3625            return new ParceledListSlice<ApplicationInfo>(list);
3626        }
3627    }
3628
3629    public List<ApplicationInfo> getPersistentApplications(int flags) {
3630        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3631
3632        // reader
3633        synchronized (mPackages) {
3634            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3635            final int userId = UserHandle.getCallingUserId();
3636            while (i.hasNext()) {
3637                final PackageParser.Package p = i.next();
3638                if (p.applicationInfo != null
3639                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3640                        && (!mSafeMode || isSystemApp(p))) {
3641                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3642                    if (ps != null) {
3643                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3644                                ps.readUserState(userId), userId);
3645                        if (ai != null) {
3646                            finalList.add(ai);
3647                        }
3648                    }
3649                }
3650            }
3651        }
3652
3653        return finalList;
3654    }
3655
3656    @Override
3657    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3658        if (!sUserManager.exists(userId)) return null;
3659        // reader
3660        synchronized (mPackages) {
3661            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3662            PackageSetting ps = provider != null
3663                    ? mSettings.mPackages.get(provider.owner.packageName)
3664                    : null;
3665            return ps != null
3666                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3667                    && (!mSafeMode || (provider.info.applicationInfo.flags
3668                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3669                    ? PackageParser.generateProviderInfo(provider, flags,
3670                            ps.readUserState(userId), userId)
3671                    : null;
3672        }
3673    }
3674
3675    /**
3676     * @deprecated
3677     */
3678    @Deprecated
3679    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3680        // reader
3681        synchronized (mPackages) {
3682            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3683                    .entrySet().iterator();
3684            final int userId = UserHandle.getCallingUserId();
3685            while (i.hasNext()) {
3686                Map.Entry<String, PackageParser.Provider> entry = i.next();
3687                PackageParser.Provider p = entry.getValue();
3688                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3689
3690                if (ps != null && p.syncable
3691                        && (!mSafeMode || (p.info.applicationInfo.flags
3692                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3693                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3694                            ps.readUserState(userId), userId);
3695                    if (info != null) {
3696                        outNames.add(entry.getKey());
3697                        outInfo.add(info);
3698                    }
3699                }
3700            }
3701        }
3702    }
3703
3704    public List<ProviderInfo> queryContentProviders(String processName,
3705            int uid, int flags) {
3706        ArrayList<ProviderInfo> finalList = null;
3707        // reader
3708        synchronized (mPackages) {
3709            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3710            final int userId = processName != null ?
3711                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3712            while (i.hasNext()) {
3713                final PackageParser.Provider p = i.next();
3714                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3715                if (ps != null && p.info.authority != null
3716                        && (processName == null
3717                                || (p.info.processName.equals(processName)
3718                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3719                        && mSettings.isEnabledLPr(p.info, flags, userId)
3720                        && (!mSafeMode
3721                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3722                    if (finalList == null) {
3723                        finalList = new ArrayList<ProviderInfo>(3);
3724                    }
3725                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3726                            ps.readUserState(userId), userId);
3727                    if (info != null) {
3728                        finalList.add(info);
3729                    }
3730                }
3731            }
3732        }
3733
3734        if (finalList != null) {
3735            Collections.sort(finalList, mProviderInitOrderSorter);
3736        }
3737
3738        return finalList;
3739    }
3740
3741    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3742            int flags) {
3743        // reader
3744        synchronized (mPackages) {
3745            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3746            return PackageParser.generateInstrumentationInfo(i, flags);
3747        }
3748    }
3749
3750    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3751            int flags) {
3752        ArrayList<InstrumentationInfo> finalList =
3753            new ArrayList<InstrumentationInfo>();
3754
3755        // reader
3756        synchronized (mPackages) {
3757            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3758            while (i.hasNext()) {
3759                final PackageParser.Instrumentation p = i.next();
3760                if (targetPackage == null
3761                        || targetPackage.equals(p.info.targetPackage)) {
3762                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3763                            flags);
3764                    if (ii != null) {
3765                        finalList.add(ii);
3766                    }
3767                }
3768            }
3769        }
3770
3771        return finalList;
3772    }
3773
3774    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3775        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3776        if (overlays == null) {
3777            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3778            return;
3779        }
3780        for (PackageParser.Package opkg : overlays.values()) {
3781            // Not much to do if idmap fails: we already logged the error
3782            // and we certainly don't want to abort installation of pkg simply
3783            // because an overlay didn't fit properly. For these reasons,
3784            // ignore the return value of createIdmapForPackagePairLI.
3785            createIdmapForPackagePairLI(pkg, opkg);
3786        }
3787    }
3788
3789    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3790            PackageParser.Package opkg) {
3791        if (!opkg.mTrustedOverlay) {
3792            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3793                    opkg.mScanPath + ": overlay not trusted");
3794            return false;
3795        }
3796        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3797        if (overlaySet == null) {
3798            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3799                    opkg.mScanPath + " but target package has no known overlays");
3800            return false;
3801        }
3802        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3803        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3804            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3805            return false;
3806        }
3807        PackageParser.Package[] overlayArray =
3808            overlaySet.values().toArray(new PackageParser.Package[0]);
3809        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3810            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3811                return p1.mOverlayPriority - p2.mOverlayPriority;
3812            }
3813        };
3814        Arrays.sort(overlayArray, cmp);
3815
3816        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3817        int i = 0;
3818        for (PackageParser.Package p : overlayArray) {
3819            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3820        }
3821        return true;
3822    }
3823
3824    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3825        String[] files = dir.list();
3826        if (files == null) {
3827            Log.d(TAG, "No files in app dir " + dir);
3828            return;
3829        }
3830
3831        if (DEBUG_PACKAGE_SCANNING) {
3832            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3833                    + " flags=0x" + Integer.toHexString(flags));
3834        }
3835
3836        int i;
3837        for (i=0; i<files.length; i++) {
3838            File file = new File(dir, files[i]);
3839            if (!isPackageFilename(files[i])) {
3840                // Ignore entries which are not apk's
3841                continue;
3842            }
3843            PackageParser.Package pkg = scanPackageLI(file,
3844                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3845            // Don't mess around with apps in system partition.
3846            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3847                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3848                // Delete the apk
3849                Slog.w(TAG, "Cleaning up failed install of " + file);
3850                file.delete();
3851            }
3852        }
3853    }
3854
3855    private static File getSettingsProblemFile() {
3856        File dataDir = Environment.getDataDirectory();
3857        File systemDir = new File(dataDir, "system");
3858        File fname = new File(systemDir, "uiderrors.txt");
3859        return fname;
3860    }
3861
3862    static void reportSettingsProblem(int priority, String msg) {
3863        try {
3864            File fname = getSettingsProblemFile();
3865            FileOutputStream out = new FileOutputStream(fname, true);
3866            PrintWriter pw = new FastPrintWriter(out);
3867            SimpleDateFormat formatter = new SimpleDateFormat();
3868            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3869            pw.println(dateString + ": " + msg);
3870            pw.close();
3871            FileUtils.setPermissions(
3872                    fname.toString(),
3873                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3874                    -1, -1);
3875        } catch (java.io.IOException e) {
3876        }
3877        Slog.println(priority, TAG, msg);
3878    }
3879
3880    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3881            PackageParser.Package pkg, File srcFile, int parseFlags) {
3882        if (ps != null
3883                && ps.codePath.equals(srcFile)
3884                && ps.timeStamp == srcFile.lastModified()
3885                && !isCompatSignatureUpdateNeeded(pkg)) {
3886            if (ps.signatures.mSignatures != null
3887                    && ps.signatures.mSignatures.length != 0) {
3888                // Optimization: reuse the existing cached certificates
3889                // if the package appears to be unchanged.
3890                pkg.mSignatures = ps.signatures.mSignatures;
3891                return true;
3892            }
3893
3894            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3895        } else {
3896            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3897        }
3898
3899        if (!pp.collectCertificates(pkg, parseFlags)) {
3900            mLastScanError = pp.getParseError();
3901            return false;
3902        }
3903        return true;
3904    }
3905
3906    /*
3907     *  Scan a package and return the newly parsed package.
3908     *  Returns null in case of errors and the error code is stored in mLastScanError
3909     */
3910    private PackageParser.Package scanPackageLI(File scanFile,
3911            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3912        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3913        String scanPath = scanFile.getPath();
3914        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3915        parseFlags |= mDefParseFlags;
3916        PackageParser pp = new PackageParser(scanPath);
3917        pp.setSeparateProcesses(mSeparateProcesses);
3918        pp.setOnlyCoreApps(mOnlyCore);
3919        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3920                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3921
3922        if (pkg == null) {
3923            mLastScanError = pp.getParseError();
3924            return null;
3925        }
3926
3927        PackageSetting ps = null;
3928        PackageSetting updatedPkg;
3929        // reader
3930        synchronized (mPackages) {
3931            // Look to see if we already know about this package.
3932            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3933            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3934                // This package has been renamed to its original name.  Let's
3935                // use that.
3936                ps = mSettings.peekPackageLPr(oldName);
3937            }
3938            // If there was no original package, see one for the real package name.
3939            if (ps == null) {
3940                ps = mSettings.peekPackageLPr(pkg.packageName);
3941            }
3942            // Check to see if this package could be hiding/updating a system
3943            // package.  Must look for it either under the original or real
3944            // package name depending on our state.
3945            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3946            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3947        }
3948        boolean updatedPkgBetter = false;
3949        // First check if this is a system package that may involve an update
3950        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3951            if (ps != null && !ps.codePath.equals(scanFile)) {
3952                // The path has changed from what was last scanned...  check the
3953                // version of the new path against what we have stored to determine
3954                // what to do.
3955                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3956                if (pkg.mVersionCode < ps.versionCode) {
3957                    // The system package has been updated and the code path does not match
3958                    // Ignore entry. Skip it.
3959                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3960                            + " ignored: updated version " + ps.versionCode
3961                            + " better than this " + pkg.mVersionCode);
3962                    if (!updatedPkg.codePath.equals(scanFile)) {
3963                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3964                                + ps.name + " changing from " + updatedPkg.codePathString
3965                                + " to " + scanFile);
3966                        updatedPkg.codePath = scanFile;
3967                        updatedPkg.codePathString = scanFile.toString();
3968                        // This is the point at which we know that the system-disk APK
3969                        // for this package has moved during a reboot (e.g. due to an OTA),
3970                        // so we need to reevaluate it for privilege policy.
3971                        if (locationIsPrivileged(scanFile)) {
3972                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3973                        }
3974                    }
3975                    updatedPkg.pkg = pkg;
3976                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3977                    return null;
3978                } else {
3979                    // The current app on the system partion is better than
3980                    // what we have updated to on the data partition; switch
3981                    // back to the system partition version.
3982                    // At this point, its safely assumed that package installation for
3983                    // apps in system partition will go through. If not there won't be a working
3984                    // version of the app
3985                    // writer
3986                    synchronized (mPackages) {
3987                        // Just remove the loaded entries from package lists.
3988                        mPackages.remove(ps.name);
3989                    }
3990                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3991                            + "reverting from " + ps.codePathString
3992                            + ": new version " + pkg.mVersionCode
3993                            + " better than installed " + ps.versionCode);
3994
3995                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3996                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
3997                            getAppInstructionSetFromSettings(ps));
3998                    synchronized (mInstallLock) {
3999                        args.cleanUpResourcesLI();
4000                    }
4001                    synchronized (mPackages) {
4002                        mSettings.enableSystemPackageLPw(ps.name);
4003                    }
4004                    updatedPkgBetter = true;
4005                }
4006            }
4007        }
4008
4009        if (updatedPkg != null) {
4010            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4011            // initially
4012            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4013
4014            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4015            // flag set initially
4016            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4017                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4018            }
4019        }
4020        // Verify certificates against what was last scanned
4021        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4022            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4023            return null;
4024        }
4025
4026        /*
4027         * A new system app appeared, but we already had a non-system one of the
4028         * same name installed earlier.
4029         */
4030        boolean shouldHideSystemApp = false;
4031        if (updatedPkg == null && ps != null
4032                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4033            /*
4034             * Check to make sure the signatures match first. If they don't,
4035             * wipe the installed application and its data.
4036             */
4037            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4038                    != PackageManager.SIGNATURE_MATCH) {
4039                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4040                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4041                ps = null;
4042            } else {
4043                /*
4044                 * If the newly-added system app is an older version than the
4045                 * already installed version, hide it. It will be scanned later
4046                 * and re-added like an update.
4047                 */
4048                if (pkg.mVersionCode < ps.versionCode) {
4049                    shouldHideSystemApp = true;
4050                } else {
4051                    /*
4052                     * The newly found system app is a newer version that the
4053                     * one previously installed. Simply remove the
4054                     * already-installed application and replace it with our own
4055                     * while keeping the application data.
4056                     */
4057                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4058                            + ps.codePathString + ": new version " + pkg.mVersionCode
4059                            + " better than installed " + ps.versionCode);
4060                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4061                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4062                            getAppInstructionSetFromSettings(ps));
4063                    synchronized (mInstallLock) {
4064                        args.cleanUpResourcesLI();
4065                    }
4066                }
4067            }
4068        }
4069
4070        // The apk is forward locked (not public) if its code and resources
4071        // are kept in different files. (except for app in either system or
4072        // vendor path).
4073        // TODO grab this value from PackageSettings
4074        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4075            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4076                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4077            }
4078        }
4079
4080        String codePath = null;
4081        String resPath = null;
4082        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4083            if (ps != null && ps.resourcePathString != null) {
4084                resPath = ps.resourcePathString;
4085            } else {
4086                // Should not happen at all. Just log an error.
4087                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4088            }
4089        } else {
4090            resPath = pkg.mScanPath;
4091        }
4092
4093        codePath = pkg.mScanPath;
4094        // Set application objects path explicitly.
4095        setApplicationInfoPaths(pkg, codePath, resPath);
4096        // Note that we invoke the following method only if we are about to unpack an application
4097        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4098                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4099
4100        /*
4101         * If the system app should be overridden by a previously installed
4102         * data, hide the system app now and let the /data/app scan pick it up
4103         * again.
4104         */
4105        if (shouldHideSystemApp) {
4106            synchronized (mPackages) {
4107                /*
4108                 * We have to grant systems permissions before we hide, because
4109                 * grantPermissions will assume the package update is trying to
4110                 * expand its permissions.
4111                 */
4112                grantPermissionsLPw(pkg, true);
4113                mSettings.disableSystemPackageLPw(pkg.packageName);
4114            }
4115        }
4116
4117        return scannedPkg;
4118    }
4119
4120    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4121            String destResPath) {
4122        pkg.mPath = pkg.mScanPath = destCodePath;
4123        pkg.applicationInfo.sourceDir = destCodePath;
4124        pkg.applicationInfo.publicSourceDir = destResPath;
4125    }
4126
4127    private static String fixProcessName(String defProcessName,
4128            String processName, int uid) {
4129        if (processName == null) {
4130            return defProcessName;
4131        }
4132        return processName;
4133    }
4134
4135    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4136        if (pkgSetting.signatures.mSignatures != null) {
4137            // Already existing package. Make sure signatures match
4138            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4139                    == PackageManager.SIGNATURE_MATCH;
4140            if (!match) {
4141                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4142                        == PackageManager.SIGNATURE_MATCH;
4143            }
4144            if (!match) {
4145                Slog.e(TAG, "Package " + pkg.packageName
4146                        + " signatures do not match the previously installed version; ignoring!");
4147                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4148                return false;
4149            }
4150        }
4151        // Check for shared user signatures
4152        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4153            // Already existing package. Make sure signatures match
4154            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4155                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4156            if (!match) {
4157                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4158                        == PackageManager.SIGNATURE_MATCH;
4159            }
4160            if (!match) {
4161                Slog.e(TAG, "Package " + pkg.packageName
4162                        + " has no signatures that match those in shared user "
4163                        + pkgSetting.sharedUser.name + "; ignoring!");
4164                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4165                return false;
4166            }
4167        }
4168        return true;
4169    }
4170
4171    /**
4172     * Enforces that only the system UID or root's UID can call a method exposed
4173     * via Binder.
4174     *
4175     * @param message used as message if SecurityException is thrown
4176     * @throws SecurityException if the caller is not system or root
4177     */
4178    private static final void enforceSystemOrRoot(String message) {
4179        final int uid = Binder.getCallingUid();
4180        if (uid != Process.SYSTEM_UID && uid != 0) {
4181            throw new SecurityException(message);
4182        }
4183    }
4184
4185    @Override
4186    public void performBootDexOpt() {
4187        enforceSystemOrRoot("Only the system can request dexopt be performed");
4188
4189        final HashSet<PackageParser.Package> pkgs;
4190        synchronized (mPackages) {
4191            pkgs = mDeferredDexOpt;
4192            mDeferredDexOpt = null;
4193        }
4194
4195        if (pkgs != null) {
4196            int i = 0;
4197            for (PackageParser.Package pkg : pkgs) {
4198                if (!isFirstBoot()) {
4199                    i++;
4200                    try {
4201                        ActivityManagerNative.getDefault().showBootMessage(
4202                                mContext.getResources().getString(
4203                                        com.android.internal.R.string.android_upgrading_apk,
4204                                        i, pkgs.size()), true);
4205                    } catch (RemoteException e) {
4206                    }
4207                }
4208                PackageParser.Package p = pkg;
4209                synchronized (mInstallLock) {
4210                    if (!p.mDidDexOpt) {
4211                        performDexOptLI(p, false /* force dex */, false /* defer */,
4212                                true /* include dependencies */);
4213                    }
4214                }
4215            }
4216        }
4217    }
4218
4219    @Override
4220    public boolean performDexOpt(String packageName) {
4221        enforceSystemOrRoot("Only the system can request dexopt be performed");
4222        if (!mNoDexOpt) {
4223            return false;
4224        }
4225
4226        PackageParser.Package p;
4227        synchronized (mPackages) {
4228            p = mPackages.get(packageName);
4229            if (p == null || p.mDidDexOpt) {
4230                return false;
4231            }
4232        }
4233        synchronized (mInstallLock) {
4234            return performDexOptLI(p, false /* force dex */, false /* defer */,
4235                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4236        }
4237    }
4238
4239    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex,
4240            boolean defer, HashSet<String> done) {
4241        for (int i=0; i<libs.size(); i++) {
4242            PackageParser.Package libPkg;
4243            String libName;
4244            synchronized (mPackages) {
4245                libName = libs.get(i);
4246                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4247                if (lib != null && lib.apk != null) {
4248                    libPkg = mPackages.get(lib.apk);
4249                } else {
4250                    libPkg = null;
4251                }
4252            }
4253            if (libPkg != null && !done.contains(libName)) {
4254                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4255            }
4256        }
4257    }
4258
4259    static final int DEX_OPT_SKIPPED = 0;
4260    static final int DEX_OPT_PERFORMED = 1;
4261    static final int DEX_OPT_DEFERRED = 2;
4262    static final int DEX_OPT_FAILED = -1;
4263
4264    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4265            boolean forceDex,
4266            boolean defer, HashSet<String> done) {
4267        final String instructionSet = instructionSetOverride != null ?
4268                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4269
4270        if (done != null) {
4271            done.add(pkg.packageName);
4272            if (pkg.usesLibraries != null) {
4273                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4274            }
4275            if (pkg.usesOptionalLibraries != null) {
4276                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4277            }
4278        }
4279
4280        boolean performed = false;
4281        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4282            String path = pkg.mScanPath;
4283            int ret = 0;
4284            try {
4285                if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path,
4286                        pkg.packageName, instructionSet, defer)) {
4287                    if (!forceDex && defer) {
4288                        if (mDeferredDexOpt == null) {
4289                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4290                        }
4291                        mDeferredDexOpt.add(pkg);
4292                        return DEX_OPT_DEFERRED;
4293                    } else {
4294                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName +
4295                                " (instructionSet=" + instructionSet + ")");
4296
4297                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4298                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4299                                                pkg.packageName, instructionSet);
4300                        pkg.mDidDexOpt = true;
4301                        performed = true;
4302                    }
4303                }
4304            } catch (FileNotFoundException e) {
4305                Slog.w(TAG, "Apk not found for dexopt: " + path);
4306                ret = -1;
4307            } catch (IOException e) {
4308                Slog.w(TAG, "IOException reading apk: " + path, e);
4309                ret = -1;
4310            } catch (dalvik.system.StaleDexCacheError e) {
4311                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4312                ret = -1;
4313            } catch (Exception e) {
4314                Slog.w(TAG, "Exception when doing dexopt : ", e);
4315                ret = -1;
4316            }
4317            if (ret < 0) {
4318                //error from installer
4319                return DEX_OPT_FAILED;
4320            }
4321        }
4322
4323        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4324    }
4325
4326    private String getAppInstructionSet(ApplicationInfo info) {
4327        String instructionSet = getPreferredInstructionSet();
4328
4329        if (info.requiredCpuAbi != null) {
4330            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4331        }
4332
4333        return instructionSet;
4334    }
4335
4336    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4337        String instructionSet = getPreferredInstructionSet();
4338
4339        if (ps.requiredCpuAbiString != null) {
4340            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4341        }
4342
4343        return instructionSet;
4344    }
4345
4346    private static String getPreferredInstructionSet() {
4347        if (sPreferredInstructionSet == null) {
4348            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4349        }
4350
4351        return sPreferredInstructionSet;
4352    }
4353
4354    private static List<String> getAllInstructionSets() {
4355        final String[] allAbis = Build.SUPPORTED_ABIS;
4356        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4357
4358        for (String abi : allAbis) {
4359            final String instructionSet = VMRuntime.getInstructionSet(abi);
4360            if (!allInstructionSets.contains(instructionSet)) {
4361                allInstructionSets.add(instructionSet);
4362            }
4363        }
4364
4365        return allInstructionSets;
4366    }
4367
4368    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4369            boolean inclDependencies) {
4370        HashSet<String> done;
4371        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4372            done = new HashSet<String>();
4373            done.add(pkg.packageName);
4374        } else {
4375            done = null;
4376        }
4377        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4378    }
4379
4380    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4381        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4382            Slog.w(TAG, "Unable to update from " + oldPkg.name
4383                    + " to " + newPkg.packageName
4384                    + ": old package not in system partition");
4385            return false;
4386        } else if (mPackages.get(oldPkg.name) != null) {
4387            Slog.w(TAG, "Unable to update from " + oldPkg.name
4388                    + " to " + newPkg.packageName
4389                    + ": old package still exists");
4390            return false;
4391        }
4392        return true;
4393    }
4394
4395    File getDataPathForUser(int userId) {
4396        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4397    }
4398
4399    private File getDataPathForPackage(String packageName, int userId) {
4400        /*
4401         * Until we fully support multiple users, return the directory we
4402         * previously would have. The PackageManagerTests will need to be
4403         * revised when this is changed back..
4404         */
4405        if (userId == 0) {
4406            return new File(mAppDataDir, packageName);
4407        } else {
4408            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4409                + File.separator + packageName);
4410        }
4411    }
4412
4413    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4414        int[] users = sUserManager.getUserIds();
4415        int res = mInstaller.install(packageName, uid, uid, seinfo);
4416        if (res < 0) {
4417            return res;
4418        }
4419        for (int user : users) {
4420            if (user != 0) {
4421                res = mInstaller.createUserData(packageName,
4422                        UserHandle.getUid(user, uid), user, seinfo);
4423                if (res < 0) {
4424                    return res;
4425                }
4426            }
4427        }
4428        return res;
4429    }
4430
4431    private int removeDataDirsLI(String packageName) {
4432        int[] users = sUserManager.getUserIds();
4433        int res = 0;
4434        for (int user : users) {
4435            int resInner = mInstaller.remove(packageName, user);
4436            if (resInner < 0) {
4437                res = resInner;
4438            }
4439        }
4440
4441        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4442        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4443        if (!nativeLibraryFile.delete()) {
4444            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4445        }
4446
4447        return res;
4448    }
4449
4450    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4451            PackageParser.Package changingLib) {
4452        if (file.path != null) {
4453            mTmpSharedLibraries[num] = file.path;
4454            return num+1;
4455        }
4456        PackageParser.Package p = mPackages.get(file.apk);
4457        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4458            // If we are doing this while in the middle of updating a library apk,
4459            // then we need to make sure to use that new apk for determining the
4460            // dependencies here.  (We haven't yet finished committing the new apk
4461            // to the package manager state.)
4462            if (p == null || p.packageName.equals(changingLib.packageName)) {
4463                p = changingLib;
4464            }
4465        }
4466        if (p != null) {
4467            String path = p.mPath;
4468            for (int i=0; i<num; i++) {
4469                if (mTmpSharedLibraries[i].equals(path)) {
4470                    return num;
4471                }
4472            }
4473            mTmpSharedLibraries[num] = p.mPath;
4474            return num+1;
4475        }
4476        return num;
4477    }
4478
4479    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4480            PackageParser.Package changingLib) {
4481        // We might be upgrading from a version of the platform that did not
4482        // provide per-package native library directories for system apps.
4483        // Fix that up here.
4484        if (isSystemApp(pkg)) {
4485            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4486            setInternalAppNativeLibraryPath(pkg, ps);
4487        }
4488
4489        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4490            if (mTmpSharedLibraries == null ||
4491                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4492                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4493            }
4494            int num = 0;
4495            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4496            for (int i=0; i<N; i++) {
4497                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4498                if (file == null) {
4499                    Slog.e(TAG, "Package " + pkg.packageName
4500                            + " requires unavailable shared library "
4501                            + pkg.usesLibraries.get(i) + "; failing!");
4502                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4503                    return false;
4504                }
4505                num = addSharedLibraryLPw(file, num, changingLib);
4506            }
4507            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4508            for (int i=0; i<N; i++) {
4509                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4510                if (file == null) {
4511                    Slog.w(TAG, "Package " + pkg.packageName
4512                            + " desires unavailable shared library "
4513                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4514                } else {
4515                    num = addSharedLibraryLPw(file, num, changingLib);
4516                }
4517            }
4518            if (num > 0) {
4519                pkg.usesLibraryFiles = new String[num];
4520                System.arraycopy(mTmpSharedLibraries, 0,
4521                        pkg.usesLibraryFiles, 0, num);
4522            } else {
4523                pkg.usesLibraryFiles = null;
4524            }
4525        }
4526        return true;
4527    }
4528
4529    private static boolean hasString(List<String> list, List<String> which) {
4530        if (list == null) {
4531            return false;
4532        }
4533        for (int i=list.size()-1; i>=0; i--) {
4534            for (int j=which.size()-1; j>=0; j--) {
4535                if (which.get(j).equals(list.get(i))) {
4536                    return true;
4537                }
4538            }
4539        }
4540        return false;
4541    }
4542
4543    private void updateAllSharedLibrariesLPw() {
4544        for (PackageParser.Package pkg : mPackages.values()) {
4545            updateSharedLibrariesLPw(pkg, null);
4546        }
4547    }
4548
4549    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4550            PackageParser.Package changingPkg) {
4551        ArrayList<PackageParser.Package> res = null;
4552        for (PackageParser.Package pkg : mPackages.values()) {
4553            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4554                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4555                if (res == null) {
4556                    res = new ArrayList<PackageParser.Package>();
4557                }
4558                res.add(pkg);
4559                updateSharedLibrariesLPw(pkg, changingPkg);
4560            }
4561        }
4562        return res;
4563    }
4564
4565    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4566            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4567        File scanFile = new File(pkg.mScanPath);
4568        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4569                pkg.applicationInfo.publicSourceDir == null) {
4570            // Bail out. The resource and code paths haven't been set.
4571            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4572            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4573            return null;
4574        }
4575
4576        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4577            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4578        }
4579
4580        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4581            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4582        }
4583
4584        if (mCustomResolverComponentName != null &&
4585                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4586            setUpCustomResolverActivity(pkg);
4587        }
4588
4589        if (pkg.packageName.equals("android")) {
4590            synchronized (mPackages) {
4591                if (mAndroidApplication != null) {
4592                    Slog.w(TAG, "*************************************************");
4593                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4594                    Slog.w(TAG, " file=" + scanFile);
4595                    Slog.w(TAG, "*************************************************");
4596                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4597                    return null;
4598                }
4599
4600                // Set up information for our fall-back user intent resolution activity.
4601                mPlatformPackage = pkg;
4602                pkg.mVersionCode = mSdkVersion;
4603                mAndroidApplication = pkg.applicationInfo;
4604
4605                if (!mResolverReplaced) {
4606                    mResolveActivity.applicationInfo = mAndroidApplication;
4607                    mResolveActivity.name = ResolverActivity.class.getName();
4608                    mResolveActivity.packageName = mAndroidApplication.packageName;
4609                    mResolveActivity.processName = "system:ui";
4610                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4611                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4612                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4613                    mResolveActivity.exported = true;
4614                    mResolveActivity.enabled = true;
4615                    mResolveInfo.activityInfo = mResolveActivity;
4616                    mResolveInfo.priority = 0;
4617                    mResolveInfo.preferredOrder = 0;
4618                    mResolveInfo.match = 0;
4619                    mResolveComponentName = new ComponentName(
4620                            mAndroidApplication.packageName, mResolveActivity.name);
4621                }
4622            }
4623        }
4624
4625        if (DEBUG_PACKAGE_SCANNING) {
4626            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4627                Log.d(TAG, "Scanning package " + pkg.packageName);
4628        }
4629
4630        if (mPackages.containsKey(pkg.packageName)
4631                || mSharedLibraries.containsKey(pkg.packageName)) {
4632            Slog.w(TAG, "Application package " + pkg.packageName
4633                    + " already installed.  Skipping duplicate.");
4634            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4635            return null;
4636        }
4637
4638        // Initialize package source and resource directories
4639        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4640        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4641
4642        SharedUserSetting suid = null;
4643        PackageSetting pkgSetting = null;
4644
4645        if (!isSystemApp(pkg)) {
4646            // Only system apps can use these features.
4647            pkg.mOriginalPackages = null;
4648            pkg.mRealPackage = null;
4649            pkg.mAdoptPermissions = null;
4650        }
4651
4652        // writer
4653        synchronized (mPackages) {
4654            if (pkg.mSharedUserId != null) {
4655                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4656                if (suid == null) {
4657                    Slog.w(TAG, "Creating application package " + pkg.packageName
4658                            + " for shared user failed");
4659                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4660                    return null;
4661                }
4662                if (DEBUG_PACKAGE_SCANNING) {
4663                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4664                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4665                                + "): packages=" + suid.packages);
4666                }
4667            }
4668
4669            // Check if we are renaming from an original package name.
4670            PackageSetting origPackage = null;
4671            String realName = null;
4672            if (pkg.mOriginalPackages != null) {
4673                // This package may need to be renamed to a previously
4674                // installed name.  Let's check on that...
4675                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4676                if (pkg.mOriginalPackages.contains(renamed)) {
4677                    // This package had originally been installed as the
4678                    // original name, and we have already taken care of
4679                    // transitioning to the new one.  Just update the new
4680                    // one to continue using the old name.
4681                    realName = pkg.mRealPackage;
4682                    if (!pkg.packageName.equals(renamed)) {
4683                        // Callers into this function may have already taken
4684                        // care of renaming the package; only do it here if
4685                        // it is not already done.
4686                        pkg.setPackageName(renamed);
4687                    }
4688
4689                } else {
4690                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4691                        if ((origPackage = mSettings.peekPackageLPr(
4692                                pkg.mOriginalPackages.get(i))) != null) {
4693                            // We do have the package already installed under its
4694                            // original name...  should we use it?
4695                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4696                                // New package is not compatible with original.
4697                                origPackage = null;
4698                                continue;
4699                            } else if (origPackage.sharedUser != null) {
4700                                // Make sure uid is compatible between packages.
4701                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4702                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4703                                            + " to " + pkg.packageName + ": old uid "
4704                                            + origPackage.sharedUser.name
4705                                            + " differs from " + pkg.mSharedUserId);
4706                                    origPackage = null;
4707                                    continue;
4708                                }
4709                            } else {
4710                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4711                                        + pkg.packageName + " to old name " + origPackage.name);
4712                            }
4713                            break;
4714                        }
4715                    }
4716                }
4717            }
4718
4719            if (mTransferedPackages.contains(pkg.packageName)) {
4720                Slog.w(TAG, "Package " + pkg.packageName
4721                        + " was transferred to another, but its .apk remains");
4722            }
4723
4724            // Just create the setting, don't add it yet. For already existing packages
4725            // the PkgSetting exists already and doesn't have to be created.
4726            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4727                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4728                    pkg.applicationInfo.requiredCpuAbi,
4729                    pkg.applicationInfo.flags, user, false);
4730            if (pkgSetting == null) {
4731                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4732                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4733                return null;
4734            }
4735
4736            if (pkgSetting.origPackage != null) {
4737                // If we are first transitioning from an original package,
4738                // fix up the new package's name now.  We need to do this after
4739                // looking up the package under its new name, so getPackageLP
4740                // can take care of fiddling things correctly.
4741                pkg.setPackageName(origPackage.name);
4742
4743                // File a report about this.
4744                String msg = "New package " + pkgSetting.realName
4745                        + " renamed to replace old package " + pkgSetting.name;
4746                reportSettingsProblem(Log.WARN, msg);
4747
4748                // Make a note of it.
4749                mTransferedPackages.add(origPackage.name);
4750
4751                // No longer need to retain this.
4752                pkgSetting.origPackage = null;
4753            }
4754
4755            if (realName != null) {
4756                // Make a note of it.
4757                mTransferedPackages.add(pkg.packageName);
4758            }
4759
4760            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4761                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4762            }
4763
4764            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4765                // Check all shared libraries and map to their actual file path.
4766                // We only do this here for apps not on a system dir, because those
4767                // are the only ones that can fail an install due to this.  We
4768                // will take care of the system apps by updating all of their
4769                // library paths after the scan is done.
4770                if (!updateSharedLibrariesLPw(pkg, null)) {
4771                    return null;
4772                }
4773            }
4774
4775            if (mFoundPolicyFile) {
4776                SELinuxMMAC.assignSeinfoValue(pkg);
4777            }
4778
4779            pkg.applicationInfo.uid = pkgSetting.appId;
4780            pkg.mExtras = pkgSetting;
4781
4782            if (!verifySignaturesLP(pkgSetting, pkg)) {
4783                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4784                    return null;
4785                }
4786                // The signature has changed, but this package is in the system
4787                // image...  let's recover!
4788                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4789                // However...  if this package is part of a shared user, but it
4790                // doesn't match the signature of the shared user, let's fail.
4791                // What this means is that you can't change the signatures
4792                // associated with an overall shared user, which doesn't seem all
4793                // that unreasonable.
4794                if (pkgSetting.sharedUser != null) {
4795                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4796                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4797                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4798                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4799                        return null;
4800                    }
4801                }
4802                // File a report about this.
4803                String msg = "System package " + pkg.packageName
4804                        + " signature changed; retaining data.";
4805                reportSettingsProblem(Log.WARN, msg);
4806            }
4807
4808            // Verify that this new package doesn't have any content providers
4809            // that conflict with existing packages.  Only do this if the
4810            // package isn't already installed, since we don't want to break
4811            // things that are installed.
4812            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4813                final int N = pkg.providers.size();
4814                int i;
4815                for (i=0; i<N; i++) {
4816                    PackageParser.Provider p = pkg.providers.get(i);
4817                    if (p.info.authority != null) {
4818                        String names[] = p.info.authority.split(";");
4819                        for (int j = 0; j < names.length; j++) {
4820                            if (mProvidersByAuthority.containsKey(names[j])) {
4821                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4822                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4823                                        " (in package " + pkg.applicationInfo.packageName +
4824                                        ") is already used by "
4825                                        + ((other != null && other.getComponentName() != null)
4826                                                ? other.getComponentName().getPackageName() : "?"));
4827                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4828                                return null;
4829                            }
4830                        }
4831                    }
4832                }
4833            }
4834
4835            if (pkg.mAdoptPermissions != null) {
4836                // This package wants to adopt ownership of permissions from
4837                // another package.
4838                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4839                    final String origName = pkg.mAdoptPermissions.get(i);
4840                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4841                    if (orig != null) {
4842                        if (verifyPackageUpdateLPr(orig, pkg)) {
4843                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4844                                    + pkg.packageName);
4845                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4846                        }
4847                    }
4848                }
4849            }
4850        }
4851
4852        final String pkgName = pkg.packageName;
4853
4854        final long scanFileTime = scanFile.lastModified();
4855        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4856        pkg.applicationInfo.processName = fixProcessName(
4857                pkg.applicationInfo.packageName,
4858                pkg.applicationInfo.processName,
4859                pkg.applicationInfo.uid);
4860
4861        File dataPath;
4862        if (mPlatformPackage == pkg) {
4863            // The system package is special.
4864            dataPath = new File (Environment.getDataDirectory(), "system");
4865            pkg.applicationInfo.dataDir = dataPath.getPath();
4866        } else {
4867            // This is a normal package, need to make its data directory.
4868            dataPath = getDataPathForPackage(pkg.packageName, 0);
4869
4870            boolean uidError = false;
4871
4872            if (dataPath.exists()) {
4873                int currentUid = 0;
4874                try {
4875                    StructStat stat = Os.stat(dataPath.getPath());
4876                    currentUid = stat.st_uid;
4877                } catch (ErrnoException e) {
4878                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4879                }
4880
4881                // If we have mismatched owners for the data path, we have a problem.
4882                if (currentUid != pkg.applicationInfo.uid) {
4883                    boolean recovered = false;
4884                    if (currentUid == 0) {
4885                        // The directory somehow became owned by root.  Wow.
4886                        // This is probably because the system was stopped while
4887                        // installd was in the middle of messing with its libs
4888                        // directory.  Ask installd to fix that.
4889                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4890                                pkg.applicationInfo.uid);
4891                        if (ret >= 0) {
4892                            recovered = true;
4893                            String msg = "Package " + pkg.packageName
4894                                    + " unexpectedly changed to uid 0; recovered to " +
4895                                    + pkg.applicationInfo.uid;
4896                            reportSettingsProblem(Log.WARN, msg);
4897                        }
4898                    }
4899                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4900                            || (scanMode&SCAN_BOOTING) != 0)) {
4901                        // If this is a system app, we can at least delete its
4902                        // current data so the application will still work.
4903                        int ret = removeDataDirsLI(pkgName);
4904                        if (ret >= 0) {
4905                            // TODO: Kill the processes first
4906                            // Old data gone!
4907                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4908                                    ? "System package " : "Third party package ";
4909                            String msg = prefix + pkg.packageName
4910                                    + " has changed from uid: "
4911                                    + currentUid + " to "
4912                                    + pkg.applicationInfo.uid + "; old data erased";
4913                            reportSettingsProblem(Log.WARN, msg);
4914                            recovered = true;
4915
4916                            // And now re-install the app.
4917                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4918                                                   pkg.applicationInfo.seinfo);
4919                            if (ret == -1) {
4920                                // Ack should not happen!
4921                                msg = prefix + pkg.packageName
4922                                        + " could not have data directory re-created after delete.";
4923                                reportSettingsProblem(Log.WARN, msg);
4924                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4925                                return null;
4926                            }
4927                        }
4928                        if (!recovered) {
4929                            mHasSystemUidErrors = true;
4930                        }
4931                    } else if (!recovered) {
4932                        // If we allow this install to proceed, we will be broken.
4933                        // Abort, abort!
4934                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4935                        return null;
4936                    }
4937                    if (!recovered) {
4938                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4939                            + pkg.applicationInfo.uid + "/fs_"
4940                            + currentUid;
4941                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4942                        String msg = "Package " + pkg.packageName
4943                                + " has mismatched uid: "
4944                                + currentUid + " on disk, "
4945                                + pkg.applicationInfo.uid + " in settings";
4946                        // writer
4947                        synchronized (mPackages) {
4948                            mSettings.mReadMessages.append(msg);
4949                            mSettings.mReadMessages.append('\n');
4950                            uidError = true;
4951                            if (!pkgSetting.uidError) {
4952                                reportSettingsProblem(Log.ERROR, msg);
4953                            }
4954                        }
4955                    }
4956                }
4957                pkg.applicationInfo.dataDir = dataPath.getPath();
4958                if (mShouldRestoreconData) {
4959                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
4960                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
4961                                pkg.applicationInfo.uid);
4962                }
4963            } else {
4964                if (DEBUG_PACKAGE_SCANNING) {
4965                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4966                        Log.v(TAG, "Want this data dir: " + dataPath);
4967                }
4968                //invoke installer to do the actual installation
4969                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4970                                           pkg.applicationInfo.seinfo);
4971                if (ret < 0) {
4972                    // Error from installer
4973                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4974                    return null;
4975                }
4976
4977                if (dataPath.exists()) {
4978                    pkg.applicationInfo.dataDir = dataPath.getPath();
4979                } else {
4980                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4981                    pkg.applicationInfo.dataDir = null;
4982                }
4983            }
4984
4985            /*
4986             * Set the data dir to the default "/data/data/<package name>/lib"
4987             * if we got here without anyone telling us different (e.g., apps
4988             * stored on SD card have their native libraries stored in the ASEC
4989             * container with the APK).
4990             *
4991             * This happens during an upgrade from a package settings file that
4992             * doesn't have a native library path attribute at all.
4993             */
4994            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4995                if (pkgSetting.nativeLibraryPathString == null) {
4996                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4997                } else {
4998                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4999                }
5000            }
5001            pkgSetting.uidError = uidError;
5002        }
5003
5004        String path = scanFile.getPath();
5005        /* Note: We don't want to unpack the native binaries for
5006         *        system applications, unless they have been updated
5007         *        (the binaries are already under /system/lib).
5008         *        Also, don't unpack libs for apps on the external card
5009         *        since they should have their libraries in the ASEC
5010         *        container already.
5011         *
5012         *        In other words, we're going to unpack the binaries
5013         *        only for non-system apps and system app upgrades.
5014         */
5015        if (pkg.applicationInfo.nativeLibraryDir != null) {
5016            try {
5017                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5018                final String dataPathString = dataPath.getCanonicalPath();
5019
5020                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5021                    /*
5022                     * Upgrading from a previous version of the OS sometimes
5023                     * leaves native libraries in the /data/data/<app>/lib
5024                     * directory for system apps even when they shouldn't be.
5025                     * Recent changes in the JNI library search path
5026                     * necessitates we remove those to match previous behavior.
5027                     */
5028                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5029                        Log.i(TAG, "removed obsolete native libraries for system package "
5030                                + path);
5031                    }
5032
5033                    setInternalAppAbi(pkg, pkgSetting);
5034                } else {
5035                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5036                        /*
5037                         * Update native library dir if it starts with
5038                         * /data/data
5039                         */
5040                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5041                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5042                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5043                        }
5044
5045                        try {
5046                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5047                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5048                                Slog.e(TAG, "Unable to copy native libraries");
5049                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5050                                return null;
5051                            }
5052
5053                            // We've successfully copied native libraries across, so we make a
5054                            // note of what ABI we're using
5055                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5056                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
5057                            } else {
5058                                pkg.applicationInfo.requiredCpuAbi = null;
5059                            }
5060                        } catch (IOException e) {
5061                            Slog.e(TAG, "Unable to copy native libraries", e);
5062                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5063                            return null;
5064                        }
5065                    } else {
5066                        // We don't have to copy the shared libraries if we're in the ASEC container
5067                        // but we still need to scan the file to figure out what ABI the app needs.
5068                        //
5069                        // TODO: This duplicates work done in the default container service. It's possible
5070                        // to clean this up but we'll need to change the interface between this service
5071                        // and IMediaContainerService (but doing so will spread this logic out, rather
5072                        // than centralizing it).
5073                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5074                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5075                        if (abi >= 0) {
5076                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
5077                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5078                            // Note that (non upgraded) system apps will not have any native
5079                            // libraries bundled in their APK, but we're guaranteed not to be
5080                            // such an app at this point.
5081                            pkg.applicationInfo.requiredCpuAbi = null;
5082                        } else {
5083                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5084                            return null;
5085                        }
5086                        handle.close();
5087                    }
5088
5089                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5090                    final int[] userIds = sUserManager.getUserIds();
5091                    synchronized (mInstallLock) {
5092                        for (int userId : userIds) {
5093                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5094                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5095                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5096                                        + ")");
5097                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5098                                return null;
5099                            }
5100                        }
5101                    }
5102                }
5103            } catch (IOException ioe) {
5104                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5105            }
5106        }
5107        pkg.mScanPath = path;
5108
5109        if ((scanMode&SCAN_NO_DEX) == 0) {
5110            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5111                    == DEX_OPT_FAILED) {
5112                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5113                    removeDataDirsLI(pkg.packageName);
5114                }
5115
5116                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5117                return null;
5118            }
5119        }
5120
5121        if (mFactoryTest && pkg.requestedPermissions.contains(
5122                android.Manifest.permission.FACTORY_TEST)) {
5123            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5124        }
5125
5126        ArrayList<PackageParser.Package> clientLibPkgs = null;
5127
5128        // writer
5129        synchronized (mPackages) {
5130            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5131                // Only system apps can add new shared libraries.
5132                if (pkg.libraryNames != null) {
5133                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5134                        String name = pkg.libraryNames.get(i);
5135                        boolean allowed = false;
5136                        if (isUpdatedSystemApp(pkg)) {
5137                            // New library entries can only be added through the
5138                            // system image.  This is important to get rid of a lot
5139                            // of nasty edge cases: for example if we allowed a non-
5140                            // system update of the app to add a library, then uninstalling
5141                            // the update would make the library go away, and assumptions
5142                            // we made such as through app install filtering would now
5143                            // have allowed apps on the device which aren't compatible
5144                            // with it.  Better to just have the restriction here, be
5145                            // conservative, and create many fewer cases that can negatively
5146                            // impact the user experience.
5147                            final PackageSetting sysPs = mSettings
5148                                    .getDisabledSystemPkgLPr(pkg.packageName);
5149                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5150                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5151                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5152                                        allowed = true;
5153                                        allowed = true;
5154                                        break;
5155                                    }
5156                                }
5157                            }
5158                        } else {
5159                            allowed = true;
5160                        }
5161                        if (allowed) {
5162                            if (!mSharedLibraries.containsKey(name)) {
5163                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5164                            } else if (!name.equals(pkg.packageName)) {
5165                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5166                                        + name + " already exists; skipping");
5167                            }
5168                        } else {
5169                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5170                                    + name + " that is not declared on system image; skipping");
5171                        }
5172                    }
5173                    if ((scanMode&SCAN_BOOTING) == 0) {
5174                        // If we are not booting, we need to update any applications
5175                        // that are clients of our shared library.  If we are booting,
5176                        // this will all be done once the scan is complete.
5177                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5178                    }
5179                }
5180            }
5181        }
5182
5183        // We also need to dexopt any apps that are dependent on this library.  Note that
5184        // if these fail, we should abort the install since installing the library will
5185        // result in some apps being broken.
5186        if (clientLibPkgs != null) {
5187            if ((scanMode&SCAN_NO_DEX) == 0) {
5188                for (int i=0; i<clientLibPkgs.size(); i++) {
5189                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5190                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5191                            == DEX_OPT_FAILED) {
5192                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5193                            removeDataDirsLI(pkg.packageName);
5194                        }
5195
5196                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5197                        return null;
5198                    }
5199                }
5200            }
5201        }
5202
5203        // Request the ActivityManager to kill the process(only for existing packages)
5204        // so that we do not end up in a confused state while the user is still using the older
5205        // version of the application while the new one gets installed.
5206        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5207            // If the package lives in an asec, tell everyone that the container is going
5208            // away so they can clean up any references to its resources (which would prevent
5209            // vold from being able to unmount the asec)
5210            if (isForwardLocked(pkg) || isExternal(pkg)) {
5211                if (DEBUG_INSTALL) {
5212                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5213                }
5214                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5215                final ArrayList<String> pkgList = new ArrayList<String>(1);
5216                pkgList.add(pkg.applicationInfo.packageName);
5217                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5218            }
5219
5220            // Post the request that it be killed now that the going-away broadcast is en route
5221            killApplication(pkg.applicationInfo.packageName,
5222                        pkg.applicationInfo.uid, "update pkg");
5223        }
5224
5225        // Also need to kill any apps that are dependent on the library.
5226        if (clientLibPkgs != null) {
5227            for (int i=0; i<clientLibPkgs.size(); i++) {
5228                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5229                killApplication(clientPkg.applicationInfo.packageName,
5230                        clientPkg.applicationInfo.uid, "update lib");
5231            }
5232        }
5233
5234        // writer
5235        synchronized (mPackages) {
5236            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5237                // We don't do this here during boot because we can do it all
5238                // at once after scanning all existing packages.
5239                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5240                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5241            }
5242            // We don't expect installation to fail beyond this point,
5243            if ((scanMode&SCAN_MONITOR) != 0) {
5244                mAppDirs.put(pkg.mPath, pkg);
5245            }
5246            // Add the new setting to mSettings
5247            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5248            // Add the new setting to mPackages
5249            mPackages.put(pkg.applicationInfo.packageName, pkg);
5250            // Make sure we don't accidentally delete its data.
5251            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5252            while (iter.hasNext()) {
5253                PackageCleanItem item = iter.next();
5254                if (pkgName.equals(item.packageName)) {
5255                    iter.remove();
5256                }
5257            }
5258
5259            // Take care of first install / last update times.
5260            if (currentTime != 0) {
5261                if (pkgSetting.firstInstallTime == 0) {
5262                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5263                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5264                    pkgSetting.lastUpdateTime = currentTime;
5265                }
5266            } else if (pkgSetting.firstInstallTime == 0) {
5267                // We need *something*.  Take time time stamp of the file.
5268                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5269            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5270                if (scanFileTime != pkgSetting.timeStamp) {
5271                    // A package on the system image has changed; consider this
5272                    // to be an update.
5273                    pkgSetting.lastUpdateTime = scanFileTime;
5274                }
5275            }
5276
5277            // Add the package's KeySets to the global KeySetManager
5278            KeySetManager ksm = mSettings.mKeySetManager;
5279            try {
5280                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5281                if (pkg.mKeySetMapping != null) {
5282                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5283                        if (entry.getValue() != null) {
5284                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5285                                entry.getValue(), entry.getKey());
5286                        }
5287                    }
5288                }
5289            } catch (NullPointerException e) {
5290                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5291            } catch (IllegalArgumentException e) {
5292                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5293            }
5294
5295            int N = pkg.providers.size();
5296            StringBuilder r = null;
5297            int i;
5298            for (i=0; i<N; i++) {
5299                PackageParser.Provider p = pkg.providers.get(i);
5300                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5301                        p.info.processName, pkg.applicationInfo.uid);
5302                mProviders.addProvider(p);
5303                p.syncable = p.info.isSyncable;
5304                if (p.info.authority != null) {
5305                    String names[] = p.info.authority.split(";");
5306                    p.info.authority = null;
5307                    for (int j = 0; j < names.length; j++) {
5308                        if (j == 1 && p.syncable) {
5309                            // We only want the first authority for a provider to possibly be
5310                            // syncable, so if we already added this provider using a different
5311                            // authority clear the syncable flag. We copy the provider before
5312                            // changing it because the mProviders object contains a reference
5313                            // to a provider that we don't want to change.
5314                            // Only do this for the second authority since the resulting provider
5315                            // object can be the same for all future authorities for this provider.
5316                            p = new PackageParser.Provider(p);
5317                            p.syncable = false;
5318                        }
5319                        if (!mProvidersByAuthority.containsKey(names[j])) {
5320                            mProvidersByAuthority.put(names[j], p);
5321                            if (p.info.authority == null) {
5322                                p.info.authority = names[j];
5323                            } else {
5324                                p.info.authority = p.info.authority + ";" + names[j];
5325                            }
5326                            if (DEBUG_PACKAGE_SCANNING) {
5327                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5328                                    Log.d(TAG, "Registered content provider: " + names[j]
5329                                            + ", className = " + p.info.name + ", isSyncable = "
5330                                            + p.info.isSyncable);
5331                            }
5332                        } else {
5333                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5334                            Slog.w(TAG, "Skipping provider name " + names[j] +
5335                                    " (in package " + pkg.applicationInfo.packageName +
5336                                    "): name already used by "
5337                                    + ((other != null && other.getComponentName() != null)
5338                                            ? other.getComponentName().getPackageName() : "?"));
5339                        }
5340                    }
5341                }
5342                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5343                    if (r == null) {
5344                        r = new StringBuilder(256);
5345                    } else {
5346                        r.append(' ');
5347                    }
5348                    r.append(p.info.name);
5349                }
5350            }
5351            if (r != null) {
5352                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5353            }
5354
5355            N = pkg.services.size();
5356            r = null;
5357            for (i=0; i<N; i++) {
5358                PackageParser.Service s = pkg.services.get(i);
5359                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5360                        s.info.processName, pkg.applicationInfo.uid);
5361                mServices.addService(s);
5362                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5363                    if (r == null) {
5364                        r = new StringBuilder(256);
5365                    } else {
5366                        r.append(' ');
5367                    }
5368                    r.append(s.info.name);
5369                }
5370            }
5371            if (r != null) {
5372                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5373            }
5374
5375            N = pkg.receivers.size();
5376            r = null;
5377            for (i=0; i<N; i++) {
5378                PackageParser.Activity a = pkg.receivers.get(i);
5379                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5380                        a.info.processName, pkg.applicationInfo.uid);
5381                mReceivers.addActivity(a, "receiver");
5382                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5383                    if (r == null) {
5384                        r = new StringBuilder(256);
5385                    } else {
5386                        r.append(' ');
5387                    }
5388                    r.append(a.info.name);
5389                }
5390            }
5391            if (r != null) {
5392                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5393            }
5394
5395            N = pkg.activities.size();
5396            r = null;
5397            for (i=0; i<N; i++) {
5398                PackageParser.Activity a = pkg.activities.get(i);
5399                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5400                        a.info.processName, pkg.applicationInfo.uid);
5401                mActivities.addActivity(a, "activity");
5402                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5403                    if (r == null) {
5404                        r = new StringBuilder(256);
5405                    } else {
5406                        r.append(' ');
5407                    }
5408                    r.append(a.info.name);
5409                }
5410            }
5411            if (r != null) {
5412                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5413            }
5414
5415            N = pkg.permissionGroups.size();
5416            r = null;
5417            for (i=0; i<N; i++) {
5418                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5419                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5420                if (cur == null) {
5421                    mPermissionGroups.put(pg.info.name, pg);
5422                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5423                        if (r == null) {
5424                            r = new StringBuilder(256);
5425                        } else {
5426                            r.append(' ');
5427                        }
5428                        r.append(pg.info.name);
5429                    }
5430                } else {
5431                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5432                            + pg.info.packageName + " ignored: original from "
5433                            + cur.info.packageName);
5434                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5435                        if (r == null) {
5436                            r = new StringBuilder(256);
5437                        } else {
5438                            r.append(' ');
5439                        }
5440                        r.append("DUP:");
5441                        r.append(pg.info.name);
5442                    }
5443                }
5444            }
5445            if (r != null) {
5446                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5447            }
5448
5449            N = pkg.permissions.size();
5450            r = null;
5451            for (i=0; i<N; i++) {
5452                PackageParser.Permission p = pkg.permissions.get(i);
5453                HashMap<String, BasePermission> permissionMap =
5454                        p.tree ? mSettings.mPermissionTrees
5455                        : mSettings.mPermissions;
5456                p.group = mPermissionGroups.get(p.info.group);
5457                if (p.info.group == null || p.group != null) {
5458                    BasePermission bp = permissionMap.get(p.info.name);
5459                    if (bp == null) {
5460                        bp = new BasePermission(p.info.name, p.info.packageName,
5461                                BasePermission.TYPE_NORMAL);
5462                        permissionMap.put(p.info.name, bp);
5463                    }
5464                    if (bp.perm == null) {
5465                        if (bp.sourcePackage != null
5466                                && !bp.sourcePackage.equals(p.info.packageName)) {
5467                            // If this is a permission that was formerly defined by a non-system
5468                            // app, but is now defined by a system app (following an upgrade),
5469                            // discard the previous declaration and consider the system's to be
5470                            // canonical.
5471                            if (isSystemApp(p.owner)) {
5472                                String msg = "New decl " + p.owner + " of permission  "
5473                                        + p.info.name + " is system";
5474                                reportSettingsProblem(Log.WARN, msg);
5475                                bp.sourcePackage = null;
5476                            }
5477                        }
5478                        if (bp.sourcePackage == null
5479                                || bp.sourcePackage.equals(p.info.packageName)) {
5480                            BasePermission tree = findPermissionTreeLP(p.info.name);
5481                            if (tree == null
5482                                    || tree.sourcePackage.equals(p.info.packageName)) {
5483                                bp.packageSetting = pkgSetting;
5484                                bp.perm = p;
5485                                bp.uid = pkg.applicationInfo.uid;
5486                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5487                                    if (r == null) {
5488                                        r = new StringBuilder(256);
5489                                    } else {
5490                                        r.append(' ');
5491                                    }
5492                                    r.append(p.info.name);
5493                                }
5494                            } else {
5495                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5496                                        + p.info.packageName + " ignored: base tree "
5497                                        + tree.name + " is from package "
5498                                        + tree.sourcePackage);
5499                            }
5500                        } else {
5501                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5502                                    + p.info.packageName + " ignored: original from "
5503                                    + bp.sourcePackage);
5504                        }
5505                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5506                        if (r == null) {
5507                            r = new StringBuilder(256);
5508                        } else {
5509                            r.append(' ');
5510                        }
5511                        r.append("DUP:");
5512                        r.append(p.info.name);
5513                    }
5514                    if (bp.perm == p) {
5515                        bp.protectionLevel = p.info.protectionLevel;
5516                    }
5517                } else {
5518                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5519                            + p.info.packageName + " ignored: no group "
5520                            + p.group);
5521                }
5522            }
5523            if (r != null) {
5524                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5525            }
5526
5527            N = pkg.instrumentation.size();
5528            r = null;
5529            for (i=0; i<N; i++) {
5530                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5531                a.info.packageName = pkg.applicationInfo.packageName;
5532                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5533                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5534                a.info.dataDir = pkg.applicationInfo.dataDir;
5535                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5536                mInstrumentation.put(a.getComponentName(), a);
5537                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5538                    if (r == null) {
5539                        r = new StringBuilder(256);
5540                    } else {
5541                        r.append(' ');
5542                    }
5543                    r.append(a.info.name);
5544                }
5545            }
5546            if (r != null) {
5547                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5548            }
5549
5550            if (pkg.protectedBroadcasts != null) {
5551                N = pkg.protectedBroadcasts.size();
5552                for (i=0; i<N; i++) {
5553                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5554                }
5555            }
5556
5557            pkgSetting.setTimeStamp(scanFileTime);
5558
5559            // Create idmap files for pairs of (packages, overlay packages).
5560            // Note: "android", ie framework-res.apk, is handled by native layers.
5561            if (pkg.mOverlayTarget != null) {
5562                // This is an overlay package.
5563                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5564                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5565                        mOverlays.put(pkg.mOverlayTarget,
5566                                new HashMap<String, PackageParser.Package>());
5567                    }
5568                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5569                    map.put(pkg.packageName, pkg);
5570                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5571                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5572                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5573                        return null;
5574                    }
5575                }
5576            } else if (mOverlays.containsKey(pkg.packageName) &&
5577                    !pkg.packageName.equals("android")) {
5578                // This is a regular package, with one or more known overlay packages.
5579                createIdmapsForPackageLI(pkg);
5580            }
5581        }
5582
5583        return pkg;
5584    }
5585
5586    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5587            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5588        String requiredInstructionSet = null;
5589        PackageSetting requirer = null;
5590        for (PackageSetting ps : packagesForUser) {
5591            if (ps.requiredCpuAbiString != null) {
5592                final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
5593                if (requiredInstructionSet != null) {
5594                    if (!instructionSet.equals(requiredInstructionSet)) {
5595                        // We have a mismatch between instruction sets (say arm vs arm64).
5596                        //
5597                        // TODO: We should rescan all the packages in a shared UID to check if
5598                        // they do contain shared libs for other ABIs in addition to the ones we've
5599                        // already extracted. For example, the package might contain both arm64-v8a
5600                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5601                        // devices.
5602                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5603                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5604                                + " requires " + instructionSet;
5605                        Slog.e(TAG, errorMessage);
5606
5607                        reportSettingsProblem(Log.WARN, errorMessage);
5608                        // Give up, don't bother making any other changes to the package settings.
5609                        return;
5610                    }
5611                } else {
5612                    requiredInstructionSet = instructionSet;
5613                    requirer = ps;
5614                }
5615            }
5616        }
5617
5618        if (requiredInstructionSet != null) {
5619            for (PackageSetting ps : packagesForUser) {
5620                if (ps.requiredCpuAbiString == null) {
5621                    ps.requiredCpuAbiString = requirer.requiredCpuAbiString;
5622                    ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString;
5623
5624                    Slog.i(TAG, "Adjusting ABI for : " + ps.pkg.packageName + " to " + ps.requiredCpuAbiString);
5625                    if (doDexOpt) {
5626                        performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
5627                        mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5628                    }
5629                }
5630            }
5631        }
5632    }
5633
5634    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5635        synchronized (mPackages) {
5636            mResolverReplaced = true;
5637            // Set up information for custom user intent resolution activity.
5638            mResolveActivity.applicationInfo = pkg.applicationInfo;
5639            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5640            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5641            mResolveActivity.processName = null;
5642            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5643            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5644                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5645            mResolveActivity.theme = 0;
5646            mResolveActivity.exported = true;
5647            mResolveActivity.enabled = true;
5648            mResolveInfo.activityInfo = mResolveActivity;
5649            mResolveInfo.priority = 0;
5650            mResolveInfo.preferredOrder = 0;
5651            mResolveInfo.match = 0;
5652            mResolveComponentName = mCustomResolverComponentName;
5653            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5654                    mResolveComponentName);
5655        }
5656    }
5657
5658    private String calculateApkRoot(final String codePathString) {
5659        final File codePath = new File(codePathString);
5660        final File codeRoot;
5661        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5662            codeRoot = Environment.getRootDirectory();
5663        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5664            codeRoot = Environment.getOemDirectory();
5665        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5666            codeRoot = Environment.getVendorDirectory();
5667        } else {
5668            // Unrecognized code path; take its top real segment as the apk root:
5669            // e.g. /something/app/blah.apk => /something
5670            try {
5671                File f = codePath.getCanonicalFile();
5672                File parent = f.getParentFile();    // non-null because codePath is a file
5673                File tmp;
5674                while ((tmp = parent.getParentFile()) != null) {
5675                    f = parent;
5676                    parent = tmp;
5677                }
5678                codeRoot = f;
5679                Slog.w(TAG, "Unrecognized code path "
5680                        + codePath + " - using " + codeRoot);
5681            } catch (IOException e) {
5682                // Can't canonicalize the lib path -- shenanigans?
5683                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5684                return Environment.getRootDirectory().getPath();
5685            }
5686        }
5687        return codeRoot.getPath();
5688    }
5689
5690    // This is the initial scan-time determination of how to handle a given
5691    // package for purposes of native library location.
5692    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5693            PackageSetting pkgSetting) {
5694        // "bundled" here means system-installed with no overriding update
5695        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5696        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5697        final File libDir;
5698        if (bundledApk) {
5699            // If "/system/lib64/apkname" exists, assume that is the per-package
5700            // native library directory to use; otherwise use "/system/lib/apkname".
5701            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5702            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5703            File packLib64 = new File(lib64, apkName);
5704            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5705        } else {
5706            libDir = mAppLibInstallDir;
5707        }
5708        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5709        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5710        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5711    }
5712
5713    // Deduces the required ABI of an upgraded system app.
5714    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
5715        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5716        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5717
5718        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
5719        // or similar.
5720        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
5721        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
5722
5723        // Assume that the bundled native libraries always correspond to the
5724        // most preferred 32 or 64 bit ABI.
5725        if (lib64.exists()) {
5726            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
5727            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
5728        } else if (lib.exists()) {
5729            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5730            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
5731        } else {
5732            // This is the case where the app has no native code.
5733            pkg.applicationInfo.requiredCpuAbi = null;
5734            pkgSetting.requiredCpuAbiString = null;
5735        }
5736    }
5737
5738    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5739            throws IOException {
5740        if (!nativeLibraryDir.isDirectory()) {
5741            nativeLibraryDir.delete();
5742
5743            if (!nativeLibraryDir.mkdir()) {
5744                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5745            }
5746
5747            try {
5748                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5749            } catch (ErrnoException e) {
5750                throw new IOException("Cannot chmod native library directory "
5751                        + nativeLibraryDir.getPath(), e);
5752            }
5753        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5754            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5755        }
5756
5757        /*
5758         * If this is an internal application or our nativeLibraryPath points to
5759         * the app-lib directory, unpack the libraries if necessary.
5760         */
5761        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5762        try {
5763            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5764            if (abi >= 0) {
5765                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5766                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5767                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5768                    return copyRet;
5769                }
5770            }
5771
5772            return abi;
5773        } finally {
5774            handle.close();
5775        }
5776    }
5777
5778    private void killApplication(String pkgName, int appId, String reason) {
5779        // Request the ActivityManager to kill the process(only for existing packages)
5780        // so that we do not end up in a confused state while the user is still using the older
5781        // version of the application while the new one gets installed.
5782        IActivityManager am = ActivityManagerNative.getDefault();
5783        if (am != null) {
5784            try {
5785                am.killApplicationWithAppId(pkgName, appId, reason);
5786            } catch (RemoteException e) {
5787            }
5788        }
5789    }
5790
5791    void removePackageLI(PackageSetting ps, boolean chatty) {
5792        if (DEBUG_INSTALL) {
5793            if (chatty)
5794                Log.d(TAG, "Removing package " + ps.name);
5795        }
5796
5797        // writer
5798        synchronized (mPackages) {
5799            mPackages.remove(ps.name);
5800            if (ps.codePathString != null) {
5801                mAppDirs.remove(ps.codePathString);
5802            }
5803
5804            final PackageParser.Package pkg = ps.pkg;
5805            if (pkg != null) {
5806                cleanPackageDataStructuresLILPw(pkg, chatty);
5807            }
5808        }
5809    }
5810
5811    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5812        if (DEBUG_INSTALL) {
5813            if (chatty)
5814                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5815        }
5816
5817        // writer
5818        synchronized (mPackages) {
5819            mPackages.remove(pkg.applicationInfo.packageName);
5820            if (pkg.mPath != null) {
5821                mAppDirs.remove(pkg.mPath);
5822            }
5823            cleanPackageDataStructuresLILPw(pkg, chatty);
5824        }
5825    }
5826
5827    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5828        int N = pkg.providers.size();
5829        StringBuilder r = null;
5830        int i;
5831        for (i=0; i<N; i++) {
5832            PackageParser.Provider p = pkg.providers.get(i);
5833            mProviders.removeProvider(p);
5834            if (p.info.authority == null) {
5835
5836                /* There was another ContentProvider with this authority when
5837                 * this app was installed so this authority is null,
5838                 * Ignore it as we don't have to unregister the provider.
5839                 */
5840                continue;
5841            }
5842            String names[] = p.info.authority.split(";");
5843            for (int j = 0; j < names.length; j++) {
5844                if (mProvidersByAuthority.get(names[j]) == p) {
5845                    mProvidersByAuthority.remove(names[j]);
5846                    if (DEBUG_REMOVE) {
5847                        if (chatty)
5848                            Log.d(TAG, "Unregistered content provider: " + names[j]
5849                                    + ", className = " + p.info.name + ", isSyncable = "
5850                                    + p.info.isSyncable);
5851                    }
5852                }
5853            }
5854            if (DEBUG_REMOVE && chatty) {
5855                if (r == null) {
5856                    r = new StringBuilder(256);
5857                } else {
5858                    r.append(' ');
5859                }
5860                r.append(p.info.name);
5861            }
5862        }
5863        if (r != null) {
5864            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5865        }
5866
5867        N = pkg.services.size();
5868        r = null;
5869        for (i=0; i<N; i++) {
5870            PackageParser.Service s = pkg.services.get(i);
5871            mServices.removeService(s);
5872            if (chatty) {
5873                if (r == null) {
5874                    r = new StringBuilder(256);
5875                } else {
5876                    r.append(' ');
5877                }
5878                r.append(s.info.name);
5879            }
5880        }
5881        if (r != null) {
5882            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5883        }
5884
5885        N = pkg.receivers.size();
5886        r = null;
5887        for (i=0; i<N; i++) {
5888            PackageParser.Activity a = pkg.receivers.get(i);
5889            mReceivers.removeActivity(a, "receiver");
5890            if (DEBUG_REMOVE && chatty) {
5891                if (r == null) {
5892                    r = new StringBuilder(256);
5893                } else {
5894                    r.append(' ');
5895                }
5896                r.append(a.info.name);
5897            }
5898        }
5899        if (r != null) {
5900            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5901        }
5902
5903        N = pkg.activities.size();
5904        r = null;
5905        for (i=0; i<N; i++) {
5906            PackageParser.Activity a = pkg.activities.get(i);
5907            mActivities.removeActivity(a, "activity");
5908            if (DEBUG_REMOVE && chatty) {
5909                if (r == null) {
5910                    r = new StringBuilder(256);
5911                } else {
5912                    r.append(' ');
5913                }
5914                r.append(a.info.name);
5915            }
5916        }
5917        if (r != null) {
5918            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5919        }
5920
5921        N = pkg.permissions.size();
5922        r = null;
5923        for (i=0; i<N; i++) {
5924            PackageParser.Permission p = pkg.permissions.get(i);
5925            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5926            if (bp == null) {
5927                bp = mSettings.mPermissionTrees.get(p.info.name);
5928            }
5929            if (bp != null && bp.perm == p) {
5930                bp.perm = null;
5931                if (DEBUG_REMOVE && chatty) {
5932                    if (r == null) {
5933                        r = new StringBuilder(256);
5934                    } else {
5935                        r.append(' ');
5936                    }
5937                    r.append(p.info.name);
5938                }
5939            }
5940        }
5941        if (r != null) {
5942            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5943        }
5944
5945        N = pkg.instrumentation.size();
5946        r = null;
5947        for (i=0; i<N; i++) {
5948            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5949            mInstrumentation.remove(a.getComponentName());
5950            if (DEBUG_REMOVE && chatty) {
5951                if (r == null) {
5952                    r = new StringBuilder(256);
5953                } else {
5954                    r.append(' ');
5955                }
5956                r.append(a.info.name);
5957            }
5958        }
5959        if (r != null) {
5960            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5961        }
5962
5963        r = null;
5964        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5965            // Only system apps can hold shared libraries.
5966            if (pkg.libraryNames != null) {
5967                for (i=0; i<pkg.libraryNames.size(); i++) {
5968                    String name = pkg.libraryNames.get(i);
5969                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5970                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5971                        mSharedLibraries.remove(name);
5972                        if (DEBUG_REMOVE && chatty) {
5973                            if (r == null) {
5974                                r = new StringBuilder(256);
5975                            } else {
5976                                r.append(' ');
5977                            }
5978                            r.append(name);
5979                        }
5980                    }
5981                }
5982            }
5983        }
5984        if (r != null) {
5985            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5986        }
5987    }
5988
5989    private static final boolean isPackageFilename(String name) {
5990        return name != null && name.endsWith(".apk");
5991    }
5992
5993    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5994        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5995            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5996                return true;
5997            }
5998        }
5999        return false;
6000    }
6001
6002    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6003    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6004    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6005
6006    private void updatePermissionsLPw(String changingPkg,
6007            PackageParser.Package pkgInfo, int flags) {
6008        // Make sure there are no dangling permission trees.
6009        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6010        while (it.hasNext()) {
6011            final BasePermission bp = it.next();
6012            if (bp.packageSetting == null) {
6013                // We may not yet have parsed the package, so just see if
6014                // we still know about its settings.
6015                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6016            }
6017            if (bp.packageSetting == null) {
6018                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6019                        + " from package " + bp.sourcePackage);
6020                it.remove();
6021            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6022                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6023                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6024                            + " from package " + bp.sourcePackage);
6025                    flags |= UPDATE_PERMISSIONS_ALL;
6026                    it.remove();
6027                }
6028            }
6029        }
6030
6031        // Make sure all dynamic permissions have been assigned to a package,
6032        // and make sure there are no dangling permissions.
6033        it = mSettings.mPermissions.values().iterator();
6034        while (it.hasNext()) {
6035            final BasePermission bp = it.next();
6036            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6037                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6038                        + bp.name + " pkg=" + bp.sourcePackage
6039                        + " info=" + bp.pendingInfo);
6040                if (bp.packageSetting == null && bp.pendingInfo != null) {
6041                    final BasePermission tree = findPermissionTreeLP(bp.name);
6042                    if (tree != null && tree.perm != null) {
6043                        bp.packageSetting = tree.packageSetting;
6044                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6045                                new PermissionInfo(bp.pendingInfo));
6046                        bp.perm.info.packageName = tree.perm.info.packageName;
6047                        bp.perm.info.name = bp.name;
6048                        bp.uid = tree.uid;
6049                    }
6050                }
6051            }
6052            if (bp.packageSetting == null) {
6053                // We may not yet have parsed the package, so just see if
6054                // we still know about its settings.
6055                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6056            }
6057            if (bp.packageSetting == null) {
6058                Slog.w(TAG, "Removing dangling permission: " + bp.name
6059                        + " from package " + bp.sourcePackage);
6060                it.remove();
6061            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6062                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6063                    Slog.i(TAG, "Removing old permission: " + bp.name
6064                            + " from package " + bp.sourcePackage);
6065                    flags |= UPDATE_PERMISSIONS_ALL;
6066                    it.remove();
6067                }
6068            }
6069        }
6070
6071        // Now update the permissions for all packages, in particular
6072        // replace the granted permissions of the system packages.
6073        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6074            for (PackageParser.Package pkg : mPackages.values()) {
6075                if (pkg != pkgInfo) {
6076                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6077                }
6078            }
6079        }
6080
6081        if (pkgInfo != null) {
6082            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6083        }
6084    }
6085
6086    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6087        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6088        if (ps == null) {
6089            return;
6090        }
6091        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6092        HashSet<String> origPermissions = gp.grantedPermissions;
6093        boolean changedPermission = false;
6094
6095        if (replace) {
6096            ps.permissionsFixed = false;
6097            if (gp == ps) {
6098                origPermissions = new HashSet<String>(gp.grantedPermissions);
6099                gp.grantedPermissions.clear();
6100                gp.gids = mGlobalGids;
6101            }
6102        }
6103
6104        if (gp.gids == null) {
6105            gp.gids = mGlobalGids;
6106        }
6107
6108        final int N = pkg.requestedPermissions.size();
6109        for (int i=0; i<N; i++) {
6110            final String name = pkg.requestedPermissions.get(i);
6111            final boolean required = pkg.requestedPermissionsRequired.get(i);
6112            final BasePermission bp = mSettings.mPermissions.get(name);
6113            if (DEBUG_INSTALL) {
6114                if (gp != ps) {
6115                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6116                }
6117            }
6118
6119            if (bp == null || bp.packageSetting == null) {
6120                Slog.w(TAG, "Unknown permission " + name
6121                        + " in package " + pkg.packageName);
6122                continue;
6123            }
6124
6125            final String perm = bp.name;
6126            boolean allowed;
6127            boolean allowedSig = false;
6128            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6129            if (level == PermissionInfo.PROTECTION_NORMAL
6130                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6131                // We grant a normal or dangerous permission if any of the following
6132                // are true:
6133                // 1) The permission is required
6134                // 2) The permission is optional, but was granted in the past
6135                // 3) The permission is optional, but was requested by an
6136                //    app in /system (not /data)
6137                //
6138                // Otherwise, reject the permission.
6139                allowed = (required || origPermissions.contains(perm)
6140                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6141            } else if (bp.packageSetting == null) {
6142                // This permission is invalid; skip it.
6143                allowed = false;
6144            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6145                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6146                if (allowed) {
6147                    allowedSig = true;
6148                }
6149            } else {
6150                allowed = false;
6151            }
6152            if (DEBUG_INSTALL) {
6153                if (gp != ps) {
6154                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6155                }
6156            }
6157            if (allowed) {
6158                if (!isSystemApp(ps) && ps.permissionsFixed) {
6159                    // If this is an existing, non-system package, then
6160                    // we can't add any new permissions to it.
6161                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6162                        // Except...  if this is a permission that was added
6163                        // to the platform (note: need to only do this when
6164                        // updating the platform).
6165                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6166                    }
6167                }
6168                if (allowed) {
6169                    if (!gp.grantedPermissions.contains(perm)) {
6170                        changedPermission = true;
6171                        gp.grantedPermissions.add(perm);
6172                        gp.gids = appendInts(gp.gids, bp.gids);
6173                    } else if (!ps.haveGids) {
6174                        gp.gids = appendInts(gp.gids, bp.gids);
6175                    }
6176                } else {
6177                    Slog.w(TAG, "Not granting permission " + perm
6178                            + " to package " + pkg.packageName
6179                            + " because it was previously installed without");
6180                }
6181            } else {
6182                if (gp.grantedPermissions.remove(perm)) {
6183                    changedPermission = true;
6184                    gp.gids = removeInts(gp.gids, bp.gids);
6185                    Slog.i(TAG, "Un-granting permission " + perm
6186                            + " from package " + pkg.packageName
6187                            + " (protectionLevel=" + bp.protectionLevel
6188                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6189                            + ")");
6190                } else {
6191                    Slog.w(TAG, "Not granting permission " + perm
6192                            + " to package " + pkg.packageName
6193                            + " (protectionLevel=" + bp.protectionLevel
6194                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6195                            + ")");
6196                }
6197            }
6198        }
6199
6200        if ((changedPermission || replace) && !ps.permissionsFixed &&
6201                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6202            // This is the first that we have heard about this package, so the
6203            // permissions we have now selected are fixed until explicitly
6204            // changed.
6205            ps.permissionsFixed = true;
6206        }
6207        ps.haveGids = true;
6208    }
6209
6210    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6211        boolean allowed = false;
6212        final int NP = PackageParser.NEW_PERMISSIONS.length;
6213        for (int ip=0; ip<NP; ip++) {
6214            final PackageParser.NewPermissionInfo npi
6215                    = PackageParser.NEW_PERMISSIONS[ip];
6216            if (npi.name.equals(perm)
6217                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6218                allowed = true;
6219                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6220                        + pkg.packageName);
6221                break;
6222            }
6223        }
6224        return allowed;
6225    }
6226
6227    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6228                                          BasePermission bp, HashSet<String> origPermissions) {
6229        boolean allowed;
6230        allowed = (compareSignatures(
6231                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6232                        == PackageManager.SIGNATURE_MATCH)
6233                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6234                        == PackageManager.SIGNATURE_MATCH);
6235        if (!allowed && (bp.protectionLevel
6236                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6237            if (isSystemApp(pkg)) {
6238                // For updated system applications, a system permission
6239                // is granted only if it had been defined by the original application.
6240                if (isUpdatedSystemApp(pkg)) {
6241                    final PackageSetting sysPs = mSettings
6242                            .getDisabledSystemPkgLPr(pkg.packageName);
6243                    final GrantedPermissions origGp = sysPs.sharedUser != null
6244                            ? sysPs.sharedUser : sysPs;
6245
6246                    if (origGp.grantedPermissions.contains(perm)) {
6247                        // If the original was granted this permission, we take
6248                        // that grant decision as read and propagate it to the
6249                        // update.
6250                        allowed = true;
6251                    } else {
6252                        // The system apk may have been updated with an older
6253                        // version of the one on the data partition, but which
6254                        // granted a new system permission that it didn't have
6255                        // before.  In this case we do want to allow the app to
6256                        // now get the new permission if the ancestral apk is
6257                        // privileged to get it.
6258                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6259                            for (int j=0;
6260                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6261                                if (perm.equals(
6262                                        sysPs.pkg.requestedPermissions.get(j))) {
6263                                    allowed = true;
6264                                    break;
6265                                }
6266                            }
6267                        }
6268                    }
6269                } else {
6270                    allowed = isPrivilegedApp(pkg);
6271                }
6272            }
6273        }
6274        if (!allowed && (bp.protectionLevel
6275                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6276            // For development permissions, a development permission
6277            // is granted only if it was already granted.
6278            allowed = origPermissions.contains(perm);
6279        }
6280        return allowed;
6281    }
6282
6283    final class ActivityIntentResolver
6284            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6285        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6286                boolean defaultOnly, int userId) {
6287            if (!sUserManager.exists(userId)) return null;
6288            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6289            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6290        }
6291
6292        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6293                int userId) {
6294            if (!sUserManager.exists(userId)) return null;
6295            mFlags = flags;
6296            return super.queryIntent(intent, resolvedType,
6297                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6298        }
6299
6300        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6301                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6302            if (!sUserManager.exists(userId)) return null;
6303            if (packageActivities == null) {
6304                return null;
6305            }
6306            mFlags = flags;
6307            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6308            final int N = packageActivities.size();
6309            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6310                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6311
6312            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6313            for (int i = 0; i < N; ++i) {
6314                intentFilters = packageActivities.get(i).intents;
6315                if (intentFilters != null && intentFilters.size() > 0) {
6316                    PackageParser.ActivityIntentInfo[] array =
6317                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6318                    intentFilters.toArray(array);
6319                    listCut.add(array);
6320                }
6321            }
6322            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6323        }
6324
6325        public final void addActivity(PackageParser.Activity a, String type) {
6326            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6327            mActivities.put(a.getComponentName(), a);
6328            if (DEBUG_SHOW_INFO)
6329                Log.v(
6330                TAG, "  " + type + " " +
6331                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6332            if (DEBUG_SHOW_INFO)
6333                Log.v(TAG, "    Class=" + a.info.name);
6334            final int NI = a.intents.size();
6335            for (int j=0; j<NI; j++) {
6336                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6337                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6338                    intent.setPriority(0);
6339                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6340                            + a.className + " with priority > 0, forcing to 0");
6341                }
6342                if (DEBUG_SHOW_INFO) {
6343                    Log.v(TAG, "    IntentFilter:");
6344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6345                }
6346                if (!intent.debugCheck()) {
6347                    Log.w(TAG, "==> For Activity " + a.info.name);
6348                }
6349                addFilter(intent);
6350            }
6351        }
6352
6353        public final void removeActivity(PackageParser.Activity a, String type) {
6354            mActivities.remove(a.getComponentName());
6355            if (DEBUG_SHOW_INFO) {
6356                Log.v(TAG, "  " + type + " "
6357                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6358                                : a.info.name) + ":");
6359                Log.v(TAG, "    Class=" + a.info.name);
6360            }
6361            final int NI = a.intents.size();
6362            for (int j=0; j<NI; j++) {
6363                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6364                if (DEBUG_SHOW_INFO) {
6365                    Log.v(TAG, "    IntentFilter:");
6366                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6367                }
6368                removeFilter(intent);
6369            }
6370        }
6371
6372        @Override
6373        protected boolean allowFilterResult(
6374                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6375            ActivityInfo filterAi = filter.activity.info;
6376            for (int i=dest.size()-1; i>=0; i--) {
6377                ActivityInfo destAi = dest.get(i).activityInfo;
6378                if (destAi.name == filterAi.name
6379                        && destAi.packageName == filterAi.packageName) {
6380                    return false;
6381                }
6382            }
6383            return true;
6384        }
6385
6386        @Override
6387        protected ActivityIntentInfo[] newArray(int size) {
6388            return new ActivityIntentInfo[size];
6389        }
6390
6391        @Override
6392        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6393            if (!sUserManager.exists(userId)) return true;
6394            PackageParser.Package p = filter.activity.owner;
6395            if (p != null) {
6396                PackageSetting ps = (PackageSetting)p.mExtras;
6397                if (ps != null) {
6398                    // System apps are never considered stopped for purposes of
6399                    // filtering, because there may be no way for the user to
6400                    // actually re-launch them.
6401                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6402                            && ps.getStopped(userId);
6403                }
6404            }
6405            return false;
6406        }
6407
6408        @Override
6409        protected boolean isPackageForFilter(String packageName,
6410                PackageParser.ActivityIntentInfo info) {
6411            return packageName.equals(info.activity.owner.packageName);
6412        }
6413
6414        @Override
6415        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6416                int match, int userId) {
6417            if (!sUserManager.exists(userId)) return null;
6418            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6419                return null;
6420            }
6421            final PackageParser.Activity activity = info.activity;
6422            if (mSafeMode && (activity.info.applicationInfo.flags
6423                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6424                return null;
6425            }
6426            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6427            if (ps == null) {
6428                return null;
6429            }
6430            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6431                    ps.readUserState(userId), userId);
6432            if (ai == null) {
6433                return null;
6434            }
6435            final ResolveInfo res = new ResolveInfo();
6436            res.activityInfo = ai;
6437            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6438                res.filter = info;
6439            }
6440            res.priority = info.getPriority();
6441            res.preferredOrder = activity.owner.mPreferredOrder;
6442            //System.out.println("Result: " + res.activityInfo.className +
6443            //                   " = " + res.priority);
6444            res.match = match;
6445            res.isDefault = info.hasDefault;
6446            res.labelRes = info.labelRes;
6447            res.nonLocalizedLabel = info.nonLocalizedLabel;
6448            res.icon = info.icon;
6449            res.system = isSystemApp(res.activityInfo.applicationInfo);
6450            return res;
6451        }
6452
6453        @Override
6454        protected void sortResults(List<ResolveInfo> results) {
6455            Collections.sort(results, mResolvePrioritySorter);
6456        }
6457
6458        @Override
6459        protected void dumpFilter(PrintWriter out, String prefix,
6460                PackageParser.ActivityIntentInfo filter) {
6461            out.print(prefix); out.print(
6462                    Integer.toHexString(System.identityHashCode(filter.activity)));
6463                    out.print(' ');
6464                    filter.activity.printComponentShortName(out);
6465                    out.print(" filter ");
6466                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6467        }
6468
6469//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6470//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6471//            final List<ResolveInfo> retList = Lists.newArrayList();
6472//            while (i.hasNext()) {
6473//                final ResolveInfo resolveInfo = i.next();
6474//                if (isEnabledLP(resolveInfo.activityInfo)) {
6475//                    retList.add(resolveInfo);
6476//                }
6477//            }
6478//            return retList;
6479//        }
6480
6481        // Keys are String (activity class name), values are Activity.
6482        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6483                = new HashMap<ComponentName, PackageParser.Activity>();
6484        private int mFlags;
6485    }
6486
6487    private final class ServiceIntentResolver
6488            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6489        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6490                boolean defaultOnly, int userId) {
6491            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6492            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6493        }
6494
6495        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6496                int userId) {
6497            if (!sUserManager.exists(userId)) return null;
6498            mFlags = flags;
6499            return super.queryIntent(intent, resolvedType,
6500                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6501        }
6502
6503        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6504                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6505            if (!sUserManager.exists(userId)) return null;
6506            if (packageServices == null) {
6507                return null;
6508            }
6509            mFlags = flags;
6510            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6511            final int N = packageServices.size();
6512            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6513                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6514
6515            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6516            for (int i = 0; i < N; ++i) {
6517                intentFilters = packageServices.get(i).intents;
6518                if (intentFilters != null && intentFilters.size() > 0) {
6519                    PackageParser.ServiceIntentInfo[] array =
6520                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6521                    intentFilters.toArray(array);
6522                    listCut.add(array);
6523                }
6524            }
6525            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6526        }
6527
6528        public final void addService(PackageParser.Service s) {
6529            mServices.put(s.getComponentName(), s);
6530            if (DEBUG_SHOW_INFO) {
6531                Log.v(TAG, "  "
6532                        + (s.info.nonLocalizedLabel != null
6533                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6534                Log.v(TAG, "    Class=" + s.info.name);
6535            }
6536            final int NI = s.intents.size();
6537            int j;
6538            for (j=0; j<NI; j++) {
6539                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6540                if (DEBUG_SHOW_INFO) {
6541                    Log.v(TAG, "    IntentFilter:");
6542                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6543                }
6544                if (!intent.debugCheck()) {
6545                    Log.w(TAG, "==> For Service " + s.info.name);
6546                }
6547                addFilter(intent);
6548            }
6549        }
6550
6551        public final void removeService(PackageParser.Service s) {
6552            mServices.remove(s.getComponentName());
6553            if (DEBUG_SHOW_INFO) {
6554                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6555                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6556                Log.v(TAG, "    Class=" + s.info.name);
6557            }
6558            final int NI = s.intents.size();
6559            int j;
6560            for (j=0; j<NI; j++) {
6561                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6562                if (DEBUG_SHOW_INFO) {
6563                    Log.v(TAG, "    IntentFilter:");
6564                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6565                }
6566                removeFilter(intent);
6567            }
6568        }
6569
6570        @Override
6571        protected boolean allowFilterResult(
6572                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6573            ServiceInfo filterSi = filter.service.info;
6574            for (int i=dest.size()-1; i>=0; i--) {
6575                ServiceInfo destAi = dest.get(i).serviceInfo;
6576                if (destAi.name == filterSi.name
6577                        && destAi.packageName == filterSi.packageName) {
6578                    return false;
6579                }
6580            }
6581            return true;
6582        }
6583
6584        @Override
6585        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6586            return new PackageParser.ServiceIntentInfo[size];
6587        }
6588
6589        @Override
6590        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6591            if (!sUserManager.exists(userId)) return true;
6592            PackageParser.Package p = filter.service.owner;
6593            if (p != null) {
6594                PackageSetting ps = (PackageSetting)p.mExtras;
6595                if (ps != null) {
6596                    // System apps are never considered stopped for purposes of
6597                    // filtering, because there may be no way for the user to
6598                    // actually re-launch them.
6599                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6600                            && ps.getStopped(userId);
6601                }
6602            }
6603            return false;
6604        }
6605
6606        @Override
6607        protected boolean isPackageForFilter(String packageName,
6608                PackageParser.ServiceIntentInfo info) {
6609            return packageName.equals(info.service.owner.packageName);
6610        }
6611
6612        @Override
6613        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6614                int match, int userId) {
6615            if (!sUserManager.exists(userId)) return null;
6616            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6617            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6618                return null;
6619            }
6620            final PackageParser.Service service = info.service;
6621            if (mSafeMode && (service.info.applicationInfo.flags
6622                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6623                return null;
6624            }
6625            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6626            if (ps == null) {
6627                return null;
6628            }
6629            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6630                    ps.readUserState(userId), userId);
6631            if (si == null) {
6632                return null;
6633            }
6634            final ResolveInfo res = new ResolveInfo();
6635            res.serviceInfo = si;
6636            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6637                res.filter = filter;
6638            }
6639            res.priority = info.getPriority();
6640            res.preferredOrder = service.owner.mPreferredOrder;
6641            //System.out.println("Result: " + res.activityInfo.className +
6642            //                   " = " + res.priority);
6643            res.match = match;
6644            res.isDefault = info.hasDefault;
6645            res.labelRes = info.labelRes;
6646            res.nonLocalizedLabel = info.nonLocalizedLabel;
6647            res.icon = info.icon;
6648            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6649            return res;
6650        }
6651
6652        @Override
6653        protected void sortResults(List<ResolveInfo> results) {
6654            Collections.sort(results, mResolvePrioritySorter);
6655        }
6656
6657        @Override
6658        protected void dumpFilter(PrintWriter out, String prefix,
6659                PackageParser.ServiceIntentInfo filter) {
6660            out.print(prefix); out.print(
6661                    Integer.toHexString(System.identityHashCode(filter.service)));
6662                    out.print(' ');
6663                    filter.service.printComponentShortName(out);
6664                    out.print(" filter ");
6665                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6666        }
6667
6668//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6669//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6670//            final List<ResolveInfo> retList = Lists.newArrayList();
6671//            while (i.hasNext()) {
6672//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6673//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6674//                    retList.add(resolveInfo);
6675//                }
6676//            }
6677//            return retList;
6678//        }
6679
6680        // Keys are String (activity class name), values are Activity.
6681        private final HashMap<ComponentName, PackageParser.Service> mServices
6682                = new HashMap<ComponentName, PackageParser.Service>();
6683        private int mFlags;
6684    };
6685
6686    private final class ProviderIntentResolver
6687            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6688        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6689                boolean defaultOnly, int userId) {
6690            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6691            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6692        }
6693
6694        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6695                int userId) {
6696            if (!sUserManager.exists(userId))
6697                return null;
6698            mFlags = flags;
6699            return super.queryIntent(intent, resolvedType,
6700                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6701        }
6702
6703        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6704                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6705            if (!sUserManager.exists(userId))
6706                return null;
6707            if (packageProviders == null) {
6708                return null;
6709            }
6710            mFlags = flags;
6711            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6712            final int N = packageProviders.size();
6713            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6714                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6715
6716            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6717            for (int i = 0; i < N; ++i) {
6718                intentFilters = packageProviders.get(i).intents;
6719                if (intentFilters != null && intentFilters.size() > 0) {
6720                    PackageParser.ProviderIntentInfo[] array =
6721                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6722                    intentFilters.toArray(array);
6723                    listCut.add(array);
6724                }
6725            }
6726            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6727        }
6728
6729        public final void addProvider(PackageParser.Provider p) {
6730            if (mProviders.containsKey(p.getComponentName())) {
6731                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6732                return;
6733            }
6734
6735            mProviders.put(p.getComponentName(), p);
6736            if (DEBUG_SHOW_INFO) {
6737                Log.v(TAG, "  "
6738                        + (p.info.nonLocalizedLabel != null
6739                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6740                Log.v(TAG, "    Class=" + p.info.name);
6741            }
6742            final int NI = p.intents.size();
6743            int j;
6744            for (j = 0; j < NI; j++) {
6745                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6746                if (DEBUG_SHOW_INFO) {
6747                    Log.v(TAG, "    IntentFilter:");
6748                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6749                }
6750                if (!intent.debugCheck()) {
6751                    Log.w(TAG, "==> For Provider " + p.info.name);
6752                }
6753                addFilter(intent);
6754            }
6755        }
6756
6757        public final void removeProvider(PackageParser.Provider p) {
6758            mProviders.remove(p.getComponentName());
6759            if (DEBUG_SHOW_INFO) {
6760                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6761                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6762                Log.v(TAG, "    Class=" + p.info.name);
6763            }
6764            final int NI = p.intents.size();
6765            int j;
6766            for (j = 0; j < NI; j++) {
6767                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6768                if (DEBUG_SHOW_INFO) {
6769                    Log.v(TAG, "    IntentFilter:");
6770                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6771                }
6772                removeFilter(intent);
6773            }
6774        }
6775
6776        @Override
6777        protected boolean allowFilterResult(
6778                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6779            ProviderInfo filterPi = filter.provider.info;
6780            for (int i = dest.size() - 1; i >= 0; i--) {
6781                ProviderInfo destPi = dest.get(i).providerInfo;
6782                if (destPi.name == filterPi.name
6783                        && destPi.packageName == filterPi.packageName) {
6784                    return false;
6785                }
6786            }
6787            return true;
6788        }
6789
6790        @Override
6791        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6792            return new PackageParser.ProviderIntentInfo[size];
6793        }
6794
6795        @Override
6796        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6797            if (!sUserManager.exists(userId))
6798                return true;
6799            PackageParser.Package p = filter.provider.owner;
6800            if (p != null) {
6801                PackageSetting ps = (PackageSetting) p.mExtras;
6802                if (ps != null) {
6803                    // System apps are never considered stopped for purposes of
6804                    // filtering, because there may be no way for the user to
6805                    // actually re-launch them.
6806                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6807                            && ps.getStopped(userId);
6808                }
6809            }
6810            return false;
6811        }
6812
6813        @Override
6814        protected boolean isPackageForFilter(String packageName,
6815                PackageParser.ProviderIntentInfo info) {
6816            return packageName.equals(info.provider.owner.packageName);
6817        }
6818
6819        @Override
6820        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6821                int match, int userId) {
6822            if (!sUserManager.exists(userId))
6823                return null;
6824            final PackageParser.ProviderIntentInfo info = filter;
6825            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6826                return null;
6827            }
6828            final PackageParser.Provider provider = info.provider;
6829            if (mSafeMode && (provider.info.applicationInfo.flags
6830                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6831                return null;
6832            }
6833            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6834            if (ps == null) {
6835                return null;
6836            }
6837            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6838                    ps.readUserState(userId), userId);
6839            if (pi == null) {
6840                return null;
6841            }
6842            final ResolveInfo res = new ResolveInfo();
6843            res.providerInfo = pi;
6844            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6845                res.filter = filter;
6846            }
6847            res.priority = info.getPriority();
6848            res.preferredOrder = provider.owner.mPreferredOrder;
6849            res.match = match;
6850            res.isDefault = info.hasDefault;
6851            res.labelRes = info.labelRes;
6852            res.nonLocalizedLabel = info.nonLocalizedLabel;
6853            res.icon = info.icon;
6854            res.system = isSystemApp(res.providerInfo.applicationInfo);
6855            return res;
6856        }
6857
6858        @Override
6859        protected void sortResults(List<ResolveInfo> results) {
6860            Collections.sort(results, mResolvePrioritySorter);
6861        }
6862
6863        @Override
6864        protected void dumpFilter(PrintWriter out, String prefix,
6865                PackageParser.ProviderIntentInfo filter) {
6866            out.print(prefix);
6867            out.print(
6868                    Integer.toHexString(System.identityHashCode(filter.provider)));
6869            out.print(' ');
6870            filter.provider.printComponentShortName(out);
6871            out.print(" filter ");
6872            out.println(Integer.toHexString(System.identityHashCode(filter)));
6873        }
6874
6875        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6876                = new HashMap<ComponentName, PackageParser.Provider>();
6877        private int mFlags;
6878    };
6879
6880    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6881            new Comparator<ResolveInfo>() {
6882        public int compare(ResolveInfo r1, ResolveInfo r2) {
6883            int v1 = r1.priority;
6884            int v2 = r2.priority;
6885            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6886            if (v1 != v2) {
6887                return (v1 > v2) ? -1 : 1;
6888            }
6889            v1 = r1.preferredOrder;
6890            v2 = r2.preferredOrder;
6891            if (v1 != v2) {
6892                return (v1 > v2) ? -1 : 1;
6893            }
6894            if (r1.isDefault != r2.isDefault) {
6895                return r1.isDefault ? -1 : 1;
6896            }
6897            v1 = r1.match;
6898            v2 = r2.match;
6899            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6900            if (v1 != v2) {
6901                return (v1 > v2) ? -1 : 1;
6902            }
6903            if (r1.system != r2.system) {
6904                return r1.system ? -1 : 1;
6905            }
6906            return 0;
6907        }
6908    };
6909
6910    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6911            new Comparator<ProviderInfo>() {
6912        public int compare(ProviderInfo p1, ProviderInfo p2) {
6913            final int v1 = p1.initOrder;
6914            final int v2 = p2.initOrder;
6915            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6916        }
6917    };
6918
6919    static final void sendPackageBroadcast(String action, String pkg,
6920            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6921            int[] userIds) {
6922        IActivityManager am = ActivityManagerNative.getDefault();
6923        if (am != null) {
6924            try {
6925                if (userIds == null) {
6926                    userIds = am.getRunningUserIds();
6927                }
6928                for (int id : userIds) {
6929                    final Intent intent = new Intent(action,
6930                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6931                    if (extras != null) {
6932                        intent.putExtras(extras);
6933                    }
6934                    if (targetPkg != null) {
6935                        intent.setPackage(targetPkg);
6936                    }
6937                    // Modify the UID when posting to other users
6938                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6939                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6940                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6941                        intent.putExtra(Intent.EXTRA_UID, uid);
6942                    }
6943                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6944                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6945                    if (DEBUG_BROADCASTS) {
6946                        RuntimeException here = new RuntimeException("here");
6947                        here.fillInStackTrace();
6948                        Slog.d(TAG, "Sending to user " + id + ": "
6949                                + intent.toShortString(false, true, false, false)
6950                                + " " + intent.getExtras(), here);
6951                    }
6952                    am.broadcastIntent(null, intent, null, finishedReceiver,
6953                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6954                            finishedReceiver != null, false, id);
6955                }
6956            } catch (RemoteException ex) {
6957            }
6958        }
6959    }
6960
6961    /**
6962     * Check if the external storage media is available. This is true if there
6963     * is a mounted external storage medium or if the external storage is
6964     * emulated.
6965     */
6966    private boolean isExternalMediaAvailable() {
6967        return mMediaMounted || Environment.isExternalStorageEmulated();
6968    }
6969
6970    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6971        // writer
6972        synchronized (mPackages) {
6973            if (!isExternalMediaAvailable()) {
6974                // If the external storage is no longer mounted at this point,
6975                // the caller may not have been able to delete all of this
6976                // packages files and can not delete any more.  Bail.
6977                return null;
6978            }
6979            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6980            if (lastPackage != null) {
6981                pkgs.remove(lastPackage);
6982            }
6983            if (pkgs.size() > 0) {
6984                return pkgs.get(0);
6985            }
6986        }
6987        return null;
6988    }
6989
6990    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6991        if (false) {
6992            RuntimeException here = new RuntimeException("here");
6993            here.fillInStackTrace();
6994            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6995                    + " andCode=" + andCode, here);
6996        }
6997        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6998                userId, andCode ? 1 : 0, packageName));
6999    }
7000
7001    void startCleaningPackages() {
7002        // reader
7003        synchronized (mPackages) {
7004            if (!isExternalMediaAvailable()) {
7005                return;
7006            }
7007            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7008                return;
7009            }
7010        }
7011        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7012        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7013        IActivityManager am = ActivityManagerNative.getDefault();
7014        if (am != null) {
7015            try {
7016                am.startService(null, intent, null, UserHandle.USER_OWNER);
7017            } catch (RemoteException e) {
7018            }
7019        }
7020    }
7021
7022    private final class AppDirObserver extends FileObserver {
7023        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7024            super(path, mask);
7025            mRootDir = path;
7026            mIsRom = isrom;
7027            mIsPrivileged = isPrivileged;
7028        }
7029
7030        public void onEvent(int event, String path) {
7031            String removedPackage = null;
7032            int removedAppId = -1;
7033            int[] removedUsers = null;
7034            String addedPackage = null;
7035            int addedAppId = -1;
7036            int[] addedUsers = null;
7037
7038            // TODO post a message to the handler to obtain serial ordering
7039            synchronized (mInstallLock) {
7040                String fullPathStr = null;
7041                File fullPath = null;
7042                if (path != null) {
7043                    fullPath = new File(mRootDir, path);
7044                    fullPathStr = fullPath.getPath();
7045                }
7046
7047                if (DEBUG_APP_DIR_OBSERVER)
7048                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7049
7050                if (!isPackageFilename(path)) {
7051                    if (DEBUG_APP_DIR_OBSERVER)
7052                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7053                    return;
7054                }
7055
7056                // Ignore packages that are being installed or
7057                // have just been installed.
7058                if (ignoreCodePath(fullPathStr)) {
7059                    return;
7060                }
7061                PackageParser.Package p = null;
7062                PackageSetting ps = null;
7063                // reader
7064                synchronized (mPackages) {
7065                    p = mAppDirs.get(fullPathStr);
7066                    if (p != null) {
7067                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7068                        if (ps != null) {
7069                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7070                        } else {
7071                            removedUsers = sUserManager.getUserIds();
7072                        }
7073                    }
7074                    addedUsers = sUserManager.getUserIds();
7075                }
7076                if ((event&REMOVE_EVENTS) != 0) {
7077                    if (ps != null) {
7078                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7079                        removePackageLI(ps, true);
7080                        removedPackage = ps.name;
7081                        removedAppId = ps.appId;
7082                    }
7083                }
7084
7085                if ((event&ADD_EVENTS) != 0) {
7086                    if (p == null) {
7087                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7088                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7089                        if (mIsRom) {
7090                            flags |= PackageParser.PARSE_IS_SYSTEM
7091                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7092                            if (mIsPrivileged) {
7093                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7094                            }
7095                        }
7096                        p = scanPackageLI(fullPath, flags,
7097                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7098                                System.currentTimeMillis(), UserHandle.ALL);
7099                        if (p != null) {
7100                            /*
7101                             * TODO this seems dangerous as the package may have
7102                             * changed since we last acquired the mPackages
7103                             * lock.
7104                             */
7105                            // writer
7106                            synchronized (mPackages) {
7107                                updatePermissionsLPw(p.packageName, p,
7108                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7109                            }
7110                            addedPackage = p.applicationInfo.packageName;
7111                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7112                        }
7113                    }
7114                }
7115
7116                // reader
7117                synchronized (mPackages) {
7118                    mSettings.writeLPr();
7119                }
7120            }
7121
7122            if (removedPackage != null) {
7123                Bundle extras = new Bundle(1);
7124                extras.putInt(Intent.EXTRA_UID, removedAppId);
7125                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7126                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7127                        extras, null, null, removedUsers);
7128            }
7129            if (addedPackage != null) {
7130                Bundle extras = new Bundle(1);
7131                extras.putInt(Intent.EXTRA_UID, addedAppId);
7132                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7133                        extras, null, null, addedUsers);
7134            }
7135        }
7136
7137        private final String mRootDir;
7138        private final boolean mIsRom;
7139        private final boolean mIsPrivileged;
7140    }
7141
7142    /*
7143     * The old-style observer methods all just trampoline to the newer signature with
7144     * expanded install observer API.  The older API continues to work but does not
7145     * supply the additional details of the Observer2 API.
7146     */
7147
7148    /* Called when a downloaded package installation has been confirmed by the user */
7149    public void installPackage(
7150            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7151        installPackageEtc(packageURI, observer, null, flags, null);
7152    }
7153
7154    /* Called when a downloaded package installation has been confirmed by the user */
7155    public void installPackage(
7156            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7157            final String installerPackageName) {
7158        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7159                installerPackageName, null, null, null);
7160    }
7161
7162    @Override
7163    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7164            int flags, String installerPackageName, Uri verificationURI,
7165            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7166        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7167                VerificationParams.NO_UID, manifestDigest);
7168        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7169                installerPackageName, verificationParams, encryptionParams);
7170    }
7171
7172    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7173            IPackageInstallObserver observer, int flags, String installerPackageName,
7174            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7175        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7176                installerPackageName, verificationParams, encryptionParams);
7177    }
7178
7179    /*
7180     * And here are the "live" versions that take both observer arguments
7181     */
7182    public void installPackageEtc(
7183            final Uri packageURI, final IPackageInstallObserver observer,
7184            IPackageInstallObserver2 observer2, final int flags) {
7185        installPackageEtc(packageURI, observer, observer2, flags, null);
7186    }
7187
7188    public void installPackageEtc(
7189            final Uri packageURI, final IPackageInstallObserver observer,
7190            final IPackageInstallObserver2 observer2, final int flags,
7191            final String installerPackageName) {
7192        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7193                installerPackageName, null, null, null);
7194    }
7195
7196    @Override
7197    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7198            IPackageInstallObserver2 observer2,
7199            int flags, String installerPackageName, Uri verificationURI,
7200            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7201        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7202                VerificationParams.NO_UID, manifestDigest);
7203        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7204                installerPackageName, verificationParams, encryptionParams);
7205    }
7206
7207    /*
7208     * All of the installPackage...*() methods redirect to this one for the master implementation
7209     */
7210    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7211            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7212            int flags, String installerPackageName,
7213            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7214        if (observer == null && observer2 == null) {
7215            throw new IllegalArgumentException("No install observer supplied");
7216        }
7217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7218                null);
7219
7220        final int uid = Binder.getCallingUid();
7221        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7222            try {
7223                if (observer != null) {
7224                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7225                }
7226                if (observer2 != null) {
7227                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7228                }
7229            } catch (RemoteException re) {
7230            }
7231            return;
7232        }
7233
7234        UserHandle user;
7235        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7236            user = UserHandle.ALL;
7237        } else {
7238            user = new UserHandle(UserHandle.getUserId(uid));
7239        }
7240
7241        final int filteredFlags;
7242
7243        if (uid == Process.SHELL_UID || uid == 0) {
7244            if (DEBUG_INSTALL) {
7245                Slog.v(TAG, "Install from ADB");
7246            }
7247            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7248        } else {
7249            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7250        }
7251
7252        verificationParams.setInstallerUid(uid);
7253
7254        final Message msg = mHandler.obtainMessage(INIT_COPY);
7255        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7256                installerPackageName, verificationParams, encryptionParams, user);
7257        mHandler.sendMessage(msg);
7258    }
7259
7260    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7261        Bundle extras = new Bundle(1);
7262        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7263
7264        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7265                packageName, extras, null, null, new int[] {userId});
7266        try {
7267            IActivityManager am = ActivityManagerNative.getDefault();
7268            final boolean isSystem =
7269                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7270            if (isSystem && am.isUserRunning(userId, false)) {
7271                // The just-installed/enabled app is bundled on the system, so presumed
7272                // to be able to run automatically without needing an explicit launch.
7273                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7274                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7275                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7276                        .setPackage(packageName);
7277                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7278                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7279            }
7280        } catch (RemoteException e) {
7281            // shouldn't happen
7282            Slog.w(TAG, "Unable to bootstrap installed package", e);
7283        }
7284    }
7285
7286    @Override
7287    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7288            int userId) {
7289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7290        PackageSetting pkgSetting;
7291        final int uid = Binder.getCallingUid();
7292        if (UserHandle.getUserId(uid) != userId) {
7293            mContext.enforceCallingOrSelfPermission(
7294                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7295                    "setApplicationBlockedSetting for user " + userId);
7296        }
7297
7298        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7299            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7300            return false;
7301        }
7302
7303        long callingId = Binder.clearCallingIdentity();
7304        try {
7305            boolean sendAdded = false;
7306            boolean sendRemoved = false;
7307            // writer
7308            synchronized (mPackages) {
7309                pkgSetting = mSettings.mPackages.get(packageName);
7310                if (pkgSetting == null) {
7311                    return false;
7312                }
7313                if (pkgSetting.getBlocked(userId) != blocked) {
7314                    pkgSetting.setBlocked(blocked, userId);
7315                    mSettings.writePackageRestrictionsLPr(userId);
7316                    if (blocked) {
7317                        sendRemoved = true;
7318                    } else {
7319                        sendAdded = true;
7320                    }
7321                }
7322            }
7323            if (sendAdded) {
7324                sendPackageAddedForUser(packageName, pkgSetting, userId);
7325                return true;
7326            }
7327            if (sendRemoved) {
7328                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7329                        "blocking pkg");
7330                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7331            }
7332        } finally {
7333            Binder.restoreCallingIdentity(callingId);
7334        }
7335        return false;
7336    }
7337
7338    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7339            int userId) {
7340        final PackageRemovedInfo info = new PackageRemovedInfo();
7341        info.removedPackage = packageName;
7342        info.removedUsers = new int[] {userId};
7343        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7344        info.sendBroadcast(false, false, false);
7345    }
7346
7347    /**
7348     * Returns true if application is not found or there was an error. Otherwise it returns
7349     * the blocked state of the package for the given user.
7350     */
7351    @Override
7352    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7353        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7354        PackageSetting pkgSetting;
7355        final int uid = Binder.getCallingUid();
7356        if (UserHandle.getUserId(uid) != userId) {
7357            mContext.enforceCallingPermission(
7358                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7359                    "getApplicationBlocked for user " + userId);
7360        }
7361        long callingId = Binder.clearCallingIdentity();
7362        try {
7363            // writer
7364            synchronized (mPackages) {
7365                pkgSetting = mSettings.mPackages.get(packageName);
7366                if (pkgSetting == null) {
7367                    return true;
7368                }
7369                return pkgSetting.getBlocked(userId);
7370            }
7371        } finally {
7372            Binder.restoreCallingIdentity(callingId);
7373        }
7374    }
7375
7376    /**
7377     * @hide
7378     */
7379    @Override
7380    public int installExistingPackageAsUser(String packageName, int userId) {
7381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7382                null);
7383        PackageSetting pkgSetting;
7384        final int uid = Binder.getCallingUid();
7385        if (UserHandle.getUserId(uid) != userId) {
7386            mContext.enforceCallingPermission(
7387                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7388                    "installExistingPackage for user " + userId);
7389        }
7390        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7391            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7392        }
7393
7394        long callingId = Binder.clearCallingIdentity();
7395        try {
7396            boolean sendAdded = false;
7397            Bundle extras = new Bundle(1);
7398
7399            // writer
7400            synchronized (mPackages) {
7401                pkgSetting = mSettings.mPackages.get(packageName);
7402                if (pkgSetting == null) {
7403                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7404                }
7405                if (!pkgSetting.getInstalled(userId)) {
7406                    pkgSetting.setInstalled(true, userId);
7407                    pkgSetting.setBlocked(false, userId);
7408                    mSettings.writePackageRestrictionsLPr(userId);
7409                    sendAdded = true;
7410                }
7411            }
7412
7413            if (sendAdded) {
7414                sendPackageAddedForUser(packageName, pkgSetting, userId);
7415            }
7416        } finally {
7417            Binder.restoreCallingIdentity(callingId);
7418        }
7419
7420        return PackageManager.INSTALL_SUCCEEDED;
7421    }
7422
7423    private boolean isUserRestricted(int userId, String restrictionKey) {
7424        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7425        if (restrictions.getBoolean(restrictionKey, false)) {
7426            Log.w(TAG, "User is restricted: " + restrictionKey);
7427            return true;
7428        }
7429        return false;
7430    }
7431
7432    @Override
7433    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7434        mContext.enforceCallingOrSelfPermission(
7435                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7436                "Only package verification agents can verify applications");
7437
7438        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7439        final PackageVerificationResponse response = new PackageVerificationResponse(
7440                verificationCode, Binder.getCallingUid());
7441        msg.arg1 = id;
7442        msg.obj = response;
7443        mHandler.sendMessage(msg);
7444    }
7445
7446    @Override
7447    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7448            long millisecondsToDelay) {
7449        mContext.enforceCallingOrSelfPermission(
7450                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7451                "Only package verification agents can extend verification timeouts");
7452
7453        final PackageVerificationState state = mPendingVerification.get(id);
7454        final PackageVerificationResponse response = new PackageVerificationResponse(
7455                verificationCodeAtTimeout, Binder.getCallingUid());
7456
7457        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7458            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7459        }
7460        if (millisecondsToDelay < 0) {
7461            millisecondsToDelay = 0;
7462        }
7463        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7464                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7465            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7466        }
7467
7468        if ((state != null) && !state.timeoutExtended()) {
7469            state.extendTimeout();
7470
7471            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7472            msg.arg1 = id;
7473            msg.obj = response;
7474            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7475        }
7476    }
7477
7478    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7479            int verificationCode, UserHandle user) {
7480        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7481        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7482        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7483        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7484        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7485
7486        mContext.sendBroadcastAsUser(intent, user,
7487                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7488    }
7489
7490    private ComponentName matchComponentForVerifier(String packageName,
7491            List<ResolveInfo> receivers) {
7492        ActivityInfo targetReceiver = null;
7493
7494        final int NR = receivers.size();
7495        for (int i = 0; i < NR; i++) {
7496            final ResolveInfo info = receivers.get(i);
7497            if (info.activityInfo == null) {
7498                continue;
7499            }
7500
7501            if (packageName.equals(info.activityInfo.packageName)) {
7502                targetReceiver = info.activityInfo;
7503                break;
7504            }
7505        }
7506
7507        if (targetReceiver == null) {
7508            return null;
7509        }
7510
7511        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7512    }
7513
7514    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7515            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7516        if (pkgInfo.verifiers.length == 0) {
7517            return null;
7518        }
7519
7520        final int N = pkgInfo.verifiers.length;
7521        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7522        for (int i = 0; i < N; i++) {
7523            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7524
7525            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7526                    receivers);
7527            if (comp == null) {
7528                continue;
7529            }
7530
7531            final int verifierUid = getUidForVerifier(verifierInfo);
7532            if (verifierUid == -1) {
7533                continue;
7534            }
7535
7536            if (DEBUG_VERIFY) {
7537                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7538                        + " with the correct signature");
7539            }
7540            sufficientVerifiers.add(comp);
7541            verificationState.addSufficientVerifier(verifierUid);
7542        }
7543
7544        return sufficientVerifiers;
7545    }
7546
7547    private int getUidForVerifier(VerifierInfo verifierInfo) {
7548        synchronized (mPackages) {
7549            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7550            if (pkg == null) {
7551                return -1;
7552            } else if (pkg.mSignatures.length != 1) {
7553                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7554                        + " has more than one signature; ignoring");
7555                return -1;
7556            }
7557
7558            /*
7559             * If the public key of the package's signature does not match
7560             * our expected public key, then this is a different package and
7561             * we should skip.
7562             */
7563
7564            final byte[] expectedPublicKey;
7565            try {
7566                final Signature verifierSig = pkg.mSignatures[0];
7567                final PublicKey publicKey = verifierSig.getPublicKey();
7568                expectedPublicKey = publicKey.getEncoded();
7569            } catch (CertificateException e) {
7570                return -1;
7571            }
7572
7573            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7574
7575            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7576                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7577                        + " does not have the expected public key; ignoring");
7578                return -1;
7579            }
7580
7581            return pkg.applicationInfo.uid;
7582        }
7583    }
7584
7585    public void finishPackageInstall(int token) {
7586        enforceSystemOrRoot("Only the system is allowed to finish installs");
7587
7588        if (DEBUG_INSTALL) {
7589            Slog.v(TAG, "BM finishing package install for " + token);
7590        }
7591
7592        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7593        mHandler.sendMessage(msg);
7594    }
7595
7596    /**
7597     * Get the verification agent timeout.
7598     *
7599     * @return verification timeout in milliseconds
7600     */
7601    private long getVerificationTimeout() {
7602        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7603                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7604                DEFAULT_VERIFICATION_TIMEOUT);
7605    }
7606
7607    /**
7608     * Get the default verification agent response code.
7609     *
7610     * @return default verification response code
7611     */
7612    private int getDefaultVerificationResponse() {
7613        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7614                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7615                DEFAULT_VERIFICATION_RESPONSE);
7616    }
7617
7618    /**
7619     * Check whether or not package verification has been enabled.
7620     *
7621     * @return true if verification should be performed
7622     */
7623    private boolean isVerificationEnabled(int flags) {
7624        if (!DEFAULT_VERIFY_ENABLE) {
7625            return false;
7626        }
7627
7628        // Check if installing from ADB
7629        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7630            // Do not run verification in a test harness environment
7631            if (ActivityManager.isRunningInTestHarness()) {
7632                return false;
7633            }
7634            // Check if the developer does not want package verification for ADB installs
7635            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7636                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7637                return false;
7638            }
7639        }
7640
7641        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7642                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7643    }
7644
7645    /**
7646     * Get the "allow unknown sources" setting.
7647     *
7648     * @return the current "allow unknown sources" setting
7649     */
7650    private int getUnknownSourcesSettings() {
7651        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7652                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7653                -1);
7654    }
7655
7656    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7657        final int uid = Binder.getCallingUid();
7658        // writer
7659        synchronized (mPackages) {
7660            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7661            if (targetPackageSetting == null) {
7662                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7663            }
7664
7665            PackageSetting installerPackageSetting;
7666            if (installerPackageName != null) {
7667                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7668                if (installerPackageSetting == null) {
7669                    throw new IllegalArgumentException("Unknown installer package: "
7670                            + installerPackageName);
7671                }
7672            } else {
7673                installerPackageSetting = null;
7674            }
7675
7676            Signature[] callerSignature;
7677            Object obj = mSettings.getUserIdLPr(uid);
7678            if (obj != null) {
7679                if (obj instanceof SharedUserSetting) {
7680                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7681                } else if (obj instanceof PackageSetting) {
7682                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7683                } else {
7684                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7685                }
7686            } else {
7687                throw new SecurityException("Unknown calling uid " + uid);
7688            }
7689
7690            // Verify: can't set installerPackageName to a package that is
7691            // not signed with the same cert as the caller.
7692            if (installerPackageSetting != null) {
7693                if (compareSignatures(callerSignature,
7694                        installerPackageSetting.signatures.mSignatures)
7695                        != PackageManager.SIGNATURE_MATCH) {
7696                    throw new SecurityException(
7697                            "Caller does not have same cert as new installer package "
7698                            + installerPackageName);
7699                }
7700            }
7701
7702            // Verify: if target already has an installer package, it must
7703            // be signed with the same cert as the caller.
7704            if (targetPackageSetting.installerPackageName != null) {
7705                PackageSetting setting = mSettings.mPackages.get(
7706                        targetPackageSetting.installerPackageName);
7707                // If the currently set package isn't valid, then it's always
7708                // okay to change it.
7709                if (setting != null) {
7710                    if (compareSignatures(callerSignature,
7711                            setting.signatures.mSignatures)
7712                            != PackageManager.SIGNATURE_MATCH) {
7713                        throw new SecurityException(
7714                                "Caller does not have same cert as old installer package "
7715                                + targetPackageSetting.installerPackageName);
7716                    }
7717                }
7718            }
7719
7720            // Okay!
7721            targetPackageSetting.installerPackageName = installerPackageName;
7722            scheduleWriteSettingsLocked();
7723        }
7724    }
7725
7726    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7727        // Queue up an async operation since the package installation may take a little while.
7728        mHandler.post(new Runnable() {
7729            public void run() {
7730                mHandler.removeCallbacks(this);
7731                 // Result object to be returned
7732                PackageInstalledInfo res = new PackageInstalledInfo();
7733                res.returnCode = currentStatus;
7734                res.uid = -1;
7735                res.pkg = null;
7736                res.removedInfo = new PackageRemovedInfo();
7737                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7738                    args.doPreInstall(res.returnCode);
7739                    synchronized (mInstallLock) {
7740                        installPackageLI(args, true, res);
7741                    }
7742                    args.doPostInstall(res.returnCode, res.uid);
7743                }
7744
7745                // A restore should be performed at this point if (a) the install
7746                // succeeded, (b) the operation is not an update, and (c) the new
7747                // package has a backupAgent defined.
7748                final boolean update = res.removedInfo.removedPackage != null;
7749                boolean doRestore = (!update
7750                        && res.pkg != null
7751                        && res.pkg.applicationInfo.backupAgentName != null);
7752
7753                // Set up the post-install work request bookkeeping.  This will be used
7754                // and cleaned up by the post-install event handling regardless of whether
7755                // there's a restore pass performed.  Token values are >= 1.
7756                int token;
7757                if (mNextInstallToken < 0) mNextInstallToken = 1;
7758                token = mNextInstallToken++;
7759
7760                PostInstallData data = new PostInstallData(args, res);
7761                mRunningInstalls.put(token, data);
7762                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7763
7764                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7765                    // Pass responsibility to the Backup Manager.  It will perform a
7766                    // restore if appropriate, then pass responsibility back to the
7767                    // Package Manager to run the post-install observer callbacks
7768                    // and broadcasts.
7769                    IBackupManager bm = IBackupManager.Stub.asInterface(
7770                            ServiceManager.getService(Context.BACKUP_SERVICE));
7771                    if (bm != null) {
7772                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7773                                + " to BM for possible restore");
7774                        try {
7775                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7776                        } catch (RemoteException e) {
7777                            // can't happen; the backup manager is local
7778                        } catch (Exception e) {
7779                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7780                            doRestore = false;
7781                        }
7782                    } else {
7783                        Slog.e(TAG, "Backup Manager not found!");
7784                        doRestore = false;
7785                    }
7786                }
7787
7788                if (!doRestore) {
7789                    // No restore possible, or the Backup Manager was mysteriously not
7790                    // available -- just fire the post-install work request directly.
7791                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7792                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7793                    mHandler.sendMessage(msg);
7794                }
7795            }
7796        });
7797    }
7798
7799    private abstract class HandlerParams {
7800        private static final int MAX_RETRIES = 4;
7801
7802        /**
7803         * Number of times startCopy() has been attempted and had a non-fatal
7804         * error.
7805         */
7806        private int mRetries = 0;
7807
7808        /** User handle for the user requesting the information or installation. */
7809        private final UserHandle mUser;
7810
7811        HandlerParams(UserHandle user) {
7812            mUser = user;
7813        }
7814
7815        UserHandle getUser() {
7816            return mUser;
7817        }
7818
7819        final boolean startCopy() {
7820            boolean res;
7821            try {
7822                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7823
7824                if (++mRetries > MAX_RETRIES) {
7825                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7826                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7827                    handleServiceError();
7828                    return false;
7829                } else {
7830                    handleStartCopy();
7831                    res = true;
7832                }
7833            } catch (RemoteException e) {
7834                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7835                mHandler.sendEmptyMessage(MCS_RECONNECT);
7836                res = false;
7837            }
7838            handleReturnCode();
7839            return res;
7840        }
7841
7842        final void serviceError() {
7843            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7844            handleServiceError();
7845            handleReturnCode();
7846        }
7847
7848        abstract void handleStartCopy() throws RemoteException;
7849        abstract void handleServiceError();
7850        abstract void handleReturnCode();
7851    }
7852
7853    class MeasureParams extends HandlerParams {
7854        private final PackageStats mStats;
7855        private boolean mSuccess;
7856
7857        private final IPackageStatsObserver mObserver;
7858
7859        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7860            super(new UserHandle(stats.userHandle));
7861            mObserver = observer;
7862            mStats = stats;
7863        }
7864
7865        @Override
7866        public String toString() {
7867            return "MeasureParams{"
7868                + Integer.toHexString(System.identityHashCode(this))
7869                + " " + mStats.packageName + "}";
7870        }
7871
7872        @Override
7873        void handleStartCopy() throws RemoteException {
7874            synchronized (mInstallLock) {
7875                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7876            }
7877
7878            if (mSuccess) {
7879                final boolean mounted;
7880                if (Environment.isExternalStorageEmulated()) {
7881                    mounted = true;
7882                } else {
7883                    final String status = Environment.getExternalStorageState();
7884                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
7885                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7886                }
7887
7888                if (mounted) {
7889                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7890
7891                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7892                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7893
7894                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
7895                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7896
7897                    // Always subtract cache size, since it's a subdirectory
7898                    mStats.externalDataSize -= mStats.externalCacheSize;
7899
7900                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7901                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7902
7903                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
7904                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7905                }
7906            }
7907        }
7908
7909        @Override
7910        void handleReturnCode() {
7911            if (mObserver != null) {
7912                try {
7913                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7914                } catch (RemoteException e) {
7915                    Slog.i(TAG, "Observer no longer exists.");
7916                }
7917            }
7918        }
7919
7920        @Override
7921        void handleServiceError() {
7922            Slog.e(TAG, "Could not measure application " + mStats.packageName
7923                            + " external storage");
7924        }
7925    }
7926
7927    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7928            throws RemoteException {
7929        long result = 0;
7930        for (File path : paths) {
7931            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7932        }
7933        return result;
7934    }
7935
7936    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7937        for (File path : paths) {
7938            try {
7939                mcs.clearDirectory(path.getAbsolutePath());
7940            } catch (RemoteException e) {
7941            }
7942        }
7943    }
7944
7945    class InstallParams extends HandlerParams {
7946        final IPackageInstallObserver observer;
7947        final IPackageInstallObserver2 observer2;
7948        int flags;
7949
7950        private final Uri mPackageURI;
7951        final String installerPackageName;
7952        final VerificationParams verificationParams;
7953        private InstallArgs mArgs;
7954        private int mRet;
7955        private File mTempPackage;
7956        final ContainerEncryptionParams encryptionParams;
7957
7958        InstallParams(Uri packageURI,
7959                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7960                int flags, String installerPackageName, VerificationParams verificationParams,
7961                ContainerEncryptionParams encryptionParams, UserHandle user) {
7962            super(user);
7963            this.mPackageURI = packageURI;
7964            this.flags = flags;
7965            this.observer = observer;
7966            this.observer2 = observer2;
7967            this.installerPackageName = installerPackageName;
7968            this.verificationParams = verificationParams;
7969            this.encryptionParams = encryptionParams;
7970        }
7971
7972        @Override
7973        public String toString() {
7974            return "InstallParams{"
7975                + Integer.toHexString(System.identityHashCode(this))
7976                + " " + mPackageURI + "}";
7977        }
7978
7979        public ManifestDigest getManifestDigest() {
7980            if (verificationParams == null) {
7981                return null;
7982            }
7983            return verificationParams.getManifestDigest();
7984        }
7985
7986        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7987            String packageName = pkgLite.packageName;
7988            int installLocation = pkgLite.installLocation;
7989            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7990            // reader
7991            synchronized (mPackages) {
7992                PackageParser.Package pkg = mPackages.get(packageName);
7993                if (pkg != null) {
7994                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7995                        // Check for downgrading.
7996                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7997                            if (pkgLite.versionCode < pkg.mVersionCode) {
7998                                Slog.w(TAG, "Can't install update of " + packageName
7999                                        + " update version " + pkgLite.versionCode
8000                                        + " is older than installed version "
8001                                        + pkg.mVersionCode);
8002                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8003                            }
8004                        }
8005                        // Check for updated system application.
8006                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8007                            if (onSd) {
8008                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8009                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8010                            }
8011                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8012                        } else {
8013                            if (onSd) {
8014                                // Install flag overrides everything.
8015                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8016                            }
8017                            // If current upgrade specifies particular preference
8018                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8019                                // Application explicitly specified internal.
8020                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8021                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8022                                // App explictly prefers external. Let policy decide
8023                            } else {
8024                                // Prefer previous location
8025                                if (isExternal(pkg)) {
8026                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8027                                }
8028                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8029                            }
8030                        }
8031                    } else {
8032                        // Invalid install. Return error code
8033                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8034                    }
8035                }
8036            }
8037            // All the special cases have been taken care of.
8038            // Return result based on recommended install location.
8039            if (onSd) {
8040                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8041            }
8042            return pkgLite.recommendedInstallLocation;
8043        }
8044
8045        private long getMemoryLowThreshold() {
8046            final DeviceStorageMonitorInternal
8047                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8048            if (dsm == null) {
8049                return 0L;
8050            }
8051            return dsm.getMemoryLowThreshold();
8052        }
8053
8054        /*
8055         * Invoke remote method to get package information and install
8056         * location values. Override install location based on default
8057         * policy if needed and then create install arguments based
8058         * on the install location.
8059         */
8060        public void handleStartCopy() throws RemoteException {
8061            int ret = PackageManager.INSTALL_SUCCEEDED;
8062            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8063            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8064            PackageInfoLite pkgLite = null;
8065
8066            if (onInt && onSd) {
8067                // Check if both bits are set.
8068                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8069                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8070            } else {
8071                final long lowThreshold = getMemoryLowThreshold();
8072                if (lowThreshold == 0L) {
8073                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8074                }
8075
8076                try {
8077                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8078                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8079
8080                    final File packageFile;
8081                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8082                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8083                        if (mTempPackage != null) {
8084                            ParcelFileDescriptor out;
8085                            try {
8086                                out = ParcelFileDescriptor.open(mTempPackage,
8087                                        ParcelFileDescriptor.MODE_READ_WRITE);
8088                            } catch (FileNotFoundException e) {
8089                                out = null;
8090                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8091                            }
8092
8093                            // Make a temporary file for decryption.
8094                            ret = mContainerService
8095                                    .copyResource(mPackageURI, encryptionParams, out);
8096                            IoUtils.closeQuietly(out);
8097
8098                            packageFile = mTempPackage;
8099
8100                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8101                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8102                                            | FileUtils.S_IROTH,
8103                                    -1, -1);
8104                        } else {
8105                            packageFile = null;
8106                        }
8107                    } else {
8108                        packageFile = new File(mPackageURI.getPath());
8109                    }
8110
8111                    if (packageFile != null) {
8112                        // Remote call to find out default install location
8113                        final String packageFilePath = packageFile.getAbsolutePath();
8114                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8115                                lowThreshold);
8116
8117                        /*
8118                         * If we have too little free space, try to free cache
8119                         * before giving up.
8120                         */
8121                        if (pkgLite.recommendedInstallLocation
8122                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8123                            final long size = mContainerService.calculateInstalledSize(
8124                                    packageFilePath, isForwardLocked());
8125                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8126                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8127                                        flags, lowThreshold);
8128                            }
8129                            /*
8130                             * The cache free must have deleted the file we
8131                             * downloaded to install.
8132                             *
8133                             * TODO: fix the "freeCache" call to not delete
8134                             *       the file we care about.
8135                             */
8136                            if (pkgLite.recommendedInstallLocation
8137                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8138                                pkgLite.recommendedInstallLocation
8139                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8140                            }
8141                        }
8142                    }
8143                } finally {
8144                    mContext.revokeUriPermission(mPackageURI,
8145                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8146                }
8147            }
8148
8149            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8150                int loc = pkgLite.recommendedInstallLocation;
8151                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8152                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8153                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8154                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8155                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8156                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8157                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8158                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8159                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8160                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8161                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8162                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8163                } else {
8164                    // Override with defaults if needed.
8165                    loc = installLocationPolicy(pkgLite, flags);
8166                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8167                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8168                    } else if (!onSd && !onInt) {
8169                        // Override install location with flags
8170                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8171                            // Set the flag to install on external media.
8172                            flags |= PackageManager.INSTALL_EXTERNAL;
8173                            flags &= ~PackageManager.INSTALL_INTERNAL;
8174                        } else {
8175                            // Make sure the flag for installing on external
8176                            // media is unset
8177                            flags |= PackageManager.INSTALL_INTERNAL;
8178                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8179                        }
8180                    }
8181                }
8182            }
8183
8184            final InstallArgs args = createInstallArgs(this);
8185            mArgs = args;
8186
8187            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8188                 /*
8189                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8190                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8191                 */
8192                int userIdentifier = getUser().getIdentifier();
8193                if (userIdentifier == UserHandle.USER_ALL
8194                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8195                    userIdentifier = UserHandle.USER_OWNER;
8196                }
8197
8198                /*
8199                 * Determine if we have any installed package verifiers. If we
8200                 * do, then we'll defer to them to verify the packages.
8201                 */
8202                final int requiredUid = mRequiredVerifierPackage == null ? -1
8203                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8204                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8205                    final Intent verification = new Intent(
8206                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8207                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8208                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8209
8210                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8211                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8212                            0 /* TODO: Which userId? */);
8213
8214                    if (DEBUG_VERIFY) {
8215                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8216                                + verification.toString() + " with " + pkgLite.verifiers.length
8217                                + " optional verifiers");
8218                    }
8219
8220                    final int verificationId = mPendingVerificationToken++;
8221
8222                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8223
8224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8225                            installerPackageName);
8226
8227                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8228
8229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8230                            pkgLite.packageName);
8231
8232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8233                            pkgLite.versionCode);
8234
8235                    if (verificationParams != null) {
8236                        if (verificationParams.getVerificationURI() != null) {
8237                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8238                                 verificationParams.getVerificationURI());
8239                        }
8240                        if (verificationParams.getOriginatingURI() != null) {
8241                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8242                                  verificationParams.getOriginatingURI());
8243                        }
8244                        if (verificationParams.getReferrer() != null) {
8245                            verification.putExtra(Intent.EXTRA_REFERRER,
8246                                  verificationParams.getReferrer());
8247                        }
8248                        if (verificationParams.getOriginatingUid() >= 0) {
8249                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8250                                  verificationParams.getOriginatingUid());
8251                        }
8252                        if (verificationParams.getInstallerUid() >= 0) {
8253                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8254                                  verificationParams.getInstallerUid());
8255                        }
8256                    }
8257
8258                    final PackageVerificationState verificationState = new PackageVerificationState(
8259                            requiredUid, args);
8260
8261                    mPendingVerification.append(verificationId, verificationState);
8262
8263                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8264                            receivers, verificationState);
8265
8266                    /*
8267                     * If any sufficient verifiers were listed in the package
8268                     * manifest, attempt to ask them.
8269                     */
8270                    if (sufficientVerifiers != null) {
8271                        final int N = sufficientVerifiers.size();
8272                        if (N == 0) {
8273                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8274                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8275                        } else {
8276                            for (int i = 0; i < N; i++) {
8277                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8278
8279                                final Intent sufficientIntent = new Intent(verification);
8280                                sufficientIntent.setComponent(verifierComponent);
8281
8282                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8283                            }
8284                        }
8285                    }
8286
8287                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8288                            mRequiredVerifierPackage, receivers);
8289                    if (ret == PackageManager.INSTALL_SUCCEEDED
8290                            && mRequiredVerifierPackage != null) {
8291                        /*
8292                         * Send the intent to the required verification agent,
8293                         * but only start the verification timeout after the
8294                         * target BroadcastReceivers have run.
8295                         */
8296                        verification.setComponent(requiredVerifierComponent);
8297                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8298                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8299                                new BroadcastReceiver() {
8300                                    @Override
8301                                    public void onReceive(Context context, Intent intent) {
8302                                        final Message msg = mHandler
8303                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8304                                        msg.arg1 = verificationId;
8305                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8306                                    }
8307                                }, null, 0, null, null);
8308
8309                        /*
8310                         * We don't want the copy to proceed until verification
8311                         * succeeds, so null out this field.
8312                         */
8313                        mArgs = null;
8314                    }
8315                } else {
8316                    /*
8317                     * No package verification is enabled, so immediately start
8318                     * the remote call to initiate copy using temporary file.
8319                     */
8320                    ret = args.copyApk(mContainerService, true);
8321                }
8322            }
8323
8324            mRet = ret;
8325        }
8326
8327        @Override
8328        void handleReturnCode() {
8329            // If mArgs is null, then MCS couldn't be reached. When it
8330            // reconnects, it will try again to install. At that point, this
8331            // will succeed.
8332            if (mArgs != null) {
8333                processPendingInstall(mArgs, mRet);
8334
8335                if (mTempPackage != null) {
8336                    if (!mTempPackage.delete()) {
8337                        Slog.w(TAG, "Couldn't delete temporary file: " +
8338                                mTempPackage.getAbsolutePath());
8339                    }
8340                }
8341            }
8342        }
8343
8344        @Override
8345        void handleServiceError() {
8346            mArgs = createInstallArgs(this);
8347            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8348        }
8349
8350        public boolean isForwardLocked() {
8351            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8352        }
8353
8354        public Uri getPackageUri() {
8355            if (mTempPackage != null) {
8356                return Uri.fromFile(mTempPackage);
8357            } else {
8358                return mPackageURI;
8359            }
8360        }
8361    }
8362
8363    /*
8364     * Utility class used in movePackage api.
8365     * srcArgs and targetArgs are not set for invalid flags and make
8366     * sure to do null checks when invoking methods on them.
8367     * We probably want to return ErrorPrams for both failed installs
8368     * and moves.
8369     */
8370    class MoveParams extends HandlerParams {
8371        final IPackageMoveObserver observer;
8372        final int flags;
8373        final String packageName;
8374        final InstallArgs srcArgs;
8375        final InstallArgs targetArgs;
8376        int uid;
8377        int mRet;
8378
8379        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8380                String packageName, String dataDir, String instructionSet,
8381                int uid, UserHandle user) {
8382            super(user);
8383            this.srcArgs = srcArgs;
8384            this.observer = observer;
8385            this.flags = flags;
8386            this.packageName = packageName;
8387            this.uid = uid;
8388            if (srcArgs != null) {
8389                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8390                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8391            } else {
8392                targetArgs = null;
8393            }
8394        }
8395
8396        @Override
8397        public String toString() {
8398            return "MoveParams{"
8399                + Integer.toHexString(System.identityHashCode(this))
8400                + " " + packageName + "}";
8401        }
8402
8403        public void handleStartCopy() throws RemoteException {
8404            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8405            // Check for storage space on target medium
8406            if (!targetArgs.checkFreeStorage(mContainerService)) {
8407                Log.w(TAG, "Insufficient storage to install");
8408                return;
8409            }
8410
8411            mRet = srcArgs.doPreCopy();
8412            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8413                return;
8414            }
8415
8416            mRet = targetArgs.copyApk(mContainerService, false);
8417            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8418                srcArgs.doPostCopy(uid);
8419                return;
8420            }
8421
8422            mRet = srcArgs.doPostCopy(uid);
8423            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8424                return;
8425            }
8426
8427            mRet = targetArgs.doPreInstall(mRet);
8428            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8429                return;
8430            }
8431
8432            if (DEBUG_SD_INSTALL) {
8433                StringBuilder builder = new StringBuilder();
8434                if (srcArgs != null) {
8435                    builder.append("src: ");
8436                    builder.append(srcArgs.getCodePath());
8437                }
8438                if (targetArgs != null) {
8439                    builder.append(" target : ");
8440                    builder.append(targetArgs.getCodePath());
8441                }
8442                Log.i(TAG, builder.toString());
8443            }
8444        }
8445
8446        @Override
8447        void handleReturnCode() {
8448            targetArgs.doPostInstall(mRet, uid);
8449            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8450            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8451                currentStatus = PackageManager.MOVE_SUCCEEDED;
8452            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8453                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8454            }
8455            processPendingMove(this, currentStatus);
8456        }
8457
8458        @Override
8459        void handleServiceError() {
8460            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8461        }
8462    }
8463
8464    /**
8465     * Used during creation of InstallArgs
8466     *
8467     * @param flags package installation flags
8468     * @return true if should be installed on external storage
8469     */
8470    private static boolean installOnSd(int flags) {
8471        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8472            return false;
8473        }
8474        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8475            return true;
8476        }
8477        return false;
8478    }
8479
8480    /**
8481     * Used during creation of InstallArgs
8482     *
8483     * @param flags package installation flags
8484     * @return true if should be installed as forward locked
8485     */
8486    private static boolean installForwardLocked(int flags) {
8487        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8488    }
8489
8490    private InstallArgs createInstallArgs(InstallParams params) {
8491        if (installOnSd(params.flags) || params.isForwardLocked()) {
8492            return new AsecInstallArgs(params);
8493        } else {
8494            return new FileInstallArgs(params);
8495        }
8496    }
8497
8498    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8499            String nativeLibraryPath, String instructionSet) {
8500        final boolean isInAsec;
8501        if (installOnSd(flags)) {
8502            /* Apps on SD card are always in ASEC containers. */
8503            isInAsec = true;
8504        } else if (installForwardLocked(flags)
8505                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8506            /*
8507             * Forward-locked apps are only in ASEC containers if they're the
8508             * new style
8509             */
8510            isInAsec = true;
8511        } else {
8512            isInAsec = false;
8513        }
8514
8515        if (isInAsec) {
8516            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8517                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8518        } else {
8519            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8520                    instructionSet);
8521        }
8522    }
8523
8524    // Used by package mover
8525    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8526            String instructionSet) {
8527        if (installOnSd(flags) || installForwardLocked(flags)) {
8528            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8529                    + AsecInstallArgs.RES_FILE_NAME);
8530            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8531                    installForwardLocked(flags));
8532        } else {
8533            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8534        }
8535    }
8536
8537    static abstract class InstallArgs {
8538        final IPackageInstallObserver observer;
8539        final IPackageInstallObserver2 observer2;
8540        // Always refers to PackageManager flags only
8541        final int flags;
8542        final Uri packageURI;
8543        final String installerPackageName;
8544        final ManifestDigest manifestDigest;
8545        final UserHandle user;
8546        final String instructionSet;
8547
8548        InstallArgs(Uri packageURI,
8549                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8550                int flags, String installerPackageName, ManifestDigest manifestDigest,
8551                UserHandle user, String instructionSet) {
8552            this.packageURI = packageURI;
8553            this.flags = flags;
8554            this.observer = observer;
8555            this.observer2 = observer2;
8556            this.installerPackageName = installerPackageName;
8557            this.manifestDigest = manifestDigest;
8558            this.user = user;
8559            this.instructionSet = instructionSet;
8560        }
8561
8562        abstract void createCopyFile();
8563        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8564        abstract int doPreInstall(int status);
8565        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8566
8567        abstract int doPostInstall(int status, int uid);
8568        abstract String getCodePath();
8569        abstract String getResourcePath();
8570        abstract String getNativeLibraryPath();
8571        // Need installer lock especially for dex file removal.
8572        abstract void cleanUpResourcesLI();
8573        abstract boolean doPostDeleteLI(boolean delete);
8574        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8575
8576        /**
8577         * Called before the source arguments are copied. This is used mostly
8578         * for MoveParams when it needs to read the source file to put it in the
8579         * destination.
8580         */
8581        int doPreCopy() {
8582            return PackageManager.INSTALL_SUCCEEDED;
8583        }
8584
8585        /**
8586         * Called after the source arguments are copied. This is used mostly for
8587         * MoveParams when it needs to read the source file to put it in the
8588         * destination.
8589         *
8590         * @return
8591         */
8592        int doPostCopy(int uid) {
8593            return PackageManager.INSTALL_SUCCEEDED;
8594        }
8595
8596        protected boolean isFwdLocked() {
8597            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8598        }
8599
8600        UserHandle getUser() {
8601            return user;
8602        }
8603    }
8604
8605    class FileInstallArgs extends InstallArgs {
8606        File installDir;
8607        String codeFileName;
8608        String resourceFileName;
8609        String libraryPath;
8610        boolean created = false;
8611
8612        FileInstallArgs(InstallParams params) {
8613            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8614                    params.installerPackageName, params.getManifestDigest(),
8615                    params.getUser(), null /* instruction set */);
8616        }
8617
8618        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8619                String instructionSet) {
8620            super(null, null, null, 0, null, null, null, instructionSet);
8621            File codeFile = new File(fullCodePath);
8622            installDir = codeFile.getParentFile();
8623            codeFileName = fullCodePath;
8624            resourceFileName = fullResourcePath;
8625            libraryPath = nativeLibraryPath;
8626        }
8627
8628        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8629            super(packageURI, null, null, 0, null, null, null, instructionSet);
8630            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8631            String apkName = getNextCodePath(null, pkgName, ".apk");
8632            codeFileName = new File(installDir, apkName + ".apk").getPath();
8633            resourceFileName = getResourcePathFromCodePath();
8634            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8635        }
8636
8637        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8638            final long lowThreshold;
8639
8640            final DeviceStorageMonitorInternal
8641                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8642            if (dsm == null) {
8643                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8644                lowThreshold = 0L;
8645            } else {
8646                if (dsm.isMemoryLow()) {
8647                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8648                    return false;
8649                }
8650
8651                lowThreshold = dsm.getMemoryLowThreshold();
8652            }
8653
8654            try {
8655                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8656                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8657                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8658            } finally {
8659                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8660            }
8661        }
8662
8663        String getCodePath() {
8664            return codeFileName;
8665        }
8666
8667        void createCopyFile() {
8668            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8669            codeFileName = createTempPackageFile(installDir).getPath();
8670            resourceFileName = getResourcePathFromCodePath();
8671            libraryPath = getLibraryPathFromCodePath();
8672            created = true;
8673        }
8674
8675        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8676            if (temp) {
8677                // Generate temp file name
8678                createCopyFile();
8679            }
8680            // Get a ParcelFileDescriptor to write to the output file
8681            File codeFile = new File(codeFileName);
8682            if (!created) {
8683                try {
8684                    codeFile.createNewFile();
8685                    // Set permissions
8686                    if (!setPermissions()) {
8687                        // Failed setting permissions.
8688                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8689                    }
8690                } catch (IOException e) {
8691                   Slog.w(TAG, "Failed to create file " + codeFile);
8692                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8693                }
8694            }
8695            ParcelFileDescriptor out = null;
8696            try {
8697                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8698            } catch (FileNotFoundException e) {
8699                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8700                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8701            }
8702            // Copy the resource now
8703            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8704            try {
8705                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8706                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8707                ret = imcs.copyResource(packageURI, null, out);
8708            } finally {
8709                IoUtils.closeQuietly(out);
8710                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8711            }
8712
8713            if (isFwdLocked()) {
8714                final File destResourceFile = new File(getResourcePath());
8715
8716                // Copy the public files
8717                try {
8718                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8719                } catch (IOException e) {
8720                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8721                            + " forward-locked app.");
8722                    destResourceFile.delete();
8723                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8724                }
8725            }
8726
8727            final File nativeLibraryFile = new File(getNativeLibraryPath());
8728            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8729            if (nativeLibraryFile.exists()) {
8730                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8731                nativeLibraryFile.delete();
8732            }
8733            try {
8734                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8735                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8736                    return copyRet;
8737                }
8738            } catch (IOException e) {
8739                Slog.e(TAG, "Copying native libraries failed", e);
8740                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8741            }
8742
8743            return ret;
8744        }
8745
8746        int doPreInstall(int status) {
8747            if (status != PackageManager.INSTALL_SUCCEEDED) {
8748                cleanUp();
8749            }
8750            return status;
8751        }
8752
8753        boolean doRename(int status, final String pkgName, String oldCodePath) {
8754            if (status != PackageManager.INSTALL_SUCCEEDED) {
8755                cleanUp();
8756                return false;
8757            } else {
8758                final File oldCodeFile = new File(getCodePath());
8759                final File oldResourceFile = new File(getResourcePath());
8760                final File oldLibraryFile = new File(getNativeLibraryPath());
8761
8762                // Rename APK file based on packageName
8763                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8764                final File newCodeFile = new File(installDir, apkName + ".apk");
8765                if (!oldCodeFile.renameTo(newCodeFile)) {
8766                    return false;
8767                }
8768                codeFileName = newCodeFile.getPath();
8769
8770                // Rename public resource file if it's forward-locked.
8771                final File newResFile = new File(getResourcePathFromCodePath());
8772                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8773                    return false;
8774                }
8775                resourceFileName = newResFile.getPath();
8776
8777                // Rename library path
8778                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8779                if (newLibraryFile.exists()) {
8780                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8781                    newLibraryFile.delete();
8782                }
8783                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8784                    Slog.e(TAG, "Cannot rename native library directory "
8785                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8786                    return false;
8787                }
8788                libraryPath = newLibraryFile.getPath();
8789
8790                // Attempt to set permissions
8791                if (!setPermissions()) {
8792                    return false;
8793                }
8794
8795                if (!SELinux.restorecon(newCodeFile)) {
8796                    return false;
8797                }
8798
8799                return true;
8800            }
8801        }
8802
8803        int doPostInstall(int status, int uid) {
8804            if (status != PackageManager.INSTALL_SUCCEEDED) {
8805                cleanUp();
8806            }
8807            return status;
8808        }
8809
8810        String getResourcePath() {
8811            return resourceFileName;
8812        }
8813
8814        private String getResourcePathFromCodePath() {
8815            final String codePath = getCodePath();
8816            if (isFwdLocked()) {
8817                final StringBuilder sb = new StringBuilder();
8818
8819                sb.append(mAppInstallDir.getPath());
8820                sb.append('/');
8821                sb.append(getApkName(codePath));
8822                sb.append(".zip");
8823
8824                /*
8825                 * If our APK is a temporary file, mark the resource as a
8826                 * temporary file as well so it can be cleaned up after
8827                 * catastrophic failure.
8828                 */
8829                if (codePath.endsWith(".tmp")) {
8830                    sb.append(".tmp");
8831                }
8832
8833                return sb.toString();
8834            } else {
8835                return codePath;
8836            }
8837        }
8838
8839        private String getLibraryPathFromCodePath() {
8840            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8841        }
8842
8843        @Override
8844        String getNativeLibraryPath() {
8845            if (libraryPath == null) {
8846                libraryPath = getLibraryPathFromCodePath();
8847            }
8848            return libraryPath;
8849        }
8850
8851        private boolean cleanUp() {
8852            boolean ret = true;
8853            String sourceDir = getCodePath();
8854            String publicSourceDir = getResourcePath();
8855            if (sourceDir != null) {
8856                File sourceFile = new File(sourceDir);
8857                if (!sourceFile.exists()) {
8858                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8859                    ret = false;
8860                }
8861                // Delete application's code and resources
8862                sourceFile.delete();
8863            }
8864            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8865                final File publicSourceFile = new File(publicSourceDir);
8866                if (!publicSourceFile.exists()) {
8867                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8868                }
8869                if (publicSourceFile.exists()) {
8870                    publicSourceFile.delete();
8871                }
8872            }
8873
8874            if (libraryPath != null) {
8875                File nativeLibraryFile = new File(libraryPath);
8876                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8877                if (!nativeLibraryFile.delete()) {
8878                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8879                }
8880            }
8881
8882            return ret;
8883        }
8884
8885        void cleanUpResourcesLI() {
8886            String sourceDir = getCodePath();
8887            if (cleanUp()) {
8888                if (instructionSet == null) {
8889                    throw new IllegalStateException("instructionSet == null");
8890                }
8891                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
8892                if (retCode < 0) {
8893                    Slog.w(TAG, "Couldn't remove dex file for package: "
8894                            +  " at location "
8895                            + sourceDir + ", retcode=" + retCode);
8896                    // we don't consider this to be a failure of the core package deletion
8897                }
8898            }
8899        }
8900
8901        private boolean setPermissions() {
8902            // TODO Do this in a more elegant way later on. for now just a hack
8903            if (!isFwdLocked()) {
8904                final int filePermissions =
8905                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8906                    |FileUtils.S_IROTH;
8907                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8908                if (retCode != 0) {
8909                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8910                            getCodePath()
8911                            + ". The return code was: " + retCode);
8912                    // TODO Define new internal error
8913                    return false;
8914                }
8915                return true;
8916            }
8917            return true;
8918        }
8919
8920        boolean doPostDeleteLI(boolean delete) {
8921            // XXX err, shouldn't we respect the delete flag?
8922            cleanUpResourcesLI();
8923            return true;
8924        }
8925    }
8926
8927    private boolean isAsecExternal(String cid) {
8928        final String asecPath = PackageHelper.getSdFilesystem(cid);
8929        return !asecPath.startsWith(mAsecInternalPath);
8930    }
8931
8932    /**
8933     * Extract the MountService "container ID" from the full code path of an
8934     * .apk.
8935     */
8936    static String cidFromCodePath(String fullCodePath) {
8937        int eidx = fullCodePath.lastIndexOf("/");
8938        String subStr1 = fullCodePath.substring(0, eidx);
8939        int sidx = subStr1.lastIndexOf("/");
8940        return subStr1.substring(sidx+1, eidx);
8941    }
8942
8943    class AsecInstallArgs extends InstallArgs {
8944        static final String RES_FILE_NAME = "pkg.apk";
8945        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8946
8947        String cid;
8948        String packagePath;
8949        String resourcePath;
8950        String libraryPath;
8951
8952        AsecInstallArgs(InstallParams params) {
8953            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8954                    params.installerPackageName, params.getManifestDigest(),
8955                    params.getUser(), null /* instruction set */);
8956        }
8957
8958        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8959                String instructionSet, boolean isExternal, boolean isForwardLocked) {
8960            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8961                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8962                    null, null, null, instructionSet);
8963            // Extract cid from fullCodePath
8964            int eidx = fullCodePath.lastIndexOf("/");
8965            String subStr1 = fullCodePath.substring(0, eidx);
8966            int sidx = subStr1.lastIndexOf("/");
8967            cid = subStr1.substring(sidx+1, eidx);
8968            setCachePath(subStr1);
8969        }
8970
8971        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
8972            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8973                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8974                    null, null, null, instructionSet);
8975            this.cid = cid;
8976            setCachePath(PackageHelper.getSdDir(cid));
8977        }
8978
8979        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
8980                boolean isExternal, boolean isForwardLocked) {
8981            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8982                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8983                    null, null, null, instructionSet);
8984            this.cid = cid;
8985        }
8986
8987        void createCopyFile() {
8988            cid = getTempContainerId();
8989        }
8990
8991        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8992            try {
8993                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8994                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8995                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8996            } finally {
8997                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8998            }
8999        }
9000
9001        private final boolean isExternal() {
9002            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9003        }
9004
9005        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9006            if (temp) {
9007                createCopyFile();
9008            } else {
9009                /*
9010                 * Pre-emptively destroy the container since it's destroyed if
9011                 * copying fails due to it existing anyway.
9012                 */
9013                PackageHelper.destroySdDir(cid);
9014            }
9015
9016            final String newCachePath;
9017            try {
9018                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9019                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9020                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9021                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9022            } finally {
9023                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9024            }
9025
9026            if (newCachePath != null) {
9027                setCachePath(newCachePath);
9028                return PackageManager.INSTALL_SUCCEEDED;
9029            } else {
9030                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9031            }
9032        }
9033
9034        @Override
9035        String getCodePath() {
9036            return packagePath;
9037        }
9038
9039        @Override
9040        String getResourcePath() {
9041            return resourcePath;
9042        }
9043
9044        @Override
9045        String getNativeLibraryPath() {
9046            return libraryPath;
9047        }
9048
9049        int doPreInstall(int status) {
9050            if (status != PackageManager.INSTALL_SUCCEEDED) {
9051                // Destroy container
9052                PackageHelper.destroySdDir(cid);
9053            } else {
9054                boolean mounted = PackageHelper.isContainerMounted(cid);
9055                if (!mounted) {
9056                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9057                            Process.SYSTEM_UID);
9058                    if (newCachePath != null) {
9059                        setCachePath(newCachePath);
9060                    } else {
9061                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9062                    }
9063                }
9064            }
9065            return status;
9066        }
9067
9068        boolean doRename(int status, final String pkgName,
9069                String oldCodePath) {
9070            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9071            String newCachePath = null;
9072            if (PackageHelper.isContainerMounted(cid)) {
9073                // Unmount the container
9074                if (!PackageHelper.unMountSdDir(cid)) {
9075                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9076                    return false;
9077                }
9078            }
9079            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9080                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9081                        " which might be stale. Will try to clean up.");
9082                // Clean up the stale container and proceed to recreate.
9083                if (!PackageHelper.destroySdDir(newCacheId)) {
9084                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9085                    return false;
9086                }
9087                // Successfully cleaned up stale container. Try to rename again.
9088                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9089                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9090                            + " inspite of cleaning it up.");
9091                    return false;
9092                }
9093            }
9094            if (!PackageHelper.isContainerMounted(newCacheId)) {
9095                Slog.w(TAG, "Mounting container " + newCacheId);
9096                newCachePath = PackageHelper.mountSdDir(newCacheId,
9097                        getEncryptKey(), Process.SYSTEM_UID);
9098            } else {
9099                newCachePath = PackageHelper.getSdDir(newCacheId);
9100            }
9101            if (newCachePath == null) {
9102                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9103                return false;
9104            }
9105            Log.i(TAG, "Succesfully renamed " + cid +
9106                    " to " + newCacheId +
9107                    " at new path: " + newCachePath);
9108            cid = newCacheId;
9109            setCachePath(newCachePath);
9110            return true;
9111        }
9112
9113        private void setCachePath(String newCachePath) {
9114            File cachePath = new File(newCachePath);
9115            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9116            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9117
9118            if (isFwdLocked()) {
9119                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9120            } else {
9121                resourcePath = packagePath;
9122            }
9123        }
9124
9125        int doPostInstall(int status, int uid) {
9126            if (status != PackageManager.INSTALL_SUCCEEDED) {
9127                cleanUp();
9128            } else {
9129                final int groupOwner;
9130                final String protectedFile;
9131                if (isFwdLocked()) {
9132                    groupOwner = UserHandle.getSharedAppGid(uid);
9133                    protectedFile = RES_FILE_NAME;
9134                } else {
9135                    groupOwner = -1;
9136                    protectedFile = null;
9137                }
9138
9139                if (uid < Process.FIRST_APPLICATION_UID
9140                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9141                    Slog.e(TAG, "Failed to finalize " + cid);
9142                    PackageHelper.destroySdDir(cid);
9143                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9144                }
9145
9146                boolean mounted = PackageHelper.isContainerMounted(cid);
9147                if (!mounted) {
9148                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9149                }
9150            }
9151            return status;
9152        }
9153
9154        private void cleanUp() {
9155            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9156
9157            // Destroy secure container
9158            PackageHelper.destroySdDir(cid);
9159        }
9160
9161        void cleanUpResourcesLI() {
9162            String sourceFile = getCodePath();
9163            // Remove dex file
9164            if (instructionSet == null) {
9165                throw new IllegalStateException("instructionSet == null");
9166            }
9167            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9168            if (retCode < 0) {
9169                Slog.w(TAG, "Couldn't remove dex file for package: "
9170                        + " at location "
9171                        + sourceFile.toString() + ", retcode=" + retCode);
9172                // we don't consider this to be a failure of the core package deletion
9173            }
9174            cleanUp();
9175        }
9176
9177        boolean matchContainer(String app) {
9178            if (cid.startsWith(app)) {
9179                return true;
9180            }
9181            return false;
9182        }
9183
9184        String getPackageName() {
9185            return getAsecPackageName(cid);
9186        }
9187
9188        boolean doPostDeleteLI(boolean delete) {
9189            boolean ret = false;
9190            boolean mounted = PackageHelper.isContainerMounted(cid);
9191            if (mounted) {
9192                // Unmount first
9193                ret = PackageHelper.unMountSdDir(cid);
9194            }
9195            if (ret && delete) {
9196                cleanUpResourcesLI();
9197            }
9198            return ret;
9199        }
9200
9201        @Override
9202        int doPreCopy() {
9203            if (isFwdLocked()) {
9204                if (!PackageHelper.fixSdPermissions(cid,
9205                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9206                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9207                }
9208            }
9209
9210            return PackageManager.INSTALL_SUCCEEDED;
9211        }
9212
9213        @Override
9214        int doPostCopy(int uid) {
9215            if (isFwdLocked()) {
9216                if (uid < Process.FIRST_APPLICATION_UID
9217                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9218                                RES_FILE_NAME)) {
9219                    Slog.e(TAG, "Failed to finalize " + cid);
9220                    PackageHelper.destroySdDir(cid);
9221                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9222                }
9223            }
9224
9225            return PackageManager.INSTALL_SUCCEEDED;
9226        }
9227    };
9228
9229    static String getAsecPackageName(String packageCid) {
9230        int idx = packageCid.lastIndexOf("-");
9231        if (idx == -1) {
9232            return packageCid;
9233        }
9234        return packageCid.substring(0, idx);
9235    }
9236
9237    // Utility method used to create code paths based on package name and available index.
9238    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9239        String idxStr = "";
9240        int idx = 1;
9241        // Fall back to default value of idx=1 if prefix is not
9242        // part of oldCodePath
9243        if (oldCodePath != null) {
9244            String subStr = oldCodePath;
9245            // Drop the suffix right away
9246            if (subStr.endsWith(suffix)) {
9247                subStr = subStr.substring(0, subStr.length() - suffix.length());
9248            }
9249            // If oldCodePath already contains prefix find out the
9250            // ending index to either increment or decrement.
9251            int sidx = subStr.lastIndexOf(prefix);
9252            if (sidx != -1) {
9253                subStr = subStr.substring(sidx + prefix.length());
9254                if (subStr != null) {
9255                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9256                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9257                    }
9258                    try {
9259                        idx = Integer.parseInt(subStr);
9260                        if (idx <= 1) {
9261                            idx++;
9262                        } else {
9263                            idx--;
9264                        }
9265                    } catch(NumberFormatException e) {
9266                    }
9267                }
9268            }
9269        }
9270        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9271        return prefix + idxStr;
9272    }
9273
9274    // Utility method used to ignore ADD/REMOVE events
9275    // by directory observer.
9276    private static boolean ignoreCodePath(String fullPathStr) {
9277        String apkName = getApkName(fullPathStr);
9278        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9279        if (idx != -1 && ((idx+1) < apkName.length())) {
9280            // Make sure the package ends with a numeral
9281            String version = apkName.substring(idx+1);
9282            try {
9283                Integer.parseInt(version);
9284                return true;
9285            } catch (NumberFormatException e) {}
9286        }
9287        return false;
9288    }
9289
9290    // Utility method that returns the relative package path with respect
9291    // to the installation directory. Like say for /data/data/com.test-1.apk
9292    // string com.test-1 is returned.
9293    static String getApkName(String codePath) {
9294        if (codePath == null) {
9295            return null;
9296        }
9297        int sidx = codePath.lastIndexOf("/");
9298        int eidx = codePath.lastIndexOf(".");
9299        if (eidx == -1) {
9300            eidx = codePath.length();
9301        } else if (eidx == 0) {
9302            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9303            return null;
9304        }
9305        return codePath.substring(sidx+1, eidx);
9306    }
9307
9308    class PackageInstalledInfo {
9309        String name;
9310        int uid;
9311        // The set of users that originally had this package installed.
9312        int[] origUsers;
9313        // The set of users that now have this package installed.
9314        int[] newUsers;
9315        PackageParser.Package pkg;
9316        int returnCode;
9317        PackageRemovedInfo removedInfo;
9318
9319        // In some error cases we want to convey more info back to the observer
9320        String origPackage;
9321        String origPermission;
9322    }
9323
9324    /*
9325     * Install a non-existing package.
9326     */
9327    private void installNewPackageLI(PackageParser.Package pkg,
9328            int parseFlags, int scanMode, UserHandle user,
9329            String installerPackageName, PackageInstalledInfo res) {
9330        // Remember this for later, in case we need to rollback this install
9331        String pkgName = pkg.packageName;
9332
9333        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9334        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9335        synchronized(mPackages) {
9336            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9337                // A package with the same name is already installed, though
9338                // it has been renamed to an older name.  The package we
9339                // are trying to install should be installed as an update to
9340                // the existing one, but that has not been requested, so bail.
9341                Slog.w(TAG, "Attempt to re-install " + pkgName
9342                        + " without first uninstalling package running as "
9343                        + mSettings.mRenamedPackages.get(pkgName));
9344                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9345                return;
9346            }
9347            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9348                // Don't allow installation over an existing package with the same name.
9349                Slog.w(TAG, "Attempt to re-install " + pkgName
9350                        + " without first uninstalling.");
9351                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9352                return;
9353            }
9354        }
9355        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9356        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9357                System.currentTimeMillis(), user);
9358        if (newPackage == null) {
9359            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9360            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9361                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9362            }
9363        } else {
9364            updateSettingsLI(newPackage,
9365                    installerPackageName,
9366                    null, null,
9367                    res);
9368            // delete the partially installed application. the data directory will have to be
9369            // restored if it was already existing
9370            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9371                // remove package from internal structures.  Note that we want deletePackageX to
9372                // delete the package data and cache directories that it created in
9373                // scanPackageLocked, unless those directories existed before we even tried to
9374                // install.
9375                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9376                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9377                                res.removedInfo, true);
9378            }
9379        }
9380    }
9381
9382    private void replacePackageLI(PackageParser.Package pkg,
9383            int parseFlags, int scanMode, UserHandle user,
9384            String installerPackageName, PackageInstalledInfo res) {
9385
9386        PackageParser.Package oldPackage;
9387        String pkgName = pkg.packageName;
9388        int[] allUsers;
9389        boolean[] perUserInstalled;
9390
9391        // First find the old package info and check signatures
9392        synchronized(mPackages) {
9393            oldPackage = mPackages.get(pkgName);
9394            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9395            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9396                    != PackageManager.SIGNATURE_MATCH) {
9397                Slog.w(TAG, "New package has a different signature: " + pkgName);
9398                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9399                return;
9400            }
9401
9402            // In case of rollback, remember per-user/profile install state
9403            PackageSetting ps = mSettings.mPackages.get(pkgName);
9404            allUsers = sUserManager.getUserIds();
9405            perUserInstalled = new boolean[allUsers.length];
9406            for (int i = 0; i < allUsers.length; i++) {
9407                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9408            }
9409        }
9410        boolean sysPkg = (isSystemApp(oldPackage));
9411        if (sysPkg) {
9412            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9413                    user, allUsers, perUserInstalled, installerPackageName, res);
9414        } else {
9415            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9416                    user, allUsers, perUserInstalled, installerPackageName, res);
9417        }
9418    }
9419
9420    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9421            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9422            int[] allUsers, boolean[] perUserInstalled,
9423            String installerPackageName, PackageInstalledInfo res) {
9424        PackageParser.Package newPackage = null;
9425        String pkgName = deletedPackage.packageName;
9426        boolean deletedPkg = true;
9427        boolean updatedSettings = false;
9428
9429        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9430                + deletedPackage);
9431        long origUpdateTime;
9432        if (pkg.mExtras != null) {
9433            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9434        } else {
9435            origUpdateTime = 0;
9436        }
9437
9438        // First delete the existing package while retaining the data directory
9439        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9440                res.removedInfo, true)) {
9441            // If the existing package wasn't successfully deleted
9442            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9443            deletedPkg = false;
9444        } else {
9445            // Successfully deleted the old package. Now proceed with re-installation
9446            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9447            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9448                    System.currentTimeMillis(), user);
9449            if (newPackage == null) {
9450                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9451                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9452                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9453                }
9454            } else {
9455                updateSettingsLI(newPackage,
9456                        installerPackageName,
9457                        allUsers, perUserInstalled,
9458                        res);
9459                updatedSettings = true;
9460            }
9461        }
9462
9463        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9464            // remove package from internal structures.  Note that we want deletePackageX to
9465            // delete the package data and cache directories that it created in
9466            // scanPackageLocked, unless those directories existed before we even tried to
9467            // install.
9468            if(updatedSettings) {
9469                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9470                deletePackageLI(
9471                        pkgName, null, true, allUsers, perUserInstalled,
9472                        PackageManager.DELETE_KEEP_DATA,
9473                                res.removedInfo, true);
9474            }
9475            // Since we failed to install the new package we need to restore the old
9476            // package that we deleted.
9477            if(deletedPkg) {
9478                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9479                File restoreFile = new File(deletedPackage.mPath);
9480                // Parse old package
9481                boolean oldOnSd = isExternal(deletedPackage);
9482                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9483                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9484                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9485                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9486                        | SCAN_UPDATE_TIME;
9487                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9488                        origUpdateTime, null) == null) {
9489                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9490                    return;
9491                }
9492                // Restore of old package succeeded. Update permissions.
9493                // writer
9494                synchronized (mPackages) {
9495                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9496                            UPDATE_PERMISSIONS_ALL);
9497                    // can downgrade to reader
9498                    mSettings.writeLPr();
9499                }
9500                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9501            }
9502        }
9503    }
9504
9505    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9506            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9507            int[] allUsers, boolean[] perUserInstalled,
9508            String installerPackageName, PackageInstalledInfo res) {
9509        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9510                + ", old=" + deletedPackage);
9511        PackageParser.Package newPackage = null;
9512        boolean updatedSettings = false;
9513        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9514                PackageParser.PARSE_IS_SYSTEM;
9515        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9516            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9517        }
9518        String packageName = deletedPackage.packageName;
9519        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9520        if (packageName == null) {
9521            Slog.w(TAG, "Attempt to delete null packageName.");
9522            return;
9523        }
9524        PackageParser.Package oldPkg;
9525        PackageSetting oldPkgSetting;
9526        // reader
9527        synchronized (mPackages) {
9528            oldPkg = mPackages.get(packageName);
9529            oldPkgSetting = mSettings.mPackages.get(packageName);
9530            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9531                    (oldPkgSetting == null)) {
9532                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9533                return;
9534            }
9535        }
9536
9537        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9538
9539        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9540        res.removedInfo.removedPackage = packageName;
9541        // Remove existing system package
9542        removePackageLI(oldPkgSetting, true);
9543        // writer
9544        synchronized (mPackages) {
9545            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9546                // We didn't need to disable the .apk as a current system package,
9547                // which means we are replacing another update that is already
9548                // installed.  We need to make sure to delete the older one's .apk.
9549                res.removedInfo.args = createInstallArgs(0,
9550                        deletedPackage.applicationInfo.sourceDir,
9551                        deletedPackage.applicationInfo.publicSourceDir,
9552                        deletedPackage.applicationInfo.nativeLibraryDir,
9553                        getAppInstructionSet(deletedPackage.applicationInfo));
9554            } else {
9555                res.removedInfo.args = null;
9556            }
9557        }
9558
9559        // Successfully disabled the old package. Now proceed with re-installation
9560        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9561        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9562        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9563        if (newPackage == null) {
9564            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9565            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9566                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9567            }
9568        } else {
9569            if (newPackage.mExtras != null) {
9570                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9571                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9572                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9573
9574                // is the update attempting to change shared user? that isn't going to work...
9575                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9576                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9577                            + " to " + newPkgSetting.sharedUser);
9578                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9579                    updatedSettings = true;
9580                }
9581            }
9582
9583            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9584                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9585                updatedSettings = true;
9586            }
9587        }
9588
9589        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9590            // Re installation failed. Restore old information
9591            // Remove new pkg information
9592            if (newPackage != null) {
9593                removeInstalledPackageLI(newPackage, true);
9594            }
9595            // Add back the old system package
9596            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9597            // Restore the old system information in Settings
9598            synchronized(mPackages) {
9599                if (updatedSettings) {
9600                    mSettings.enableSystemPackageLPw(packageName);
9601                    mSettings.setInstallerPackageName(packageName,
9602                            oldPkgSetting.installerPackageName);
9603                }
9604                mSettings.writeLPr();
9605            }
9606        }
9607    }
9608
9609    // Utility method used to move dex files during install.
9610    private int moveDexFilesLI(PackageParser.Package newPackage) {
9611        int retCode;
9612        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9613            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9614                    getAppInstructionSet(newPackage.applicationInfo));
9615            if (retCode != 0) {
9616                if (mNoDexOpt) {
9617                    /*
9618                     * If we're in an engineering build, programs are lazily run
9619                     * through dexopt. If the .dex file doesn't exist yet, it
9620                     * will be created when the program is run next.
9621                     */
9622                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9623                } else {
9624                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9625                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9626                }
9627            }
9628        }
9629        return PackageManager.INSTALL_SUCCEEDED;
9630    }
9631
9632    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9633            int[] allUsers, boolean[] perUserInstalled,
9634            PackageInstalledInfo res) {
9635        String pkgName = newPackage.packageName;
9636        synchronized (mPackages) {
9637            //write settings. the installStatus will be incomplete at this stage.
9638            //note that the new package setting would have already been
9639            //added to mPackages. It hasn't been persisted yet.
9640            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9641            mSettings.writeLPr();
9642        }
9643
9644        if ((res.returnCode = moveDexFilesLI(newPackage))
9645                != PackageManager.INSTALL_SUCCEEDED) {
9646            // Discontinue if moving dex files failed.
9647            return;
9648        }
9649
9650        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9651
9652        synchronized (mPackages) {
9653            updatePermissionsLPw(newPackage.packageName, newPackage,
9654                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9655                            ? UPDATE_PERMISSIONS_ALL : 0));
9656            // For system-bundled packages, we assume that installing an upgraded version
9657            // of the package implies that the user actually wants to run that new code,
9658            // so we enable the package.
9659            if (isSystemApp(newPackage)) {
9660                // NB: implicit assumption that system package upgrades apply to all users
9661                if (DEBUG_INSTALL) {
9662                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9663                }
9664                PackageSetting ps = mSettings.mPackages.get(pkgName);
9665                if (ps != null) {
9666                    if (res.origUsers != null) {
9667                        for (int userHandle : res.origUsers) {
9668                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9669                                    userHandle, installerPackageName);
9670                        }
9671                    }
9672                    // Also convey the prior install/uninstall state
9673                    if (allUsers != null && perUserInstalled != null) {
9674                        for (int i = 0; i < allUsers.length; i++) {
9675                            if (DEBUG_INSTALL) {
9676                                Slog.d(TAG, "    user " + allUsers[i]
9677                                        + " => " + perUserInstalled[i]);
9678                            }
9679                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9680                        }
9681                        // these install state changes will be persisted in the
9682                        // upcoming call to mSettings.writeLPr().
9683                    }
9684                }
9685            }
9686            res.name = pkgName;
9687            res.uid = newPackage.applicationInfo.uid;
9688            res.pkg = newPackage;
9689            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9690            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9691            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9692            //to update install status
9693            mSettings.writeLPr();
9694        }
9695    }
9696
9697    private void installPackageLI(InstallArgs args,
9698            boolean newInstall, PackageInstalledInfo res) {
9699        int pFlags = args.flags;
9700        String installerPackageName = args.installerPackageName;
9701        File tmpPackageFile = new File(args.getCodePath());
9702        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9703        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9704        boolean replace = false;
9705        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9706                | (newInstall ? SCAN_NEW_INSTALL : 0);
9707        // Result object to be returned
9708        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9709
9710        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9711        // Retrieve PackageSettings and parse package
9712        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9713                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9714                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9715        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9716        pp.setSeparateProcesses(mSeparateProcesses);
9717        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9718                null, mMetrics, parseFlags);
9719        if (pkg == null) {
9720            res.returnCode = pp.getParseError();
9721            return;
9722        }
9723        String pkgName = res.name = pkg.packageName;
9724        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9725            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9726                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9727                return;
9728            }
9729        }
9730        if (!pp.collectCertificates(pkg, parseFlags)) {
9731            res.returnCode = pp.getParseError();
9732            return;
9733        }
9734
9735        /* If the installer passed in a manifest digest, compare it now. */
9736        if (args.manifestDigest != null) {
9737            if (DEBUG_INSTALL) {
9738                final String parsedManifest = pkg.manifestDigest == null ? "null"
9739                        : pkg.manifestDigest.toString();
9740                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9741                        + parsedManifest);
9742            }
9743
9744            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9745                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9746                return;
9747            }
9748        } else if (DEBUG_INSTALL) {
9749            final String parsedManifest = pkg.manifestDigest == null
9750                    ? "null" : pkg.manifestDigest.toString();
9751            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9752        }
9753
9754        // Get rid of all references to package scan path via parser.
9755        pp = null;
9756        String oldCodePath = null;
9757        boolean systemApp = false;
9758        synchronized (mPackages) {
9759            // Check whether the newly-scanned package wants to define an already-defined perm
9760            int N = pkg.permissions.size();
9761            for (int i = 0; i < N; i++) {
9762                PackageParser.Permission perm = pkg.permissions.get(i);
9763                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
9764                if (bp != null) {
9765                    // If the defining package is signed with our cert, it's okay.  This
9766                    // also includes the "updating the same package" case, of course.
9767                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
9768                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9769                        Slog.w(TAG, "Package " + pkg.packageName
9770                                + " attempting to redeclare permission " + perm.info.name
9771                                + " already owned by " + bp.sourcePackage);
9772                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
9773                        res.origPermission = perm.info.name;
9774                        res.origPackage = bp.sourcePackage;
9775                        return;
9776                    }
9777                }
9778            }
9779
9780            // Check if installing already existing package
9781            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9782                String oldName = mSettings.mRenamedPackages.get(pkgName);
9783                if (pkg.mOriginalPackages != null
9784                        && pkg.mOriginalPackages.contains(oldName)
9785                        && mPackages.containsKey(oldName)) {
9786                    // This package is derived from an original package,
9787                    // and this device has been updating from that original
9788                    // name.  We must continue using the original name, so
9789                    // rename the new package here.
9790                    pkg.setPackageName(oldName);
9791                    pkgName = pkg.packageName;
9792                    replace = true;
9793                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9794                            + oldName + " pkgName=" + pkgName);
9795                } else if (mPackages.containsKey(pkgName)) {
9796                    // This package, under its official name, already exists
9797                    // on the device; we should replace it.
9798                    replace = true;
9799                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9800                }
9801            }
9802            PackageSetting ps = mSettings.mPackages.get(pkgName);
9803            if (ps != null) {
9804                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9805                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9806                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9807                    systemApp = (ps.pkg.applicationInfo.flags &
9808                            ApplicationInfo.FLAG_SYSTEM) != 0;
9809                }
9810                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9811            }
9812        }
9813
9814        if (systemApp && onSd) {
9815            // Disable updates to system apps on sdcard
9816            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9817            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9818            return;
9819        }
9820
9821        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9822            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9823            return;
9824        }
9825        // Set application objects path explicitly after the rename
9826        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9827        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9828        if (replace) {
9829            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9830                    installerPackageName, res);
9831        } else {
9832            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9833                    installerPackageName, res);
9834        }
9835        synchronized (mPackages) {
9836            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9837            if (ps != null) {
9838                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9839            }
9840        }
9841    }
9842
9843    private static boolean isForwardLocked(PackageParser.Package pkg) {
9844        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9845    }
9846
9847
9848    private boolean isForwardLocked(PackageSetting ps) {
9849        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9850    }
9851
9852    private static boolean isExternal(PackageParser.Package pkg) {
9853        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9854    }
9855
9856    private static boolean isExternal(PackageSetting ps) {
9857        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9858    }
9859
9860    private static boolean isSystemApp(PackageParser.Package pkg) {
9861        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9862    }
9863
9864    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9865        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9866    }
9867
9868    private static boolean isSystemApp(ApplicationInfo info) {
9869        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9870    }
9871
9872    private static boolean isSystemApp(PackageSetting ps) {
9873        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9874    }
9875
9876    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9877        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9878    }
9879
9880    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9881        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9882    }
9883
9884    private int packageFlagsToInstallFlags(PackageSetting ps) {
9885        int installFlags = 0;
9886        if (isExternal(ps)) {
9887            installFlags |= PackageManager.INSTALL_EXTERNAL;
9888        }
9889        if (isForwardLocked(ps)) {
9890            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9891        }
9892        return installFlags;
9893    }
9894
9895    private void deleteTempPackageFiles() {
9896        final FilenameFilter filter = new FilenameFilter() {
9897            public boolean accept(File dir, String name) {
9898                return name.startsWith("vmdl") && name.endsWith(".tmp");
9899            }
9900        };
9901        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9902        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9903    }
9904
9905    private static final void deleteTempPackageFilesInDirectory(File directory,
9906            FilenameFilter filter) {
9907        final String[] tmpFilesList = directory.list(filter);
9908        if (tmpFilesList == null) {
9909            return;
9910        }
9911        for (int i = 0; i < tmpFilesList.length; i++) {
9912            final File tmpFile = new File(directory, tmpFilesList[i]);
9913            tmpFile.delete();
9914        }
9915    }
9916
9917    private File createTempPackageFile(File installDir) {
9918        File tmpPackageFile;
9919        try {
9920            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9921        } catch (IOException e) {
9922            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9923            return null;
9924        }
9925        try {
9926            FileUtils.setPermissions(
9927                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9928                    -1, -1);
9929            if (!SELinux.restorecon(tmpPackageFile)) {
9930                return null;
9931            }
9932        } catch (IOException e) {
9933            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9934            return null;
9935        }
9936        return tmpPackageFile;
9937    }
9938
9939    @Override
9940    public void deletePackageAsUser(final String packageName,
9941                                    final IPackageDeleteObserver observer,
9942                                    final int userId, final int flags) {
9943        mContext.enforceCallingOrSelfPermission(
9944                android.Manifest.permission.DELETE_PACKAGES, null);
9945        final int uid = Binder.getCallingUid();
9946        if (UserHandle.getUserId(uid) != userId) {
9947            mContext.enforceCallingPermission(
9948                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9949                    "deletePackage for user " + userId);
9950        }
9951        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9952            try {
9953                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9954            } catch (RemoteException re) {
9955            }
9956            return;
9957        }
9958
9959        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9960        // Queue up an async operation since the package deletion may take a little while.
9961        mHandler.post(new Runnable() {
9962            public void run() {
9963                mHandler.removeCallbacks(this);
9964                final int returnCode = deletePackageX(packageName, userId, flags);
9965                if (observer != null) {
9966                    try {
9967                        observer.packageDeleted(packageName, returnCode);
9968                    } catch (RemoteException e) {
9969                        Log.i(TAG, "Observer no longer exists.");
9970                    } //end catch
9971                } //end if
9972            } //end run
9973        });
9974    }
9975
9976    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9977        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9978                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9979        try {
9980            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9981                    || dpm.isDeviceOwner(packageName))) {
9982                return true;
9983            }
9984        } catch (RemoteException e) {
9985        }
9986        return false;
9987    }
9988
9989    /**
9990     *  This method is an internal method that could be get invoked either
9991     *  to delete an installed package or to clean up a failed installation.
9992     *  After deleting an installed package, a broadcast is sent to notify any
9993     *  listeners that the package has been installed. For cleaning up a failed
9994     *  installation, the broadcast is not necessary since the package's
9995     *  installation wouldn't have sent the initial broadcast either
9996     *  The key steps in deleting a package are
9997     *  deleting the package information in internal structures like mPackages,
9998     *  deleting the packages base directories through installd
9999     *  updating mSettings to reflect current status
10000     *  persisting settings for later use
10001     *  sending a broadcast if necessary
10002     */
10003    private int deletePackageX(String packageName, int userId, int flags) {
10004        final PackageRemovedInfo info = new PackageRemovedInfo();
10005        final boolean res;
10006
10007        if (isPackageDeviceAdmin(packageName, userId)) {
10008            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10009            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10010        }
10011
10012        boolean removedForAllUsers = false;
10013        boolean systemUpdate = false;
10014
10015        // for the uninstall-updates case and restricted profiles, remember the per-
10016        // userhandle installed state
10017        int[] allUsers;
10018        boolean[] perUserInstalled;
10019        synchronized (mPackages) {
10020            PackageSetting ps = mSettings.mPackages.get(packageName);
10021            allUsers = sUserManager.getUserIds();
10022            perUserInstalled = new boolean[allUsers.length];
10023            for (int i = 0; i < allUsers.length; i++) {
10024                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10025            }
10026        }
10027
10028        synchronized (mInstallLock) {
10029            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10030            res = deletePackageLI(packageName,
10031                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10032                            ? UserHandle.ALL : new UserHandle(userId),
10033                    true, allUsers, perUserInstalled,
10034                    flags | REMOVE_CHATTY, info, true);
10035            systemUpdate = info.isRemovedPackageSystemUpdate;
10036            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10037                removedForAllUsers = true;
10038            }
10039            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10040                    + " removedForAllUsers=" + removedForAllUsers);
10041        }
10042
10043        if (res) {
10044            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10045
10046            // If the removed package was a system update, the old system package
10047            // was re-enabled; we need to broadcast this information
10048            if (systemUpdate) {
10049                Bundle extras = new Bundle(1);
10050                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10051                        ? info.removedAppId : info.uid);
10052                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10053
10054                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10055                        extras, null, null, null);
10056                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10057                        extras, null, null, null);
10058                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10059                        null, packageName, null, null);
10060            }
10061        }
10062        // Force a gc here.
10063        Runtime.getRuntime().gc();
10064        // Delete the resources here after sending the broadcast to let
10065        // other processes clean up before deleting resources.
10066        if (info.args != null) {
10067            synchronized (mInstallLock) {
10068                info.args.doPostDeleteLI(true);
10069            }
10070        }
10071
10072        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10073    }
10074
10075    static class PackageRemovedInfo {
10076        String removedPackage;
10077        int uid = -1;
10078        int removedAppId = -1;
10079        int[] removedUsers = null;
10080        boolean isRemovedPackageSystemUpdate = false;
10081        // Clean up resources deleted packages.
10082        InstallArgs args = null;
10083
10084        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10085            Bundle extras = new Bundle(1);
10086            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10087            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10088            if (replacing) {
10089                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10090            }
10091            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10092            if (removedPackage != null) {
10093                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10094                        extras, null, null, removedUsers);
10095                if (fullRemove && !replacing) {
10096                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10097                            extras, null, null, removedUsers);
10098                }
10099            }
10100            if (removedAppId >= 0) {
10101                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10102                        removedUsers);
10103            }
10104        }
10105    }
10106
10107    /*
10108     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10109     * flag is not set, the data directory is removed as well.
10110     * make sure this flag is set for partially installed apps. If not its meaningless to
10111     * delete a partially installed application.
10112     */
10113    private void removePackageDataLI(PackageSetting ps,
10114            int[] allUserHandles, boolean[] perUserInstalled,
10115            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10116        String packageName = ps.name;
10117        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10118        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10119        // Retrieve object to delete permissions for shared user later on
10120        final PackageSetting deletedPs;
10121        // reader
10122        synchronized (mPackages) {
10123            deletedPs = mSettings.mPackages.get(packageName);
10124            if (outInfo != null) {
10125                outInfo.removedPackage = packageName;
10126                outInfo.removedUsers = deletedPs != null
10127                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10128                        : null;
10129            }
10130        }
10131        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10132            removeDataDirsLI(packageName);
10133            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10134        }
10135        // writer
10136        synchronized (mPackages) {
10137            if (deletedPs != null) {
10138                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10139                    if (outInfo != null) {
10140                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10141                    }
10142                    if (deletedPs != null) {
10143                        updatePermissionsLPw(deletedPs.name, null, 0);
10144                        if (deletedPs.sharedUser != null) {
10145                            // remove permissions associated with package
10146                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10147                        }
10148                    }
10149                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10150                }
10151                // make sure to preserve per-user disabled state if this removal was just
10152                // a downgrade of a system app to the factory package
10153                if (allUserHandles != null && perUserInstalled != null) {
10154                    if (DEBUG_REMOVE) {
10155                        Slog.d(TAG, "Propagating install state across downgrade");
10156                    }
10157                    for (int i = 0; i < allUserHandles.length; i++) {
10158                        if (DEBUG_REMOVE) {
10159                            Slog.d(TAG, "    user " + allUserHandles[i]
10160                                    + " => " + perUserInstalled[i]);
10161                        }
10162                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10163                    }
10164                }
10165            }
10166            // can downgrade to reader
10167            if (writeSettings) {
10168                // Save settings now
10169                mSettings.writeLPr();
10170            }
10171        }
10172        if (outInfo != null) {
10173            // A user ID was deleted here. Go through all users and remove it
10174            // from KeyStore.
10175            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10176        }
10177    }
10178
10179    static boolean locationIsPrivileged(File path) {
10180        try {
10181            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10182                    .getCanonicalPath();
10183            return path.getCanonicalPath().startsWith(privilegedAppDir);
10184        } catch (IOException e) {
10185            Slog.e(TAG, "Unable to access code path " + path);
10186        }
10187        return false;
10188    }
10189
10190    /*
10191     * Tries to delete system package.
10192     */
10193    private boolean deleteSystemPackageLI(PackageSetting newPs,
10194            int[] allUserHandles, boolean[] perUserInstalled,
10195            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10196        final boolean applyUserRestrictions
10197                = (allUserHandles != null) && (perUserInstalled != null);
10198        PackageSetting disabledPs = null;
10199        // Confirm if the system package has been updated
10200        // An updated system app can be deleted. This will also have to restore
10201        // the system pkg from system partition
10202        // reader
10203        synchronized (mPackages) {
10204            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10205        }
10206        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10207                + " disabledPs=" + disabledPs);
10208        if (disabledPs == null) {
10209            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10210            return false;
10211        } else if (DEBUG_REMOVE) {
10212            Slog.d(TAG, "Deleting system pkg from data partition");
10213        }
10214        if (DEBUG_REMOVE) {
10215            if (applyUserRestrictions) {
10216                Slog.d(TAG, "Remembering install states:");
10217                for (int i = 0; i < allUserHandles.length; i++) {
10218                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10219                }
10220            }
10221        }
10222        // Delete the updated package
10223        outInfo.isRemovedPackageSystemUpdate = true;
10224        if (disabledPs.versionCode < newPs.versionCode) {
10225            // Delete data for downgrades
10226            flags &= ~PackageManager.DELETE_KEEP_DATA;
10227        } else {
10228            // Preserve data by setting flag
10229            flags |= PackageManager.DELETE_KEEP_DATA;
10230        }
10231        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10232                allUserHandles, perUserInstalled, outInfo, writeSettings);
10233        if (!ret) {
10234            return false;
10235        }
10236        // writer
10237        synchronized (mPackages) {
10238            // Reinstate the old system package
10239            mSettings.enableSystemPackageLPw(newPs.name);
10240            // Remove any native libraries from the upgraded package.
10241            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10242        }
10243        // Install the system package
10244        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10245        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10246        if (locationIsPrivileged(disabledPs.codePath)) {
10247            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10248        }
10249        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10250                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10251
10252        if (newPkg == null) {
10253            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10254                    + " with error:" + mLastScanError);
10255            return false;
10256        }
10257        // writer
10258        synchronized (mPackages) {
10259            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10260            setInternalAppNativeLibraryPath(newPkg, ps);
10261            updatePermissionsLPw(newPkg.packageName, newPkg,
10262                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10263            if (applyUserRestrictions) {
10264                if (DEBUG_REMOVE) {
10265                    Slog.d(TAG, "Propagating install state across reinstall");
10266                }
10267                for (int i = 0; i < allUserHandles.length; i++) {
10268                    if (DEBUG_REMOVE) {
10269                        Slog.d(TAG, "    user " + allUserHandles[i]
10270                                + " => " + perUserInstalled[i]);
10271                    }
10272                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10273                }
10274                // Regardless of writeSettings we need to ensure that this restriction
10275                // state propagation is persisted
10276                mSettings.writeAllUsersPackageRestrictionsLPr();
10277            }
10278            // can downgrade to reader here
10279            if (writeSettings) {
10280                mSettings.writeLPr();
10281            }
10282        }
10283        return true;
10284    }
10285
10286    private boolean deleteInstalledPackageLI(PackageSetting ps,
10287            boolean deleteCodeAndResources, int flags,
10288            int[] allUserHandles, boolean[] perUserInstalled,
10289            PackageRemovedInfo outInfo, boolean writeSettings) {
10290        if (outInfo != null) {
10291            outInfo.uid = ps.appId;
10292        }
10293
10294        // Delete package data from internal structures and also remove data if flag is set
10295        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10296
10297        // Delete application code and resources
10298        if (deleteCodeAndResources && (outInfo != null)) {
10299            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10300                    ps.resourcePathString, ps.nativeLibraryPathString,
10301                    getAppInstructionSetFromSettings(ps));
10302        }
10303        return true;
10304    }
10305
10306    /*
10307     * This method handles package deletion in general
10308     */
10309    private boolean deletePackageLI(String packageName, UserHandle user,
10310            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10311            int flags, PackageRemovedInfo outInfo,
10312            boolean writeSettings) {
10313        if (packageName == null) {
10314            Slog.w(TAG, "Attempt to delete null packageName.");
10315            return false;
10316        }
10317        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10318        PackageSetting ps;
10319        boolean dataOnly = false;
10320        int removeUser = -1;
10321        int appId = -1;
10322        synchronized (mPackages) {
10323            ps = mSettings.mPackages.get(packageName);
10324            if (ps == null) {
10325                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10326                return false;
10327            }
10328            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10329                    && user.getIdentifier() != UserHandle.USER_ALL) {
10330                // The caller is asking that the package only be deleted for a single
10331                // user.  To do this, we just mark its uninstalled state and delete
10332                // its data.  If this is a system app, we only allow this to happen if
10333                // they have set the special DELETE_SYSTEM_APP which requests different
10334                // semantics than normal for uninstalling system apps.
10335                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10336                ps.setUserState(user.getIdentifier(),
10337                        COMPONENT_ENABLED_STATE_DEFAULT,
10338                        false, //installed
10339                        true,  //stopped
10340                        true,  //notLaunched
10341                        false, //blocked
10342                        null, null, null);
10343                if (!isSystemApp(ps)) {
10344                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10345                        // Other user still have this package installed, so all
10346                        // we need to do is clear this user's data and save that
10347                        // it is uninstalled.
10348                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10349                        removeUser = user.getIdentifier();
10350                        appId = ps.appId;
10351                        mSettings.writePackageRestrictionsLPr(removeUser);
10352                    } else {
10353                        // We need to set it back to 'installed' so the uninstall
10354                        // broadcasts will be sent correctly.
10355                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10356                        ps.setInstalled(true, user.getIdentifier());
10357                    }
10358                } else {
10359                    // This is a system app, so we assume that the
10360                    // other users still have this package installed, so all
10361                    // we need to do is clear this user's data and save that
10362                    // it is uninstalled.
10363                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10364                    removeUser = user.getIdentifier();
10365                    appId = ps.appId;
10366                    mSettings.writePackageRestrictionsLPr(removeUser);
10367                }
10368            }
10369        }
10370
10371        if (removeUser >= 0) {
10372            // From above, we determined that we are deleting this only
10373            // for a single user.  Continue the work here.
10374            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10375            if (outInfo != null) {
10376                outInfo.removedPackage = packageName;
10377                outInfo.removedAppId = appId;
10378                outInfo.removedUsers = new int[] {removeUser};
10379            }
10380            mInstaller.clearUserData(packageName, removeUser);
10381            removeKeystoreDataIfNeeded(removeUser, appId);
10382            schedulePackageCleaning(packageName, removeUser, false);
10383            return true;
10384        }
10385
10386        if (dataOnly) {
10387            // Delete application data first
10388            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10389            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10390            return true;
10391        }
10392
10393        boolean ret = false;
10394        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10395        if (isSystemApp(ps)) {
10396            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10397            // When an updated system application is deleted we delete the existing resources as well and
10398            // fall back to existing code in system partition
10399            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10400                    flags, outInfo, writeSettings);
10401        } else {
10402            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10403            // Kill application pre-emptively especially for apps on sd.
10404            killApplication(packageName, ps.appId, "uninstall pkg");
10405            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10406                    allUserHandles, perUserInstalled,
10407                    outInfo, writeSettings);
10408        }
10409
10410        return ret;
10411    }
10412
10413    private final class ClearStorageConnection implements ServiceConnection {
10414        IMediaContainerService mContainerService;
10415
10416        @Override
10417        public void onServiceConnected(ComponentName name, IBinder service) {
10418            synchronized (this) {
10419                mContainerService = IMediaContainerService.Stub.asInterface(service);
10420                notifyAll();
10421            }
10422        }
10423
10424        @Override
10425        public void onServiceDisconnected(ComponentName name) {
10426        }
10427    }
10428
10429    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10430        final boolean mounted;
10431        if (Environment.isExternalStorageEmulated()) {
10432            mounted = true;
10433        } else {
10434            final String status = Environment.getExternalStorageState();
10435
10436            mounted = status.equals(Environment.MEDIA_MOUNTED)
10437                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10438        }
10439
10440        if (!mounted) {
10441            return;
10442        }
10443
10444        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10445        int[] users;
10446        if (userId == UserHandle.USER_ALL) {
10447            users = sUserManager.getUserIds();
10448        } else {
10449            users = new int[] { userId };
10450        }
10451        final ClearStorageConnection conn = new ClearStorageConnection();
10452        if (mContext.bindServiceAsUser(
10453                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10454            try {
10455                for (int curUser : users) {
10456                    long timeout = SystemClock.uptimeMillis() + 5000;
10457                    synchronized (conn) {
10458                        long now = SystemClock.uptimeMillis();
10459                        while (conn.mContainerService == null && now < timeout) {
10460                            try {
10461                                conn.wait(timeout - now);
10462                            } catch (InterruptedException e) {
10463                            }
10464                        }
10465                    }
10466                    if (conn.mContainerService == null) {
10467                        return;
10468                    }
10469
10470                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10471                    clearDirectory(conn.mContainerService,
10472                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10473                    if (allData) {
10474                        clearDirectory(conn.mContainerService,
10475                                userEnv.buildExternalStorageAppDataDirs(packageName));
10476                        clearDirectory(conn.mContainerService,
10477                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10478                    }
10479                }
10480            } finally {
10481                mContext.unbindService(conn);
10482            }
10483        }
10484    }
10485
10486    @Override
10487    public void clearApplicationUserData(final String packageName,
10488            final IPackageDataObserver observer, final int userId) {
10489        mContext.enforceCallingOrSelfPermission(
10490                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10491        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10492        // Queue up an async operation since the package deletion may take a little while.
10493        mHandler.post(new Runnable() {
10494            public void run() {
10495                mHandler.removeCallbacks(this);
10496                final boolean succeeded;
10497                synchronized (mInstallLock) {
10498                    succeeded = clearApplicationUserDataLI(packageName, userId);
10499                }
10500                clearExternalStorageDataSync(packageName, userId, true);
10501                if (succeeded) {
10502                    // invoke DeviceStorageMonitor's update method to clear any notifications
10503                    DeviceStorageMonitorInternal
10504                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10505                    if (dsm != null) {
10506                        dsm.checkMemory();
10507                    }
10508                }
10509                if(observer != null) {
10510                    try {
10511                        observer.onRemoveCompleted(packageName, succeeded);
10512                    } catch (RemoteException e) {
10513                        Log.i(TAG, "Observer no longer exists.");
10514                    }
10515                } //end if observer
10516            } //end run
10517        });
10518    }
10519
10520    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10521        if (packageName == null) {
10522            Slog.w(TAG, "Attempt to delete null packageName.");
10523            return false;
10524        }
10525        PackageParser.Package p;
10526        boolean dataOnly = false;
10527        final int appId;
10528        synchronized (mPackages) {
10529            p = mPackages.get(packageName);
10530            if (p == null) {
10531                dataOnly = true;
10532                PackageSetting ps = mSettings.mPackages.get(packageName);
10533                if ((ps == null) || (ps.pkg == null)) {
10534                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10535                    return false;
10536                }
10537                p = ps.pkg;
10538            }
10539            if (!dataOnly) {
10540                // need to check this only for fully installed applications
10541                if (p == null) {
10542                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10543                    return false;
10544                }
10545                final ApplicationInfo applicationInfo = p.applicationInfo;
10546                if (applicationInfo == null) {
10547                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10548                    return false;
10549                }
10550            }
10551            if (p != null && p.applicationInfo != null) {
10552                appId = p.applicationInfo.uid;
10553            } else {
10554                appId = -1;
10555            }
10556        }
10557        int retCode = mInstaller.clearUserData(packageName, userId);
10558        if (retCode < 0) {
10559            Slog.w(TAG, "Couldn't remove cache files for package: "
10560                    + packageName);
10561            return false;
10562        }
10563        removeKeystoreDataIfNeeded(userId, appId);
10564        return true;
10565    }
10566
10567    /**
10568     * Remove entries from the keystore daemon. Will only remove it if the
10569     * {@code appId} is valid.
10570     */
10571    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10572        if (appId < 0) {
10573            return;
10574        }
10575
10576        final KeyStore keyStore = KeyStore.getInstance();
10577        if (keyStore != null) {
10578            if (userId == UserHandle.USER_ALL) {
10579                for (final int individual : sUserManager.getUserIds()) {
10580                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10581                }
10582            } else {
10583                keyStore.clearUid(UserHandle.getUid(userId, appId));
10584            }
10585        } else {
10586            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10587        }
10588    }
10589
10590    public void deleteApplicationCacheFiles(final String packageName,
10591            final IPackageDataObserver observer) {
10592        mContext.enforceCallingOrSelfPermission(
10593                android.Manifest.permission.DELETE_CACHE_FILES, null);
10594        // Queue up an async operation since the package deletion may take a little while.
10595        final int userId = UserHandle.getCallingUserId();
10596        mHandler.post(new Runnable() {
10597            public void run() {
10598                mHandler.removeCallbacks(this);
10599                final boolean succeded;
10600                synchronized (mInstallLock) {
10601                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10602                }
10603                clearExternalStorageDataSync(packageName, userId, false);
10604                if(observer != null) {
10605                    try {
10606                        observer.onRemoveCompleted(packageName, succeded);
10607                    } catch (RemoteException e) {
10608                        Log.i(TAG, "Observer no longer exists.");
10609                    }
10610                } //end if observer
10611            } //end run
10612        });
10613    }
10614
10615    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10616        if (packageName == null) {
10617            Slog.w(TAG, "Attempt to delete null packageName.");
10618            return false;
10619        }
10620        PackageParser.Package p;
10621        synchronized (mPackages) {
10622            p = mPackages.get(packageName);
10623        }
10624        if (p == null) {
10625            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10626            return false;
10627        }
10628        final ApplicationInfo applicationInfo = p.applicationInfo;
10629        if (applicationInfo == null) {
10630            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10631            return false;
10632        }
10633        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10634        if (retCode < 0) {
10635            Slog.w(TAG, "Couldn't remove cache files for package: "
10636                       + packageName + " u" + userId);
10637            return false;
10638        }
10639        return true;
10640    }
10641
10642    public void getPackageSizeInfo(final String packageName, int userHandle,
10643            final IPackageStatsObserver observer) {
10644        mContext.enforceCallingOrSelfPermission(
10645                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10646        if (packageName == null) {
10647            throw new IllegalArgumentException("Attempt to get size of null packageName");
10648        }
10649
10650        PackageStats stats = new PackageStats(packageName, userHandle);
10651
10652        /*
10653         * Queue up an async operation since the package measurement may take a
10654         * little while.
10655         */
10656        Message msg = mHandler.obtainMessage(INIT_COPY);
10657        msg.obj = new MeasureParams(stats, observer);
10658        mHandler.sendMessage(msg);
10659    }
10660
10661    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10662            PackageStats pStats) {
10663        if (packageName == null) {
10664            Slog.w(TAG, "Attempt to get size of null packageName.");
10665            return false;
10666        }
10667        PackageParser.Package p;
10668        boolean dataOnly = false;
10669        String libDirPath = null;
10670        String asecPath = null;
10671        PackageSetting ps = null;
10672        synchronized (mPackages) {
10673            p = mPackages.get(packageName);
10674            ps = mSettings.mPackages.get(packageName);
10675            if(p == null) {
10676                dataOnly = true;
10677                if((ps == null) || (ps.pkg == null)) {
10678                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10679                    return false;
10680                }
10681                p = ps.pkg;
10682            }
10683            if (ps != null) {
10684                libDirPath = ps.nativeLibraryPathString;
10685            }
10686            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10687                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10688                if (secureContainerId != null) {
10689                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10690                }
10691            }
10692        }
10693        String publicSrcDir = null;
10694        if(!dataOnly) {
10695            final ApplicationInfo applicationInfo = p.applicationInfo;
10696            if (applicationInfo == null) {
10697                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10698                return false;
10699            }
10700            if (isForwardLocked(p)) {
10701                publicSrcDir = applicationInfo.publicSourceDir;
10702            }
10703        }
10704        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10705                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10706                pStats);
10707        if (res < 0) {
10708            return false;
10709        }
10710
10711        // Fix-up for forward-locked applications in ASEC containers.
10712        if (!isExternal(p)) {
10713            pStats.codeSize += pStats.externalCodeSize;
10714            pStats.externalCodeSize = 0L;
10715        }
10716
10717        return true;
10718    }
10719
10720
10721    public void addPackageToPreferred(String packageName) {
10722        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10723    }
10724
10725    public void removePackageFromPreferred(String packageName) {
10726        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10727    }
10728
10729    public List<PackageInfo> getPreferredPackages(int flags) {
10730        return new ArrayList<PackageInfo>();
10731    }
10732
10733    private int getUidTargetSdkVersionLockedLPr(int uid) {
10734        Object obj = mSettings.getUserIdLPr(uid);
10735        if (obj instanceof SharedUserSetting) {
10736            final SharedUserSetting sus = (SharedUserSetting) obj;
10737            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10738            final Iterator<PackageSetting> it = sus.packages.iterator();
10739            while (it.hasNext()) {
10740                final PackageSetting ps = it.next();
10741                if (ps.pkg != null) {
10742                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10743                    if (v < vers) vers = v;
10744                }
10745            }
10746            return vers;
10747        } else if (obj instanceof PackageSetting) {
10748            final PackageSetting ps = (PackageSetting) obj;
10749            if (ps.pkg != null) {
10750                return ps.pkg.applicationInfo.targetSdkVersion;
10751            }
10752        }
10753        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10754    }
10755
10756    public void addPreferredActivity(IntentFilter filter, int match,
10757            ComponentName[] set, ComponentName activity, int userId) {
10758        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10759    }
10760
10761    private void addPreferredActivityInternal(IntentFilter filter, int match,
10762            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10763        // writer
10764        int callingUid = Binder.getCallingUid();
10765        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10766        if (filter.countActions() == 0) {
10767            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10768            return;
10769        }
10770        synchronized (mPackages) {
10771            if (mContext.checkCallingOrSelfPermission(
10772                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10773                    != PackageManager.PERMISSION_GRANTED) {
10774                if (getUidTargetSdkVersionLockedLPr(callingUid)
10775                        < Build.VERSION_CODES.FROYO) {
10776                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10777                            + callingUid);
10778                    return;
10779                }
10780                mContext.enforceCallingOrSelfPermission(
10781                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10782            }
10783
10784            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10785            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10786            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10787                    new PreferredActivity(filter, match, set, activity, always));
10788            mSettings.writePackageRestrictionsLPr(userId);
10789        }
10790    }
10791
10792    public void replacePreferredActivity(IntentFilter filter, int match,
10793            ComponentName[] set, ComponentName activity) {
10794        if (filter.countActions() != 1) {
10795            throw new IllegalArgumentException(
10796                    "replacePreferredActivity expects filter to have only 1 action.");
10797        }
10798        if (filter.countDataAuthorities() != 0
10799                || filter.countDataPaths() != 0
10800                || filter.countDataSchemes() > 1
10801                || filter.countDataTypes() != 0) {
10802            throw new IllegalArgumentException(
10803                    "replacePreferredActivity expects filter to have no data authorities, " +
10804                    "paths, or types; and at most one scheme.");
10805        }
10806        synchronized (mPackages) {
10807            if (mContext.checkCallingOrSelfPermission(
10808                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10809                    != PackageManager.PERMISSION_GRANTED) {
10810                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10811                        < Build.VERSION_CODES.FROYO) {
10812                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10813                            + Binder.getCallingUid());
10814                    return;
10815                }
10816                mContext.enforceCallingOrSelfPermission(
10817                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10818            }
10819
10820            final int callingUserId = UserHandle.getCallingUserId();
10821            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10822            if (pir != null) {
10823                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10824                if (filter.countDataSchemes() == 1) {
10825                    Uri.Builder builder = new Uri.Builder();
10826                    builder.scheme(filter.getDataScheme(0));
10827                    intent.setData(builder.build());
10828                }
10829                List<PreferredActivity> matches = pir.queryIntent(
10830                        intent, null, true, callingUserId);
10831                if (DEBUG_PREFERRED) {
10832                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10833                }
10834                for (int i = 0; i < matches.size(); i++) {
10835                    PreferredActivity pa = matches.get(i);
10836                    if (DEBUG_PREFERRED) {
10837                        Slog.i(TAG, "Removing preferred activity "
10838                                + pa.mPref.mComponent + ":");
10839                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10840                    }
10841                    pir.removeFilter(pa);
10842                }
10843            }
10844            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10845        }
10846    }
10847
10848    public void clearPackagePreferredActivities(String packageName) {
10849        final int uid = Binder.getCallingUid();
10850        // writer
10851        synchronized (mPackages) {
10852            PackageParser.Package pkg = mPackages.get(packageName);
10853            if (pkg == null || pkg.applicationInfo.uid != uid) {
10854                if (mContext.checkCallingOrSelfPermission(
10855                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10856                        != PackageManager.PERMISSION_GRANTED) {
10857                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10858                            < Build.VERSION_CODES.FROYO) {
10859                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10860                                + Binder.getCallingUid());
10861                        return;
10862                    }
10863                    mContext.enforceCallingOrSelfPermission(
10864                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10865                }
10866            }
10867
10868            int user = UserHandle.getCallingUserId();
10869            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10870                mSettings.writePackageRestrictionsLPr(user);
10871                scheduleWriteSettingsLocked();
10872            }
10873        }
10874    }
10875
10876    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10877    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10878        ArrayList<PreferredActivity> removed = null;
10879        boolean changed = false;
10880        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10881            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10882            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10883            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10884                continue;
10885            }
10886            Iterator<PreferredActivity> it = pir.filterIterator();
10887            while (it.hasNext()) {
10888                PreferredActivity pa = it.next();
10889                // Mark entry for removal only if it matches the package name
10890                // and the entry is of type "always".
10891                if (packageName == null ||
10892                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10893                                && pa.mPref.mAlways)) {
10894                    if (removed == null) {
10895                        removed = new ArrayList<PreferredActivity>();
10896                    }
10897                    removed.add(pa);
10898                }
10899            }
10900            if (removed != null) {
10901                for (int j=0; j<removed.size(); j++) {
10902                    PreferredActivity pa = removed.get(j);
10903                    pir.removeFilter(pa);
10904                }
10905                changed = true;
10906            }
10907        }
10908        return changed;
10909    }
10910
10911    public void resetPreferredActivities(int userId) {
10912        mContext.enforceCallingOrSelfPermission(
10913                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10914        // writer
10915        synchronized (mPackages) {
10916            int user = UserHandle.getCallingUserId();
10917            clearPackagePreferredActivitiesLPw(null, user);
10918            mSettings.readDefaultPreferredAppsLPw(this, user);
10919            mSettings.writePackageRestrictionsLPr(user);
10920            scheduleWriteSettingsLocked();
10921        }
10922    }
10923
10924    public int getPreferredActivities(List<IntentFilter> outFilters,
10925            List<ComponentName> outActivities, String packageName) {
10926
10927        int num = 0;
10928        final int userId = UserHandle.getCallingUserId();
10929        // reader
10930        synchronized (mPackages) {
10931            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10932            if (pir != null) {
10933                final Iterator<PreferredActivity> it = pir.filterIterator();
10934                while (it.hasNext()) {
10935                    final PreferredActivity pa = it.next();
10936                    if (packageName == null
10937                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10938                                    && pa.mPref.mAlways)) {
10939                        if (outFilters != null) {
10940                            outFilters.add(new IntentFilter(pa));
10941                        }
10942                        if (outActivities != null) {
10943                            outActivities.add(pa.mPref.mComponent);
10944                        }
10945                    }
10946                }
10947            }
10948        }
10949
10950        return num;
10951    }
10952
10953    @Override
10954    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
10955            int userId) {
10956        int callingUid = Binder.getCallingUid();
10957        if (callingUid != Process.SYSTEM_UID) {
10958            throw new SecurityException(
10959                    "addPersistentPreferredActivity can only be run by the system");
10960        }
10961        if (filter.countActions() == 0) {
10962            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10963            return;
10964        }
10965        synchronized (mPackages) {
10966            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
10967                    " :");
10968            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10969            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
10970                    new PersistentPreferredActivity(filter, activity));
10971            mSettings.writePackageRestrictionsLPr(userId);
10972        }
10973    }
10974
10975    @Override
10976    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
10977        int callingUid = Binder.getCallingUid();
10978        if (callingUid != Process.SYSTEM_UID) {
10979            throw new SecurityException(
10980                    "clearPackagePersistentPreferredActivities can only be run by the system");
10981        }
10982        ArrayList<PersistentPreferredActivity> removed = null;
10983        boolean changed = false;
10984        synchronized (mPackages) {
10985            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
10986                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
10987                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
10988                        .valueAt(i);
10989                if (userId != thisUserId) {
10990                    continue;
10991                }
10992                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
10993                while (it.hasNext()) {
10994                    PersistentPreferredActivity ppa = it.next();
10995                    // Mark entry for removal only if it matches the package name.
10996                    if (ppa.mComponent.getPackageName().equals(packageName)) {
10997                        if (removed == null) {
10998                            removed = new ArrayList<PersistentPreferredActivity>();
10999                        }
11000                        removed.add(ppa);
11001                    }
11002                }
11003                if (removed != null) {
11004                    for (int j=0; j<removed.size(); j++) {
11005                        PersistentPreferredActivity ppa = removed.get(j);
11006                        ppir.removeFilter(ppa);
11007                    }
11008                    changed = true;
11009                }
11010            }
11011
11012            if (changed) {
11013                mSettings.writePackageRestrictionsLPr(userId);
11014            }
11015        }
11016    }
11017
11018    @Override
11019    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11020        Intent intent = new Intent(Intent.ACTION_MAIN);
11021        intent.addCategory(Intent.CATEGORY_HOME);
11022
11023        final int callingUserId = UserHandle.getCallingUserId();
11024        List<ResolveInfo> list = queryIntentActivities(intent, null,
11025                PackageManager.GET_META_DATA, callingUserId);
11026        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11027                true, false, false, callingUserId);
11028
11029        allHomeCandidates.clear();
11030        if (list != null) {
11031            for (ResolveInfo ri : list) {
11032                allHomeCandidates.add(ri);
11033            }
11034        }
11035        return (preferred == null || preferred.activityInfo == null)
11036                ? null
11037                : new ComponentName(preferred.activityInfo.packageName,
11038                        preferred.activityInfo.name);
11039    }
11040
11041    @Override
11042    public void setApplicationEnabledSetting(String appPackageName,
11043            int newState, int flags, int userId, String callingPackage) {
11044        if (!sUserManager.exists(userId)) return;
11045        if (callingPackage == null) {
11046            callingPackage = Integer.toString(Binder.getCallingUid());
11047        }
11048        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11049    }
11050
11051    @Override
11052    public void setComponentEnabledSetting(ComponentName componentName,
11053            int newState, int flags, int userId) {
11054        if (!sUserManager.exists(userId)) return;
11055        setEnabledSetting(componentName.getPackageName(),
11056                componentName.getClassName(), newState, flags, userId, null);
11057    }
11058
11059    private void setEnabledSetting(final String packageName, String className, int newState,
11060            final int flags, int userId, String callingPackage) {
11061        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11062              || newState == COMPONENT_ENABLED_STATE_ENABLED
11063              || newState == COMPONENT_ENABLED_STATE_DISABLED
11064              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11065              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11066            throw new IllegalArgumentException("Invalid new component state: "
11067                    + newState);
11068        }
11069        PackageSetting pkgSetting;
11070        final int uid = Binder.getCallingUid();
11071        final int permission = mContext.checkCallingOrSelfPermission(
11072                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11073        enforceCrossUserPermission(uid, userId, false, "set enabled");
11074        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11075        boolean sendNow = false;
11076        boolean isApp = (className == null);
11077        String componentName = isApp ? packageName : className;
11078        int packageUid = -1;
11079        ArrayList<String> components;
11080
11081        // writer
11082        synchronized (mPackages) {
11083            pkgSetting = mSettings.mPackages.get(packageName);
11084            if (pkgSetting == null) {
11085                if (className == null) {
11086                    throw new IllegalArgumentException(
11087                            "Unknown package: " + packageName);
11088                }
11089                throw new IllegalArgumentException(
11090                        "Unknown component: " + packageName
11091                        + "/" + className);
11092            }
11093            // Allow root and verify that userId is not being specified by a different user
11094            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11095                throw new SecurityException(
11096                        "Permission Denial: attempt to change component state from pid="
11097                        + Binder.getCallingPid()
11098                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11099            }
11100            if (className == null) {
11101                // We're dealing with an application/package level state change
11102                if (pkgSetting.getEnabled(userId) == newState) {
11103                    // Nothing to do
11104                    return;
11105                }
11106                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11107                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11108                    // Don't care about who enables an app.
11109                    callingPackage = null;
11110                }
11111                pkgSetting.setEnabled(newState, userId, callingPackage);
11112                // pkgSetting.pkg.mSetEnabled = newState;
11113            } else {
11114                // We're dealing with a component level state change
11115                // First, verify that this is a valid class name.
11116                PackageParser.Package pkg = pkgSetting.pkg;
11117                if (pkg == null || !pkg.hasComponentClassName(className)) {
11118                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11119                        throw new IllegalArgumentException("Component class " + className
11120                                + " does not exist in " + packageName);
11121                    } else {
11122                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11123                                + className + " does not exist in " + packageName);
11124                    }
11125                }
11126                switch (newState) {
11127                case COMPONENT_ENABLED_STATE_ENABLED:
11128                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11129                        return;
11130                    }
11131                    break;
11132                case COMPONENT_ENABLED_STATE_DISABLED:
11133                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11134                        return;
11135                    }
11136                    break;
11137                case COMPONENT_ENABLED_STATE_DEFAULT:
11138                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11139                        return;
11140                    }
11141                    break;
11142                default:
11143                    Slog.e(TAG, "Invalid new component state: " + newState);
11144                    return;
11145                }
11146            }
11147            mSettings.writePackageRestrictionsLPr(userId);
11148            components = mPendingBroadcasts.get(userId, packageName);
11149            final boolean newPackage = components == null;
11150            if (newPackage) {
11151                components = new ArrayList<String>();
11152            }
11153            if (!components.contains(componentName)) {
11154                components.add(componentName);
11155            }
11156            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11157                sendNow = true;
11158                // Purge entry from pending broadcast list if another one exists already
11159                // since we are sending one right away.
11160                mPendingBroadcasts.remove(userId, packageName);
11161            } else {
11162                if (newPackage) {
11163                    mPendingBroadcasts.put(userId, packageName, components);
11164                }
11165                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11166                    // Schedule a message
11167                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11168                }
11169            }
11170        }
11171
11172        long callingId = Binder.clearCallingIdentity();
11173        try {
11174            if (sendNow) {
11175                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11176                sendPackageChangedBroadcast(packageName,
11177                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11178            }
11179        } finally {
11180            Binder.restoreCallingIdentity(callingId);
11181        }
11182    }
11183
11184    private void sendPackageChangedBroadcast(String packageName,
11185            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11186        if (DEBUG_INSTALL)
11187            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11188                    + componentNames);
11189        Bundle extras = new Bundle(4);
11190        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11191        String nameList[] = new String[componentNames.size()];
11192        componentNames.toArray(nameList);
11193        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11194        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11195        extras.putInt(Intent.EXTRA_UID, packageUid);
11196        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11197                new int[] {UserHandle.getUserId(packageUid)});
11198    }
11199
11200    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11201        if (!sUserManager.exists(userId)) return;
11202        final int uid = Binder.getCallingUid();
11203        final int permission = mContext.checkCallingOrSelfPermission(
11204                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11205        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11206        enforceCrossUserPermission(uid, userId, true, "stop package");
11207        // writer
11208        synchronized (mPackages) {
11209            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11210                    uid, userId)) {
11211                scheduleWritePackageRestrictionsLocked(userId);
11212            }
11213        }
11214    }
11215
11216    public String getInstallerPackageName(String packageName) {
11217        // reader
11218        synchronized (mPackages) {
11219            return mSettings.getInstallerPackageNameLPr(packageName);
11220        }
11221    }
11222
11223    @Override
11224    public int getApplicationEnabledSetting(String packageName, int userId) {
11225        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11226        int uid = Binder.getCallingUid();
11227        enforceCrossUserPermission(uid, userId, false, "get enabled");
11228        // reader
11229        synchronized (mPackages) {
11230            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11231        }
11232    }
11233
11234    @Override
11235    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11236        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11237        int uid = Binder.getCallingUid();
11238        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11239        // reader
11240        synchronized (mPackages) {
11241            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11242        }
11243    }
11244
11245    public void enterSafeMode() {
11246        enforceSystemOrRoot("Only the system can request entering safe mode");
11247
11248        if (!mSystemReady) {
11249            mSafeMode = true;
11250        }
11251    }
11252
11253    public void systemReady() {
11254        mSystemReady = true;
11255
11256        // Read the compatibilty setting when the system is ready.
11257        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11258                mContext.getContentResolver(),
11259                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11260        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11261        if (DEBUG_SETTINGS) {
11262            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11263        }
11264
11265        synchronized (mPackages) {
11266            // Verify that all of the preferred activity components actually
11267            // exist.  It is possible for applications to be updated and at
11268            // that point remove a previously declared activity component that
11269            // had been set as a preferred activity.  We try to clean this up
11270            // the next time we encounter that preferred activity, but it is
11271            // possible for the user flow to never be able to return to that
11272            // situation so here we do a sanity check to make sure we haven't
11273            // left any junk around.
11274            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11275            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11276                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11277                removed.clear();
11278                for (PreferredActivity pa : pir.filterSet()) {
11279                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11280                        removed.add(pa);
11281                    }
11282                }
11283                if (removed.size() > 0) {
11284                    for (int j=0; j<removed.size(); j++) {
11285                        PreferredActivity pa = removed.get(i);
11286                        Slog.w(TAG, "Removing dangling preferred activity: "
11287                                + pa.mPref.mComponent);
11288                        pir.removeFilter(pa);
11289                    }
11290                    mSettings.writePackageRestrictionsLPr(
11291                            mSettings.mPreferredActivities.keyAt(i));
11292                }
11293            }
11294        }
11295        sUserManager.systemReady();
11296    }
11297
11298    public boolean isSafeMode() {
11299        return mSafeMode;
11300    }
11301
11302    public boolean hasSystemUidErrors() {
11303        return mHasSystemUidErrors;
11304    }
11305
11306    static String arrayToString(int[] array) {
11307        StringBuffer buf = new StringBuffer(128);
11308        buf.append('[');
11309        if (array != null) {
11310            for (int i=0; i<array.length; i++) {
11311                if (i > 0) buf.append(", ");
11312                buf.append(array[i]);
11313            }
11314        }
11315        buf.append(']');
11316        return buf.toString();
11317    }
11318
11319    static class DumpState {
11320        public static final int DUMP_LIBS = 1 << 0;
11321
11322        public static final int DUMP_FEATURES = 1 << 1;
11323
11324        public static final int DUMP_RESOLVERS = 1 << 2;
11325
11326        public static final int DUMP_PERMISSIONS = 1 << 3;
11327
11328        public static final int DUMP_PACKAGES = 1 << 4;
11329
11330        public static final int DUMP_SHARED_USERS = 1 << 5;
11331
11332        public static final int DUMP_MESSAGES = 1 << 6;
11333
11334        public static final int DUMP_PROVIDERS = 1 << 7;
11335
11336        public static final int DUMP_VERIFIERS = 1 << 8;
11337
11338        public static final int DUMP_PREFERRED = 1 << 9;
11339
11340        public static final int DUMP_PREFERRED_XML = 1 << 10;
11341
11342        public static final int DUMP_KEYSETS = 1 << 11;
11343
11344        public static final int DUMP_VERSION = 1 << 12;
11345
11346        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11347
11348        private int mTypes;
11349
11350        private int mOptions;
11351
11352        private boolean mTitlePrinted;
11353
11354        private SharedUserSetting mSharedUser;
11355
11356        public boolean isDumping(int type) {
11357            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11358                return true;
11359            }
11360
11361            return (mTypes & type) != 0;
11362        }
11363
11364        public void setDump(int type) {
11365            mTypes |= type;
11366        }
11367
11368        public boolean isOptionEnabled(int option) {
11369            return (mOptions & option) != 0;
11370        }
11371
11372        public void setOptionEnabled(int option) {
11373            mOptions |= option;
11374        }
11375
11376        public boolean onTitlePrinted() {
11377            final boolean printed = mTitlePrinted;
11378            mTitlePrinted = true;
11379            return printed;
11380        }
11381
11382        public boolean getTitlePrinted() {
11383            return mTitlePrinted;
11384        }
11385
11386        public void setTitlePrinted(boolean enabled) {
11387            mTitlePrinted = enabled;
11388        }
11389
11390        public SharedUserSetting getSharedUser() {
11391            return mSharedUser;
11392        }
11393
11394        public void setSharedUser(SharedUserSetting user) {
11395            mSharedUser = user;
11396        }
11397    }
11398
11399    @Override
11400    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11401        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11402                != PackageManager.PERMISSION_GRANTED) {
11403            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11404                    + Binder.getCallingPid()
11405                    + ", uid=" + Binder.getCallingUid()
11406                    + " without permission "
11407                    + android.Manifest.permission.DUMP);
11408            return;
11409        }
11410
11411        DumpState dumpState = new DumpState();
11412        boolean fullPreferred = false;
11413        boolean checkin = false;
11414
11415        String packageName = null;
11416
11417        int opti = 0;
11418        while (opti < args.length) {
11419            String opt = args[opti];
11420            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11421                break;
11422            }
11423            opti++;
11424            if ("-a".equals(opt)) {
11425                // Right now we only know how to print all.
11426            } else if ("-h".equals(opt)) {
11427                pw.println("Package manager dump options:");
11428                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11429                pw.println("    --checkin: dump for a checkin");
11430                pw.println("    -f: print details of intent filters");
11431                pw.println("    -h: print this help");
11432                pw.println("  cmd may be one of:");
11433                pw.println("    l[ibraries]: list known shared libraries");
11434                pw.println("    f[ibraries]: list device features");
11435                pw.println("    r[esolvers]: dump intent resolvers");
11436                pw.println("    perm[issions]: dump permissions");
11437                pw.println("    pref[erred]: print preferred package settings");
11438                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11439                pw.println("    prov[iders]: dump content providers");
11440                pw.println("    p[ackages]: dump installed packages");
11441                pw.println("    s[hared-users]: dump shared user IDs");
11442                pw.println("    m[essages]: print collected runtime messages");
11443                pw.println("    v[erifiers]: print package verifier info");
11444                pw.println("    version: print database version info");
11445                pw.println("    <package.name>: info about given package");
11446                pw.println("    k[eysets]: print known keysets");
11447                return;
11448            } else if ("--checkin".equals(opt)) {
11449                checkin = true;
11450            } else if ("-f".equals(opt)) {
11451                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11452            } else {
11453                pw.println("Unknown argument: " + opt + "; use -h for help");
11454            }
11455        }
11456
11457        // Is the caller requesting to dump a particular piece of data?
11458        if (opti < args.length) {
11459            String cmd = args[opti];
11460            opti++;
11461            // Is this a package name?
11462            if ("android".equals(cmd) || cmd.contains(".")) {
11463                packageName = cmd;
11464                // When dumping a single package, we always dump all of its
11465                // filter information since the amount of data will be reasonable.
11466                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11467            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11468                dumpState.setDump(DumpState.DUMP_LIBS);
11469            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11470                dumpState.setDump(DumpState.DUMP_FEATURES);
11471            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11472                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11473            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11474                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11475            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11476                dumpState.setDump(DumpState.DUMP_PREFERRED);
11477            } else if ("preferred-xml".equals(cmd)) {
11478                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11479                if (opti < args.length && "--full".equals(args[opti])) {
11480                    fullPreferred = true;
11481                    opti++;
11482                }
11483            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11484                dumpState.setDump(DumpState.DUMP_PACKAGES);
11485            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11486                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11487            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11488                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11489            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11490                dumpState.setDump(DumpState.DUMP_MESSAGES);
11491            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11492                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11493            } else if ("version".equals(cmd)) {
11494                dumpState.setDump(DumpState.DUMP_VERSION);
11495            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11496                dumpState.setDump(DumpState.DUMP_KEYSETS);
11497            }
11498        }
11499
11500        if (checkin) {
11501            pw.println("vers,1");
11502        }
11503
11504        // reader
11505        synchronized (mPackages) {
11506            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11507                if (!checkin) {
11508                    if (dumpState.onTitlePrinted())
11509                        pw.println();
11510                    pw.println("Database versions:");
11511                    pw.print("  SDK Version:");
11512                    pw.print(" internal=");
11513                    pw.print(mSettings.mInternalSdkPlatform);
11514                    pw.print(" external=");
11515                    pw.println(mSettings.mExternalSdkPlatform);
11516                    pw.print("  DB Version:");
11517                    pw.print(" internal=");
11518                    pw.print(mSettings.mInternalDatabaseVersion);
11519                    pw.print(" external=");
11520                    pw.println(mSettings.mExternalDatabaseVersion);
11521                }
11522            }
11523
11524            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11525                if (!checkin) {
11526                    if (dumpState.onTitlePrinted())
11527                        pw.println();
11528                    pw.println("Verifiers:");
11529                    pw.print("  Required: ");
11530                    pw.print(mRequiredVerifierPackage);
11531                    pw.print(" (uid=");
11532                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11533                    pw.println(")");
11534                } else if (mRequiredVerifierPackage != null) {
11535                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11536                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11537                }
11538            }
11539
11540            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11541                boolean printedHeader = false;
11542                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11543                while (it.hasNext()) {
11544                    String name = it.next();
11545                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11546                    if (!checkin) {
11547                        if (!printedHeader) {
11548                            if (dumpState.onTitlePrinted())
11549                                pw.println();
11550                            pw.println("Libraries:");
11551                            printedHeader = true;
11552                        }
11553                        pw.print("  ");
11554                    } else {
11555                        pw.print("lib,");
11556                    }
11557                    pw.print(name);
11558                    if (!checkin) {
11559                        pw.print(" -> ");
11560                    }
11561                    if (ent.path != null) {
11562                        if (!checkin) {
11563                            pw.print("(jar) ");
11564                            pw.print(ent.path);
11565                        } else {
11566                            pw.print(",jar,");
11567                            pw.print(ent.path);
11568                        }
11569                    } else {
11570                        if (!checkin) {
11571                            pw.print("(apk) ");
11572                            pw.print(ent.apk);
11573                        } else {
11574                            pw.print(",apk,");
11575                            pw.print(ent.apk);
11576                        }
11577                    }
11578                    pw.println();
11579                }
11580            }
11581
11582            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11583                if (dumpState.onTitlePrinted())
11584                    pw.println();
11585                if (!checkin) {
11586                    pw.println("Features:");
11587                }
11588                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11589                while (it.hasNext()) {
11590                    String name = it.next();
11591                    if (!checkin) {
11592                        pw.print("  ");
11593                    } else {
11594                        pw.print("feat,");
11595                    }
11596                    pw.println(name);
11597                }
11598            }
11599
11600            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11601                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11602                        : "Activity Resolver Table:", "  ", packageName,
11603                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11604                    dumpState.setTitlePrinted(true);
11605                }
11606                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11607                        : "Receiver Resolver Table:", "  ", packageName,
11608                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11609                    dumpState.setTitlePrinted(true);
11610                }
11611                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11612                        : "Service Resolver Table:", "  ", packageName,
11613                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11614                    dumpState.setTitlePrinted(true);
11615                }
11616                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11617                        : "Provider Resolver Table:", "  ", packageName,
11618                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11619                    dumpState.setTitlePrinted(true);
11620                }
11621            }
11622
11623            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11624                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11625                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11626                    int user = mSettings.mPreferredActivities.keyAt(i);
11627                    if (pir.dump(pw,
11628                            dumpState.getTitlePrinted()
11629                                ? "\nPreferred Activities User " + user + ":"
11630                                : "Preferred Activities User " + user + ":", "  ",
11631                            packageName, true)) {
11632                        dumpState.setTitlePrinted(true);
11633                    }
11634                }
11635            }
11636
11637            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11638                pw.flush();
11639                FileOutputStream fout = new FileOutputStream(fd);
11640                BufferedOutputStream str = new BufferedOutputStream(fout);
11641                XmlSerializer serializer = new FastXmlSerializer();
11642                try {
11643                    serializer.setOutput(str, "utf-8");
11644                    serializer.startDocument(null, true);
11645                    serializer.setFeature(
11646                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11647                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11648                    serializer.endDocument();
11649                    serializer.flush();
11650                } catch (IllegalArgumentException e) {
11651                    pw.println("Failed writing: " + e);
11652                } catch (IllegalStateException e) {
11653                    pw.println("Failed writing: " + e);
11654                } catch (IOException e) {
11655                    pw.println("Failed writing: " + e);
11656                }
11657            }
11658
11659            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11660                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11661            }
11662
11663            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11664                boolean printedSomething = false;
11665                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11666                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11667                        continue;
11668                    }
11669                    if (!printedSomething) {
11670                        if (dumpState.onTitlePrinted())
11671                            pw.println();
11672                        pw.println("Registered ContentProviders:");
11673                        printedSomething = true;
11674                    }
11675                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11676                    pw.print("    "); pw.println(p.toString());
11677                }
11678                printedSomething = false;
11679                for (Map.Entry<String, PackageParser.Provider> entry :
11680                        mProvidersByAuthority.entrySet()) {
11681                    PackageParser.Provider p = entry.getValue();
11682                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11683                        continue;
11684                    }
11685                    if (!printedSomething) {
11686                        if (dumpState.onTitlePrinted())
11687                            pw.println();
11688                        pw.println("ContentProvider Authorities:");
11689                        printedSomething = true;
11690                    }
11691                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11692                    pw.print("    "); pw.println(p.toString());
11693                    if (p.info != null && p.info.applicationInfo != null) {
11694                        final String appInfo = p.info.applicationInfo.toString();
11695                        pw.print("      applicationInfo="); pw.println(appInfo);
11696                    }
11697                }
11698            }
11699
11700            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11701                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11702            }
11703
11704            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11705                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11706            }
11707
11708            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11709                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11710            }
11711
11712            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11713                if (dumpState.onTitlePrinted())
11714                    pw.println();
11715                mSettings.dumpReadMessagesLPr(pw, dumpState);
11716
11717                pw.println();
11718                pw.println("Package warning messages:");
11719                final File fname = getSettingsProblemFile();
11720                FileInputStream in = null;
11721                try {
11722                    in = new FileInputStream(fname);
11723                    final int avail = in.available();
11724                    final byte[] data = new byte[avail];
11725                    in.read(data);
11726                    pw.print(new String(data));
11727                } catch (FileNotFoundException e) {
11728                } catch (IOException e) {
11729                } finally {
11730                    if (in != null) {
11731                        try {
11732                            in.close();
11733                        } catch (IOException e) {
11734                        }
11735                    }
11736                }
11737            }
11738        }
11739    }
11740
11741    // ------- apps on sdcard specific code -------
11742    static final boolean DEBUG_SD_INSTALL = false;
11743
11744    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11745
11746    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11747
11748    private boolean mMediaMounted = false;
11749
11750    private String getEncryptKey() {
11751        try {
11752            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11753                    SD_ENCRYPTION_KEYSTORE_NAME);
11754            if (sdEncKey == null) {
11755                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11756                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11757                if (sdEncKey == null) {
11758                    Slog.e(TAG, "Failed to create encryption keys");
11759                    return null;
11760                }
11761            }
11762            return sdEncKey;
11763        } catch (NoSuchAlgorithmException nsae) {
11764            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11765            return null;
11766        } catch (IOException ioe) {
11767            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11768            return null;
11769        }
11770
11771    }
11772
11773    /* package */static String getTempContainerId() {
11774        int tmpIdx = 1;
11775        String list[] = PackageHelper.getSecureContainerList();
11776        if (list != null) {
11777            for (final String name : list) {
11778                // Ignore null and non-temporary container entries
11779                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11780                    continue;
11781                }
11782
11783                String subStr = name.substring(mTempContainerPrefix.length());
11784                try {
11785                    int cid = Integer.parseInt(subStr);
11786                    if (cid >= tmpIdx) {
11787                        tmpIdx = cid + 1;
11788                    }
11789                } catch (NumberFormatException e) {
11790                }
11791            }
11792        }
11793        return mTempContainerPrefix + tmpIdx;
11794    }
11795
11796    /*
11797     * Update media status on PackageManager.
11798     */
11799    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11800        int callingUid = Binder.getCallingUid();
11801        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11802            throw new SecurityException("Media status can only be updated by the system");
11803        }
11804        // reader; this apparently protects mMediaMounted, but should probably
11805        // be a different lock in that case.
11806        synchronized (mPackages) {
11807            Log.i(TAG, "Updating external media status from "
11808                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11809                    + (mediaStatus ? "mounted" : "unmounted"));
11810            if (DEBUG_SD_INSTALL)
11811                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11812                        + ", mMediaMounted=" + mMediaMounted);
11813            if (mediaStatus == mMediaMounted) {
11814                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11815                        : 0, -1);
11816                mHandler.sendMessage(msg);
11817                return;
11818            }
11819            mMediaMounted = mediaStatus;
11820        }
11821        // Queue up an async operation since the package installation may take a
11822        // little while.
11823        mHandler.post(new Runnable() {
11824            public void run() {
11825                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11826            }
11827        });
11828    }
11829
11830    /**
11831     * Called by MountService when the initial ASECs to scan are available.
11832     * Should block until all the ASEC containers are finished being scanned.
11833     */
11834    public void scanAvailableAsecs() {
11835        updateExternalMediaStatusInner(true, false, false);
11836        if (mShouldRestoreconData) {
11837            SELinuxMMAC.setRestoreconDone();
11838            mShouldRestoreconData = false;
11839        }
11840    }
11841
11842    /*
11843     * Collect information of applications on external media, map them against
11844     * existing containers and update information based on current mount status.
11845     * Please note that we always have to report status if reportStatus has been
11846     * set to true especially when unloading packages.
11847     */
11848    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11849            boolean externalStorage) {
11850        // Collection of uids
11851        int uidArr[] = null;
11852        // Collection of stale containers
11853        HashSet<String> removeCids = new HashSet<String>();
11854        // Collection of packages on external media with valid containers.
11855        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11856        // Get list of secure containers.
11857        final String list[] = PackageHelper.getSecureContainerList();
11858        if (list == null || list.length == 0) {
11859            Log.i(TAG, "No secure containers on sdcard");
11860        } else {
11861            // Process list of secure containers and categorize them
11862            // as active or stale based on their package internal state.
11863            int uidList[] = new int[list.length];
11864            int num = 0;
11865            // reader
11866            synchronized (mPackages) {
11867                for (String cid : list) {
11868                    if (DEBUG_SD_INSTALL)
11869                        Log.i(TAG, "Processing container " + cid);
11870                    String pkgName = getAsecPackageName(cid);
11871                    if (pkgName == null) {
11872                        if (DEBUG_SD_INSTALL)
11873                            Log.i(TAG, "Container : " + cid + " stale");
11874                        removeCids.add(cid);
11875                        continue;
11876                    }
11877                    if (DEBUG_SD_INSTALL)
11878                        Log.i(TAG, "Looking for pkg : " + pkgName);
11879
11880                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11881                    if (ps == null) {
11882                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11883                        removeCids.add(cid);
11884                        continue;
11885                    }
11886
11887                    /*
11888                     * Skip packages that are not external if we're unmounting
11889                     * external storage.
11890                     */
11891                    if (externalStorage && !isMounted && !isExternal(ps)) {
11892                        continue;
11893                    }
11894
11895                    final AsecInstallArgs args = new AsecInstallArgs(cid,
11896                            getAppInstructionSetFromSettings(ps),
11897                            isForwardLocked(ps));
11898                    // The package status is changed only if the code path
11899                    // matches between settings and the container id.
11900                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11901                        if (DEBUG_SD_INSTALL) {
11902                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11903                                    + " at code path: " + ps.codePathString);
11904                        }
11905
11906                        // We do have a valid package installed on sdcard
11907                        processCids.put(args, ps.codePathString);
11908                        final int uid = ps.appId;
11909                        if (uid != -1) {
11910                            uidList[num++] = uid;
11911                        }
11912                    } else {
11913                        Log.i(TAG, "Deleting stale container for " + cid);
11914                        removeCids.add(cid);
11915                    }
11916                }
11917            }
11918
11919            if (num > 0) {
11920                // Sort uid list
11921                Arrays.sort(uidList, 0, num);
11922                // Throw away duplicates
11923                uidArr = new int[num];
11924                uidArr[0] = uidList[0];
11925                int di = 0;
11926                for (int i = 1; i < num; i++) {
11927                    if (uidList[i - 1] != uidList[i]) {
11928                        uidArr[di++] = uidList[i];
11929                    }
11930                }
11931            }
11932        }
11933        // Process packages with valid entries.
11934        if (isMounted) {
11935            if (DEBUG_SD_INSTALL)
11936                Log.i(TAG, "Loading packages");
11937            loadMediaPackages(processCids, uidArr, removeCids);
11938            startCleaningPackages();
11939        } else {
11940            if (DEBUG_SD_INSTALL)
11941                Log.i(TAG, "Unloading packages");
11942            unloadMediaPackages(processCids, uidArr, reportStatus);
11943        }
11944    }
11945
11946   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11947           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11948        int size = pkgList.size();
11949        if (size > 0) {
11950            // Send broadcasts here
11951            Bundle extras = new Bundle();
11952            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11953                    .toArray(new String[size]));
11954            if (uidArr != null) {
11955                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11956            }
11957            if (replacing) {
11958                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11959            }
11960            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11961                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11962            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11963        }
11964    }
11965
11966   /*
11967     * Look at potentially valid container ids from processCids If package
11968     * information doesn't match the one on record or package scanning fails,
11969     * the cid is added to list of removeCids. We currently don't delete stale
11970     * containers.
11971     */
11972   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11973            HashSet<String> removeCids) {
11974        ArrayList<String> pkgList = new ArrayList<String>();
11975        Set<AsecInstallArgs> keys = processCids.keySet();
11976        boolean doGc = false;
11977        for (AsecInstallArgs args : keys) {
11978            String codePath = processCids.get(args);
11979            if (DEBUG_SD_INSTALL)
11980                Log.i(TAG, "Loading container : " + args.cid);
11981            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11982            try {
11983                // Make sure there are no container errors first.
11984                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11985                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11986                            + " when installing from sdcard");
11987                    continue;
11988                }
11989                // Check code path here.
11990                if (codePath == null || !codePath.equals(args.getCodePath())) {
11991                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11992                            + " does not match one in settings " + codePath);
11993                    continue;
11994                }
11995                // Parse package
11996                int parseFlags = mDefParseFlags;
11997                if (args.isExternal()) {
11998                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11999                }
12000                if (args.isFwdLocked()) {
12001                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12002                }
12003
12004                doGc = true;
12005                synchronized (mInstallLock) {
12006                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12007                            0, 0, null);
12008                    // Scan the package
12009                    if (pkg != null) {
12010                        /*
12011                         * TODO why is the lock being held? doPostInstall is
12012                         * called in other places without the lock. This needs
12013                         * to be straightened out.
12014                         */
12015                        // writer
12016                        synchronized (mPackages) {
12017                            retCode = PackageManager.INSTALL_SUCCEEDED;
12018                            pkgList.add(pkg.packageName);
12019                            // Post process args
12020                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12021                                    pkg.applicationInfo.uid);
12022                        }
12023                    } else {
12024                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12025                    }
12026                }
12027
12028            } finally {
12029                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12030                    // Don't destroy container here. Wait till gc clears things
12031                    // up.
12032                    removeCids.add(args.cid);
12033                }
12034            }
12035        }
12036        // writer
12037        synchronized (mPackages) {
12038            // If the platform SDK has changed since the last time we booted,
12039            // we need to re-grant app permission to catch any new ones that
12040            // appear. This is really a hack, and means that apps can in some
12041            // cases get permissions that the user didn't initially explicitly
12042            // allow... it would be nice to have some better way to handle
12043            // this situation.
12044            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12045            if (regrantPermissions)
12046                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12047                        + mSdkVersion + "; regranting permissions for external storage");
12048            mSettings.mExternalSdkPlatform = mSdkVersion;
12049
12050            // Make sure group IDs have been assigned, and any permission
12051            // changes in other apps are accounted for
12052            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12053                    | (regrantPermissions
12054                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12055                            : 0));
12056
12057            mSettings.updateExternalDatabaseVersion();
12058
12059            // can downgrade to reader
12060            // Persist settings
12061            mSettings.writeLPr();
12062        }
12063        // Send a broadcast to let everyone know we are done processing
12064        if (pkgList.size() > 0) {
12065            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12066        }
12067        // Force gc to avoid any stale parser references that we might have.
12068        if (doGc) {
12069            Runtime.getRuntime().gc();
12070        }
12071        // List stale containers and destroy stale temporary containers.
12072        if (removeCids != null) {
12073            for (String cid : removeCids) {
12074                if (cid.startsWith(mTempContainerPrefix)) {
12075                    Log.i(TAG, "Destroying stale temporary container " + cid);
12076                    PackageHelper.destroySdDir(cid);
12077                } else {
12078                    Log.w(TAG, "Container " + cid + " is stale");
12079               }
12080           }
12081        }
12082    }
12083
12084   /*
12085     * Utility method to unload a list of specified containers
12086     */
12087    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12088        // Just unmount all valid containers.
12089        for (AsecInstallArgs arg : cidArgs) {
12090            synchronized (mInstallLock) {
12091                arg.doPostDeleteLI(false);
12092           }
12093       }
12094   }
12095
12096    /*
12097     * Unload packages mounted on external media. This involves deleting package
12098     * data from internal structures, sending broadcasts about diabled packages,
12099     * gc'ing to free up references, unmounting all secure containers
12100     * corresponding to packages on external media, and posting a
12101     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12102     * that we always have to post this message if status has been requested no
12103     * matter what.
12104     */
12105    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12106            final boolean reportStatus) {
12107        if (DEBUG_SD_INSTALL)
12108            Log.i(TAG, "unloading media packages");
12109        ArrayList<String> pkgList = new ArrayList<String>();
12110        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12111        final Set<AsecInstallArgs> keys = processCids.keySet();
12112        for (AsecInstallArgs args : keys) {
12113            String pkgName = args.getPackageName();
12114            if (DEBUG_SD_INSTALL)
12115                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12116            // Delete package internally
12117            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12118            synchronized (mInstallLock) {
12119                boolean res = deletePackageLI(pkgName, null, false, null, null,
12120                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12121                if (res) {
12122                    pkgList.add(pkgName);
12123                } else {
12124                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12125                    failedList.add(args);
12126                }
12127            }
12128        }
12129
12130        // reader
12131        synchronized (mPackages) {
12132            // We didn't update the settings after removing each package;
12133            // write them now for all packages.
12134            mSettings.writeLPr();
12135        }
12136
12137        // We have to absolutely send UPDATED_MEDIA_STATUS only
12138        // after confirming that all the receivers processed the ordered
12139        // broadcast when packages get disabled, force a gc to clean things up.
12140        // and unload all the containers.
12141        if (pkgList.size() > 0) {
12142            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12143                    new IIntentReceiver.Stub() {
12144                public void performReceive(Intent intent, int resultCode, String data,
12145                        Bundle extras, boolean ordered, boolean sticky,
12146                        int sendingUser) throws RemoteException {
12147                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12148                            reportStatus ? 1 : 0, 1, keys);
12149                    mHandler.sendMessage(msg);
12150                }
12151            });
12152        } else {
12153            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12154                    keys);
12155            mHandler.sendMessage(msg);
12156        }
12157    }
12158
12159    /** Binder call */
12160    @Override
12161    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12162            final int flags) {
12163        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12164        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12165        int returnCode = PackageManager.MOVE_SUCCEEDED;
12166        int currFlags = 0;
12167        int newFlags = 0;
12168        // reader
12169        synchronized (mPackages) {
12170            PackageParser.Package pkg = mPackages.get(packageName);
12171            if (pkg == null) {
12172                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12173            } else {
12174                // Disable moving fwd locked apps and system packages
12175                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12176                    Slog.w(TAG, "Cannot move system application");
12177                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12178                } else if (pkg.mOperationPending) {
12179                    Slog.w(TAG, "Attempt to move package which has pending operations");
12180                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12181                } else {
12182                    // Find install location first
12183                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12184                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12185                        Slog.w(TAG, "Ambigous flags specified for move location.");
12186                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12187                    } else {
12188                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12189                                : PackageManager.INSTALL_INTERNAL;
12190                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12191                                : PackageManager.INSTALL_INTERNAL;
12192
12193                        if (newFlags == currFlags) {
12194                            Slog.w(TAG, "No move required. Trying to move to same location");
12195                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12196                        } else {
12197                            if (isForwardLocked(pkg)) {
12198                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12199                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12200                            }
12201                        }
12202                    }
12203                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12204                        pkg.mOperationPending = true;
12205                    }
12206                }
12207            }
12208
12209            /*
12210             * TODO this next block probably shouldn't be inside the lock. We
12211             * can't guarantee these won't change after this is fired off
12212             * anyway.
12213             */
12214            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12215                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12216                        null, -1, user),
12217                        returnCode);
12218            } else {
12219                Message msg = mHandler.obtainMessage(INIT_COPY);
12220                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12221                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12222                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12223                        instructionSet);
12224                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12225                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12226                msg.obj = mp;
12227                mHandler.sendMessage(msg);
12228            }
12229        }
12230    }
12231
12232    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12233        // Queue up an async operation since the package deletion may take a
12234        // little while.
12235        mHandler.post(new Runnable() {
12236            public void run() {
12237                // TODO fix this; this does nothing.
12238                mHandler.removeCallbacks(this);
12239                int returnCode = currentStatus;
12240                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12241                    int uidArr[] = null;
12242                    ArrayList<String> pkgList = null;
12243                    synchronized (mPackages) {
12244                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12245                        if (pkg == null) {
12246                            Slog.w(TAG, " Package " + mp.packageName
12247                                    + " doesn't exist. Aborting move");
12248                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12249                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12250                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12251                                    + mp.srcArgs.getCodePath() + " to "
12252                                    + pkg.applicationInfo.sourceDir
12253                                    + " Aborting move and returning error");
12254                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12255                        } else {
12256                            uidArr = new int[] {
12257                                pkg.applicationInfo.uid
12258                            };
12259                            pkgList = new ArrayList<String>();
12260                            pkgList.add(mp.packageName);
12261                        }
12262                    }
12263                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12264                        // Send resources unavailable broadcast
12265                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12266                        // Update package code and resource paths
12267                        synchronized (mInstallLock) {
12268                            synchronized (mPackages) {
12269                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12270                                // Recheck for package again.
12271                                if (pkg == null) {
12272                                    Slog.w(TAG, " Package " + mp.packageName
12273                                            + " doesn't exist. Aborting move");
12274                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12275                                } else if (!mp.srcArgs.getCodePath().equals(
12276                                        pkg.applicationInfo.sourceDir)) {
12277                                    Slog.w(TAG, "Package " + mp.packageName
12278                                            + " code path changed from " + mp.srcArgs.getCodePath()
12279                                            + " to " + pkg.applicationInfo.sourceDir
12280                                            + " Aborting move and returning error");
12281                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12282                                } else {
12283                                    final String oldCodePath = pkg.mPath;
12284                                    final String newCodePath = mp.targetArgs.getCodePath();
12285                                    final String newResPath = mp.targetArgs.getResourcePath();
12286                                    final String newNativePath = mp.targetArgs
12287                                            .getNativeLibraryPath();
12288
12289                                    final File newNativeDir = new File(newNativePath);
12290
12291                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12292                                        // NOTE: We do not report any errors from the APK scan and library
12293                                        // copy at this point.
12294                                        NativeLibraryHelper.ApkHandle handle =
12295                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12296                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12297                                                handle, Build.SUPPORTED_ABIS);
12298                                        if (abi >= 0) {
12299                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12300                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12301                                        }
12302                                        handle.close();
12303                                    }
12304                                    final int[] users = sUserManager.getUserIds();
12305                                    for (int user : users) {
12306                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12307                                                newNativePath, user) < 0) {
12308                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12309                                        }
12310                                    }
12311
12312                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12313                                        pkg.mPath = newCodePath;
12314                                        // Move dex files around
12315                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12316                                            // Moving of dex files failed. Set
12317                                            // error code and abort move.
12318                                            pkg.mPath = pkg.mScanPath;
12319                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12320                                        }
12321                                    }
12322
12323                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12324                                        pkg.mScanPath = newCodePath;
12325                                        pkg.applicationInfo.sourceDir = newCodePath;
12326                                        pkg.applicationInfo.publicSourceDir = newResPath;
12327                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12328                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12329                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12330                                        ps.codePathString = ps.codePath.getPath();
12331                                        ps.resourcePath = new File(
12332                                                pkg.applicationInfo.publicSourceDir);
12333                                        ps.resourcePathString = ps.resourcePath.getPath();
12334                                        ps.nativeLibraryPathString = newNativePath;
12335                                        // Set the application info flag
12336                                        // correctly.
12337                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12338                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12339                                        } else {
12340                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12341                                        }
12342                                        ps.setFlags(pkg.applicationInfo.flags);
12343                                        mAppDirs.remove(oldCodePath);
12344                                        mAppDirs.put(newCodePath, pkg);
12345                                        // Persist settings
12346                                        mSettings.writeLPr();
12347                                    }
12348                                }
12349                            }
12350                        }
12351                        // Send resources available broadcast
12352                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12353                    }
12354                }
12355                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12356                    // Clean up failed installation
12357                    if (mp.targetArgs != null) {
12358                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12359                                -1);
12360                    }
12361                } else {
12362                    // Force a gc to clear things up.
12363                    Runtime.getRuntime().gc();
12364                    // Delete older code
12365                    synchronized (mInstallLock) {
12366                        mp.srcArgs.doPostDeleteLI(true);
12367                    }
12368                }
12369
12370                // Allow more operations on this file if we didn't fail because
12371                // an operation was already pending for this package.
12372                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12373                    synchronized (mPackages) {
12374                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12375                        if (pkg != null) {
12376                            pkg.mOperationPending = false;
12377                       }
12378                   }
12379                }
12380
12381                IPackageMoveObserver observer = mp.observer;
12382                if (observer != null) {
12383                    try {
12384                        observer.packageMoved(mp.packageName, returnCode);
12385                    } catch (RemoteException e) {
12386                        Log.i(TAG, "Observer no longer exists.");
12387                    }
12388                }
12389            }
12390        });
12391    }
12392
12393    public boolean setInstallLocation(int loc) {
12394        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12395                null);
12396        if (getInstallLocation() == loc) {
12397            return true;
12398        }
12399        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12400                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12401            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12402                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12403            return true;
12404        }
12405        return false;
12406   }
12407
12408    public int getInstallLocation() {
12409        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12410                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12411                PackageHelper.APP_INSTALL_AUTO);
12412    }
12413
12414    /** Called by UserManagerService */
12415    void cleanUpUserLILPw(int userHandle) {
12416        mDirtyUsers.remove(userHandle);
12417        mSettings.removeUserLPr(userHandle);
12418        mPendingBroadcasts.remove(userHandle);
12419        if (mInstaller != null) {
12420            // Technically, we shouldn't be doing this with the package lock
12421            // held.  However, this is very rare, and there is already so much
12422            // other disk I/O going on, that we'll let it slide for now.
12423            mInstaller.removeUserDataDirs(userHandle);
12424        }
12425    }
12426
12427    /** Called by UserManagerService */
12428    void createNewUserLILPw(int userHandle, File path) {
12429        if (mInstaller != null) {
12430            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12431        }
12432    }
12433
12434    @Override
12435    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12436        mContext.enforceCallingOrSelfPermission(
12437                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12438                "Only package verification agents can read the verifier device identity");
12439
12440        synchronized (mPackages) {
12441            return mSettings.getVerifierDeviceIdentityLPw();
12442        }
12443    }
12444
12445    @Override
12446    public void setPermissionEnforced(String permission, boolean enforced) {
12447        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12448        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12449            synchronized (mPackages) {
12450                if (mSettings.mReadExternalStorageEnforced == null
12451                        || mSettings.mReadExternalStorageEnforced != enforced) {
12452                    mSettings.mReadExternalStorageEnforced = enforced;
12453                    mSettings.writeLPr();
12454                }
12455            }
12456            // kill any non-foreground processes so we restart them and
12457            // grant/revoke the GID.
12458            final IActivityManager am = ActivityManagerNative.getDefault();
12459            if (am != null) {
12460                final long token = Binder.clearCallingIdentity();
12461                try {
12462                    am.killProcessesBelowForeground("setPermissionEnforcement");
12463                } catch (RemoteException e) {
12464                } finally {
12465                    Binder.restoreCallingIdentity(token);
12466                }
12467            }
12468        } else {
12469            throw new IllegalArgumentException("No selective enforcement for " + permission);
12470        }
12471    }
12472
12473    @Override
12474    @Deprecated
12475    public boolean isPermissionEnforced(String permission) {
12476        return true;
12477    }
12478
12479    @Override
12480    public boolean isStorageLow() {
12481        final long token = Binder.clearCallingIdentity();
12482        try {
12483            final DeviceStorageMonitorInternal
12484                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12485            if (dsm != null) {
12486                return dsm.isMemoryLow();
12487            } else {
12488                return false;
12489            }
12490        } finally {
12491            Binder.restoreCallingIdentity(token);
12492        }
12493    }
12494}
12495