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