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