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