PackageManagerService.java revision f230061b383f3e5fa63a266d84477963dc5f226c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.system.OsConstants.S_IRWXU;
27import static android.system.OsConstants.S_IRGRP;
28import static android.system.OsConstants.S_IXGRP;
29import static android.system.OsConstants.S_IROTH;
30import static android.system.OsConstants.S_IXOTH;
31import static android.os.Process.PACKAGE_INFO_GID;
32import static android.os.Process.SYSTEM_UID;
33import static com.android.internal.util.ArrayUtils.appendInt;
34import static com.android.internal.util.ArrayUtils.removeInt;
35
36import com.android.internal.R;
37import com.android.internal.app.IMediaContainerService;
38import com.android.internal.app.ResolverActivity;
39import com.android.internal.content.NativeLibraryHelper;
40import com.android.internal.content.PackageHelper;
41import com.android.internal.util.FastPrintWriter;
42import com.android.internal.util.FastXmlSerializer;
43import com.android.internal.util.XmlUtils;
44import com.android.server.EventLogTags;
45import com.android.server.IntentResolver;
46import com.android.server.LocalServices;
47import com.android.server.ServiceThread;
48import com.android.server.Watchdog;
49import com.android.server.storage.DeviceStorageMonitorInternal;
50
51import org.xmlpull.v1.XmlPullParser;
52import org.xmlpull.v1.XmlPullParserException;
53import org.xmlpull.v1.XmlSerializer;
54
55import android.app.ActivityManager;
56import android.app.ActivityManagerNative;
57import android.app.IActivityManager;
58import android.app.admin.IDevicePolicyManager;
59import android.app.backup.IBackupManager;
60import android.content.BroadcastReceiver;
61import android.content.ComponentName;
62import android.content.Context;
63import android.content.IIntentReceiver;
64import android.content.Intent;
65import android.content.IntentFilter;
66import android.content.IntentSender;
67import android.content.IntentSender.SendIntentException;
68import android.content.ServiceConnection;
69import android.content.pm.ActivityInfo;
70import android.content.pm.ApplicationInfo;
71import android.content.pm.ContainerEncryptionParams;
72import android.content.pm.FeatureInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageDeleteObserver;
75import android.content.pm.IPackageInstallObserver;
76import android.content.pm.IPackageManager;
77import android.content.pm.IPackageMoveObserver;
78import android.content.pm.IPackageStatsObserver;
79import android.content.pm.InstrumentationInfo;
80import android.content.pm.ManifestDigest;
81import android.content.pm.PackageCleanItem;
82import android.content.pm.PackageInfo;
83import android.content.pm.PackageInfoLite;
84import android.content.pm.PackageManager;
85import android.content.pm.PackageParser.ActivityIntentInfo;
86import android.content.pm.PackageParser;
87import android.content.pm.PackageStats;
88import android.content.pm.PackageUserState;
89import android.content.pm.ParceledListSlice;
90import android.content.pm.PermissionGroupInfo;
91import android.content.pm.PermissionInfo;
92import android.content.pm.ProviderInfo;
93import android.content.pm.ResolveInfo;
94import android.content.pm.ServiceInfo;
95import android.content.pm.Signature;
96import android.content.pm.VerificationParams;
97import android.content.pm.VerifierDeviceIdentity;
98import android.content.pm.VerifierInfo;
99import android.content.res.Resources;
100import android.hardware.display.DisplayManager;
101import android.net.Uri;
102import android.os.Binder;
103import android.os.Build;
104import android.os.Bundle;
105import android.os.Environment;
106import android.os.Environment.UserEnvironment;
107import android.os.FileObserver;
108import android.os.FileUtils;
109import android.os.Handler;
110import android.os.IBinder;
111import android.os.Looper;
112import android.os.Message;
113import android.os.Parcel;
114import android.os.ParcelFileDescriptor;
115import android.os.Process;
116import android.os.RemoteException;
117import android.os.SELinux;
118import android.os.ServiceManager;
119import android.os.SystemClock;
120import android.os.SystemProperties;
121import android.os.UserHandle;
122import android.os.UserManager;
123import android.security.KeyStore;
124import android.security.SystemKeyStore;
125import android.system.ErrnoException;
126import android.system.Os;
127import android.system.StructStat;
128import android.text.TextUtils;
129import android.util.AtomicFile;
130import android.util.DisplayMetrics;
131import android.util.EventLog;
132import android.util.Log;
133import android.util.LogPrinter;
134import android.util.PrintStreamPrinter;
135import android.util.Slog;
136import android.util.SparseArray;
137import android.util.Xml;
138import android.view.Display;
139
140import java.io.BufferedInputStream;
141import java.io.BufferedOutputStream;
142import java.io.File;
143import java.io.FileDescriptor;
144import java.io.FileInputStream;
145import java.io.FileNotFoundException;
146import java.io.FileOutputStream;
147import java.io.FileReader;
148import java.io.FilenameFilter;
149import java.io.IOException;
150import java.io.InputStream;
151import java.io.PrintWriter;
152import java.nio.charset.StandardCharsets;
153import java.security.NoSuchAlgorithmException;
154import java.security.PublicKey;
155import java.security.cert.CertificateException;
156import java.text.SimpleDateFormat;
157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.Collection;
160import java.util.Collections;
161import java.util.Comparator;
162import java.util.Date;
163import java.util.HashMap;
164import java.util.HashSet;
165import java.util.Iterator;
166import java.util.List;
167import java.util.Map;
168import java.util.Set;
169import java.util.concurrent.atomic.AtomicBoolean;
170import java.util.concurrent.atomic.AtomicLong;
171
172import dalvik.system.DexFile;
173import dalvik.system.StaleDexCacheError;
174import dalvik.system.VMRuntime;
175import libcore.io.IoUtils;
176
177/**
178 * Keep track of all those .apks everywhere.
179 *
180 * This is very central to the platform's security; please run the unit
181 * tests whenever making modifications here:
182 *
183mmm frameworks/base/tests/AndroidTests
184adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
185adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
186 *
187 * {@hide}
188 */
189public class PackageManagerService extends IPackageManager.Stub {
190    static final String TAG = "PackageManager";
191    static final boolean DEBUG_SETTINGS = false;
192    static final boolean DEBUG_PREFERRED = false;
193    static final boolean DEBUG_UPGRADE = false;
194    private static final boolean DEBUG_INSTALL = false;
195    private static final boolean DEBUG_REMOVE = false;
196    private static final boolean DEBUG_BROADCASTS = false;
197    private static final boolean DEBUG_SHOW_INFO = false;
198    private static final boolean DEBUG_PACKAGE_INFO = false;
199    private static final boolean DEBUG_INTENT_MATCHING = false;
200    private static final boolean DEBUG_PACKAGE_SCANNING = false;
201    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
202    private static final boolean DEBUG_VERIFY = false;
203    private static final boolean DEBUG_DEXOPT = false;
204
205    private static final int RADIO_UID = Process.PHONE_UID;
206    private static final int LOG_UID = Process.LOG_UID;
207    private static final int NFC_UID = Process.NFC_UID;
208    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
209    private static final int SHELL_UID = Process.SHELL_UID;
210
211    private static final boolean GET_CERTIFICATES = true;
212
213    private static final int REMOVE_EVENTS =
214        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
215    private static final int ADD_EVENTS =
216        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
217
218    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
219    // Suffix used during package installation when copying/moving
220    // package apks to install directory.
221    private static final String INSTALL_PACKAGE_SUFFIX = "-";
222
223    static final int SCAN_MONITOR = 1<<0;
224    static final int SCAN_NO_DEX = 1<<1;
225    static final int SCAN_FORCE_DEX = 1<<2;
226    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
227    static final int SCAN_NEW_INSTALL = 1<<4;
228    static final int SCAN_NO_PATHS = 1<<5;
229    static final int SCAN_UPDATE_TIME = 1<<6;
230    static final int SCAN_DEFER_DEX = 1<<7;
231    static final int SCAN_BOOTING = 1<<8;
232    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
233    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
234
235    static final int REMOVE_CHATTY = 1<<16;
236
237    /**
238     * Timeout (in milliseconds) after which the watchdog should declare that
239     * our handler thread is wedged.  The usual default for such things is one
240     * minute but we sometimes do very lengthy I/O operations on this thread,
241     * such as installing multi-gigabyte applications, so ours needs to be longer.
242     */
243    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
244
245    /**
246     * Whether verification is enabled by default.
247     */
248    private static final boolean DEFAULT_VERIFY_ENABLE = true;
249
250    /**
251     * The default maximum time to wait for the verification agent to return in
252     * milliseconds.
253     */
254    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
255
256    /**
257     * The default response for package verification timeout.
258     *
259     * This can be either PackageManager.VERIFICATION_ALLOW or
260     * PackageManager.VERIFICATION_REJECT.
261     */
262    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
263
264    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
265
266    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
267            DEFAULT_CONTAINER_PACKAGE,
268            "com.android.defcontainer.DefaultContainerService");
269
270    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
271
272    private static final String LIB_DIR_NAME = "lib";
273    private static final String LIB64_DIR_NAME = "lib64";
274
275    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
276
277    static final String mTempContainerPrefix = "smdl2tmp";
278
279    final ServiceThread mHandlerThread;
280
281    private static String sPreferredInstructionSet;
282
283    private static final String IDMAP_PREFIX = "/data/resource-cache/";
284    private static final String IDMAP_SUFFIX = "@idmap";
285
286    final PackageHandler mHandler;
287
288    final int mSdkVersion = Build.VERSION.SDK_INT;
289    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
290            ? null : Build.VERSION.CODENAME;
291
292    final Context mContext;
293    final boolean mFactoryTest;
294    final boolean mOnlyCore;
295    final DisplayMetrics mMetrics;
296    final int mDefParseFlags;
297    final String[] mSeparateProcesses;
298
299    // This is where all application persistent data goes.
300    final File mAppDataDir;
301
302    // This is where all application persistent data goes for secondary users.
303    final File mUserAppDataDir;
304
305    /** The location for ASEC container files on internal storage. */
306    final String mAsecInternalPath;
307
308    // This is the object monitoring the framework dir.
309    final FileObserver mFrameworkInstallObserver;
310
311    // This is the object monitoring the system app dir.
312    final FileObserver mSystemInstallObserver;
313
314    // This is the object monitoring the privileged system app dir.
315    final FileObserver mPrivilegedInstallObserver;
316
317    // This is the object monitoring the system app dir.
318    final FileObserver mVendorInstallObserver;
319
320    // This is the object monitoring the vendor overlay package dir.
321    final FileObserver mVendorOverlayInstallObserver;
322
323    // This is the object monitoring mAppInstallDir.
324    final FileObserver mAppInstallObserver;
325
326    // This is the object monitoring mDrmAppPrivateInstallDir.
327    final FileObserver mDrmAppInstallObserver;
328
329    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
330    // LOCK HELD.  Can be called with mInstallLock held.
331    final Installer mInstaller;
332
333    final File mAppInstallDir;
334
335    /**
336     * Directory to which applications installed internally have native
337     * libraries copied.
338     */
339    private File mAppLibInstallDir;
340
341    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
342    // apps.
343    final File mDrmAppPrivateInstallDir;
344
345    // ----------------------------------------------------------------
346
347    // Lock for state used when installing and doing other long running
348    // operations.  Methods that must be called with this lock held have
349    // the prefix "LI".
350    final Object mInstallLock = new Object();
351
352    // These are the directories in the 3rd party applications installed dir
353    // that we have currently loaded packages from.  Keys are the application's
354    // installed zip file (absolute codePath), and values are Package.
355    final HashMap<String, PackageParser.Package> mAppDirs =
356            new HashMap<String, PackageParser.Package>();
357
358    // Information for the parser to write more useful error messages.
359    int mLastScanError;
360
361    // ----------------------------------------------------------------
362
363    // Keys are String (package name), values are Package.  This also serves
364    // as the lock for the global state.  Methods that must be called with
365    // this lock held have the prefix "LP".
366    final HashMap<String, PackageParser.Package> mPackages =
367            new HashMap<String, PackageParser.Package>();
368
369    // Tracks available target package names -> overlay package paths.
370    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
371        new HashMap<String, HashMap<String, PackageParser.Package>>();
372
373    final Settings mSettings;
374    boolean mRestoredSettings;
375
376    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
377    int[] mGlobalGids;
378
379    // These are the built-in uid -> permission mappings that were read from the
380    // etc/permissions.xml file.
381    final SparseArray<HashSet<String>> mSystemPermissions =
382            new SparseArray<HashSet<String>>();
383
384    static final class SharedLibraryEntry {
385        final String path;
386        final String apk;
387
388        SharedLibraryEntry(String _path, String _apk) {
389            path = _path;
390            apk = _apk;
391        }
392    }
393
394    // These are the built-in shared libraries that were read from the
395    // etc/permissions.xml file.
396    final HashMap<String, SharedLibraryEntry> mSharedLibraries
397            = new HashMap<String, SharedLibraryEntry>();
398
399    // Temporary for building the final shared libraries for an .apk.
400    String[] mTmpSharedLibraries = null;
401
402    // These are the features this devices supports that were read from the
403    // etc/permissions.xml file.
404    final HashMap<String, FeatureInfo> mAvailableFeatures =
405            new HashMap<String, FeatureInfo>();
406
407    // If mac_permissions.xml was found for seinfo labeling.
408    boolean mFoundPolicyFile;
409
410    // If a recursive restorecon of /data/data/<pkg> is needed.
411    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
412
413    // All available activities, for your resolving pleasure.
414    final ActivityIntentResolver mActivities =
415            new ActivityIntentResolver();
416
417    // All available receivers, for your resolving pleasure.
418    final ActivityIntentResolver mReceivers =
419            new ActivityIntentResolver();
420
421    // All available services, for your resolving pleasure.
422    final ServiceIntentResolver mServices = new ServiceIntentResolver();
423
424    // All available providers, for your resolving pleasure.
425    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
426
427    // Mapping from provider base names (first directory in content URI codePath)
428    // to the provider information.
429    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
430            new HashMap<String, PackageParser.Provider>();
431
432    // Mapping from instrumentation class names to info about them.
433    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
434            new HashMap<ComponentName, PackageParser.Instrumentation>();
435
436    // Mapping from permission names to info about them.
437    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
438            new HashMap<String, PackageParser.PermissionGroup>();
439
440    // Packages whose data we have transfered into another package, thus
441    // should no longer exist.
442    final HashSet<String> mTransferedPackages = new HashSet<String>();
443
444    // Broadcast actions that are only available to the system.
445    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
446
447    /** List of packages waiting for verification. */
448    final SparseArray<PackageVerificationState> mPendingVerification
449            = new SparseArray<PackageVerificationState>();
450
451    HashSet<PackageParser.Package> mDeferredDexOpt = null;
452
453    /** Token for keys in mPendingVerification. */
454    private int mPendingVerificationToken = 0;
455
456    boolean mSystemReady;
457    boolean mSafeMode;
458    boolean mHasSystemUidErrors;
459
460    ApplicationInfo mAndroidApplication;
461    final ActivityInfo mResolveActivity = new ActivityInfo();
462    final ResolveInfo mResolveInfo = new ResolveInfo();
463    ComponentName mResolveComponentName;
464    PackageParser.Package mPlatformPackage;
465    ComponentName mCustomResolverComponentName;
466
467    boolean mResolverReplaced = false;
468
469    // Set of pending broadcasts for aggregating enable/disable of components.
470    static class PendingPackageBroadcasts {
471        // for each user id, a map of <package name -> components within that package>
472        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
473
474        public PendingPackageBroadcasts() {
475            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
476        }
477
478        public ArrayList<String> get(int userId, String packageName) {
479            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
480            return packages.get(packageName);
481        }
482
483        public void put(int userId, String packageName, ArrayList<String> components) {
484            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
485            packages.put(packageName, components);
486        }
487
488        public void remove(int userId, String packageName) {
489            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
490            if (packages != null) {
491                packages.remove(packageName);
492            }
493        }
494
495        public void remove(int userId) {
496            mUidMap.remove(userId);
497        }
498
499        public int userIdCount() {
500            return mUidMap.size();
501        }
502
503        public int userIdAt(int n) {
504            return mUidMap.keyAt(n);
505        }
506
507        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
508            return mUidMap.get(userId);
509        }
510
511        public int size() {
512            // total number of pending broadcast entries across all userIds
513            int num = 0;
514            for (int i = 0; i< mUidMap.size(); i++) {
515                num += mUidMap.valueAt(i).size();
516            }
517            return num;
518        }
519
520        public void clear() {
521            mUidMap.clear();
522        }
523
524        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
525            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
526            if (map == null) {
527                map = new HashMap<String, ArrayList<String>>();
528                mUidMap.put(userId, map);
529            }
530            return map;
531        }
532    }
533    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
534
535    // Service Connection to remote media container service to copy
536    // package uri's from external media onto secure containers
537    // or internal storage.
538    private IMediaContainerService mContainerService = null;
539
540    static final int SEND_PENDING_BROADCAST = 1;
541    static final int MCS_BOUND = 3;
542    static final int END_COPY = 4;
543    static final int INIT_COPY = 5;
544    static final int MCS_UNBIND = 6;
545    static final int START_CLEANING_PACKAGE = 7;
546    static final int FIND_INSTALL_LOC = 8;
547    static final int POST_INSTALL = 9;
548    static final int MCS_RECONNECT = 10;
549    static final int MCS_GIVE_UP = 11;
550    static final int UPDATED_MEDIA_STATUS = 12;
551    static final int WRITE_SETTINGS = 13;
552    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
553    static final int PACKAGE_VERIFIED = 15;
554    static final int CHECK_PENDING_VERIFICATION = 16;
555
556    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
557
558    // Delay time in millisecs
559    static final int BROADCAST_DELAY = 10 * 1000;
560
561    static UserManagerService sUserManager;
562
563    // Stores a list of users whose package restrictions file needs to be updated
564    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
565
566    final private DefaultContainerConnection mDefContainerConn =
567            new DefaultContainerConnection();
568    class DefaultContainerConnection implements ServiceConnection {
569        public void onServiceConnected(ComponentName name, IBinder service) {
570            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
571            IMediaContainerService imcs =
572                IMediaContainerService.Stub.asInterface(service);
573            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
574        }
575
576        public void onServiceDisconnected(ComponentName name) {
577            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
578        }
579    };
580
581    // Recordkeeping of restore-after-install operations that are currently in flight
582    // between the Package Manager and the Backup Manager
583    class PostInstallData {
584        public InstallArgs args;
585        public PackageInstalledInfo res;
586
587        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
588            args = _a;
589            res = _r;
590        }
591    };
592    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
593    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
594
595    private final String mRequiredVerifierPackage;
596
597    private final PackageUsage mPackageUsage = new PackageUsage();
598
599    private class PackageUsage {
600        private static final int WRITE_INTERVAL
601            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
602
603        private final Object mFileLock = new Object();
604        private final AtomicLong mLastWritten = new AtomicLong(0);
605        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
606
607        private boolean mIsFirstBoot = false;
608
609        boolean isFirstBoot() {
610            return mIsFirstBoot;
611        }
612
613        void write(boolean force) {
614            if (force) {
615                writeInternal();
616                return;
617            }
618            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
619                && !DEBUG_DEXOPT) {
620                return;
621            }
622            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
623                new Thread("PackageUsage_DiskWriter") {
624                    @Override
625                    public void run() {
626                        try {
627                            writeInternal();
628                        } finally {
629                            mBackgroundWriteRunning.set(false);
630                        }
631                    }
632                }.start();
633            }
634        }
635
636        private void writeInternal() {
637            synchronized (mPackages) {
638                synchronized (mFileLock) {
639                    AtomicFile file = getFile();
640                    FileOutputStream f = null;
641                    try {
642                        f = file.startWrite();
643                        BufferedOutputStream out = new BufferedOutputStream(f);
644                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
645                        StringBuilder sb = new StringBuilder();
646                        for (PackageParser.Package pkg : mPackages.values()) {
647                            if (pkg.mLastPackageUsageTimeInMills == 0) {
648                                continue;
649                            }
650                            sb.setLength(0);
651                            sb.append(pkg.packageName);
652                            sb.append(' ');
653                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
654                            sb.append('\n');
655                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
656                        }
657                        out.flush();
658                        file.finishWrite(f);
659                    } catch (IOException e) {
660                        if (f != null) {
661                            file.failWrite(f);
662                        }
663                        Log.e(TAG, "Failed to write package usage times", e);
664                    }
665                }
666            }
667            mLastWritten.set(SystemClock.elapsedRealtime());
668        }
669
670        void readLP() {
671            synchronized (mFileLock) {
672                AtomicFile file = getFile();
673                BufferedInputStream in = null;
674                try {
675                    in = new BufferedInputStream(file.openRead());
676                    StringBuffer sb = new StringBuffer();
677                    while (true) {
678                        String packageName = readToken(in, sb, ' ');
679                        if (packageName == null) {
680                            break;
681                        }
682                        String timeInMillisString = readToken(in, sb, '\n');
683                        if (timeInMillisString == null) {
684                            throw new IOException("Failed to find last usage time for package "
685                                                  + packageName);
686                        }
687                        PackageParser.Package pkg = mPackages.get(packageName);
688                        if (pkg == null) {
689                            continue;
690                        }
691                        long timeInMillis;
692                        try {
693                            timeInMillis = Long.parseLong(timeInMillisString.toString());
694                        } catch (NumberFormatException e) {
695                            throw new IOException("Failed to parse " + timeInMillisString
696                                                  + " as a long.", e);
697                        }
698                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
699                    }
700                } catch (FileNotFoundException expected) {
701                    mIsFirstBoot = true;
702                } catch (IOException e) {
703                    Log.w(TAG, "Failed to read package usage times", e);
704                } finally {
705                    IoUtils.closeQuietly(in);
706                }
707            }
708            mLastWritten.set(SystemClock.elapsedRealtime());
709        }
710
711        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
712                throws IOException {
713            sb.setLength(0);
714            while (true) {
715                int ch = in.read();
716                if (ch == -1) {
717                    if (sb.length() == 0) {
718                        return null;
719                    }
720                    throw new IOException("Unexpected EOF");
721                }
722                if (ch == endOfToken) {
723                    return sb.toString();
724                }
725                sb.append((char)ch);
726            }
727        }
728
729        private AtomicFile getFile() {
730            File dataDir = Environment.getDataDirectory();
731            File systemDir = new File(dataDir, "system");
732            File fname = new File(systemDir, "package-usage.list");
733            return new AtomicFile(fname);
734        }
735    }
736
737    class PackageHandler extends Handler {
738        private boolean mBound = false;
739        final ArrayList<HandlerParams> mPendingInstalls =
740            new ArrayList<HandlerParams>();
741
742        private boolean connectToService() {
743            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
744                    " DefaultContainerService");
745            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
746            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
747            if (mContext.bindServiceAsUser(service, mDefContainerConn,
748                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
749                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
750                mBound = true;
751                return true;
752            }
753            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754            return false;
755        }
756
757        private void disconnectService() {
758            mContainerService = null;
759            mBound = false;
760            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
761            mContext.unbindService(mDefContainerConn);
762            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
763        }
764
765        PackageHandler(Looper looper) {
766            super(looper);
767        }
768
769        public void handleMessage(Message msg) {
770            try {
771                doHandleMessage(msg);
772            } finally {
773                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
774            }
775        }
776
777        void doHandleMessage(Message msg) {
778            switch (msg.what) {
779                case INIT_COPY: {
780                    HandlerParams params = (HandlerParams) msg.obj;
781                    int idx = mPendingInstalls.size();
782                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
783                    // If a bind was already initiated we dont really
784                    // need to do anything. The pending install
785                    // will be processed later on.
786                    if (!mBound) {
787                        // If this is the only one pending we might
788                        // have to bind to the service again.
789                        if (!connectToService()) {
790                            Slog.e(TAG, "Failed to bind to media container service");
791                            params.serviceError();
792                            return;
793                        } else {
794                            // Once we bind to the service, the first
795                            // pending request will be processed.
796                            mPendingInstalls.add(idx, params);
797                        }
798                    } else {
799                        mPendingInstalls.add(idx, params);
800                        // Already bound to the service. Just make
801                        // sure we trigger off processing the first request.
802                        if (idx == 0) {
803                            mHandler.sendEmptyMessage(MCS_BOUND);
804                        }
805                    }
806                    break;
807                }
808                case MCS_BOUND: {
809                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
810                    if (msg.obj != null) {
811                        mContainerService = (IMediaContainerService) msg.obj;
812                    }
813                    if (mContainerService == null) {
814                        // Something seriously wrong. Bail out
815                        Slog.e(TAG, "Cannot bind to media container service");
816                        for (HandlerParams params : mPendingInstalls) {
817                            // Indicate service bind error
818                            params.serviceError();
819                        }
820                        mPendingInstalls.clear();
821                    } else if (mPendingInstalls.size() > 0) {
822                        HandlerParams params = mPendingInstalls.get(0);
823                        if (params != null) {
824                            if (params.startCopy()) {
825                                // We are done...  look for more work or to
826                                // go idle.
827                                if (DEBUG_SD_INSTALL) Log.i(TAG,
828                                        "Checking for more work or unbind...");
829                                // Delete pending install
830                                if (mPendingInstalls.size() > 0) {
831                                    mPendingInstalls.remove(0);
832                                }
833                                if (mPendingInstalls.size() == 0) {
834                                    if (mBound) {
835                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                                "Posting delayed MCS_UNBIND");
837                                        removeMessages(MCS_UNBIND);
838                                        Message ubmsg = obtainMessage(MCS_UNBIND);
839                                        // Unbind after a little delay, to avoid
840                                        // continual thrashing.
841                                        sendMessageDelayed(ubmsg, 10000);
842                                    }
843                                } else {
844                                    // There are more pending requests in queue.
845                                    // Just post MCS_BOUND message to trigger processing
846                                    // of next pending install.
847                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
848                                            "Posting MCS_BOUND for next woek");
849                                    mHandler.sendEmptyMessage(MCS_BOUND);
850                                }
851                            }
852                        }
853                    } else {
854                        // Should never happen ideally.
855                        Slog.w(TAG, "Empty queue");
856                    }
857                    break;
858                }
859                case MCS_RECONNECT: {
860                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
861                    if (mPendingInstalls.size() > 0) {
862                        if (mBound) {
863                            disconnectService();
864                        }
865                        if (!connectToService()) {
866                            Slog.e(TAG, "Failed to bind to media container service");
867                            for (HandlerParams params : mPendingInstalls) {
868                                // Indicate service bind error
869                                params.serviceError();
870                            }
871                            mPendingInstalls.clear();
872                        }
873                    }
874                    break;
875                }
876                case MCS_UNBIND: {
877                    // If there is no actual work left, then time to unbind.
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
879
880                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
881                        if (mBound) {
882                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
883
884                            disconnectService();
885                        }
886                    } else if (mPendingInstalls.size() > 0) {
887                        // There are more pending requests in queue.
888                        // Just post MCS_BOUND message to trigger processing
889                        // of next pending install.
890                        mHandler.sendEmptyMessage(MCS_BOUND);
891                    }
892
893                    break;
894                }
895                case MCS_GIVE_UP: {
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
897                    mPendingInstalls.remove(0);
898                    break;
899                }
900                case SEND_PENDING_BROADCAST: {
901                    String packages[];
902                    ArrayList<String> components[];
903                    int size = 0;
904                    int uids[];
905                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
906                    synchronized (mPackages) {
907                        if (mPendingBroadcasts == null) {
908                            return;
909                        }
910                        size = mPendingBroadcasts.size();
911                        if (size <= 0) {
912                            // Nothing to be done. Just return
913                            return;
914                        }
915                        packages = new String[size];
916                        components = new ArrayList[size];
917                        uids = new int[size];
918                        int i = 0;  // filling out the above arrays
919
920                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
921                            int packageUserId = mPendingBroadcasts.userIdAt(n);
922                            Iterator<Map.Entry<String, ArrayList<String>>> it
923                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
924                                            .entrySet().iterator();
925                            while (it.hasNext() && i < size) {
926                                Map.Entry<String, ArrayList<String>> ent = it.next();
927                                packages[i] = ent.getKey();
928                                components[i] = ent.getValue();
929                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
930                                uids[i] = (ps != null)
931                                        ? UserHandle.getUid(packageUserId, ps.appId)
932                                        : -1;
933                                i++;
934                            }
935                        }
936                        size = i;
937                        mPendingBroadcasts.clear();
938                    }
939                    // Send broadcasts
940                    for (int i = 0; i < size; i++) {
941                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
942                    }
943                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
944                    break;
945                }
946                case START_CLEANING_PACKAGE: {
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
948                    final String packageName = (String)msg.obj;
949                    final int userId = msg.arg1;
950                    final boolean andCode = msg.arg2 != 0;
951                    synchronized (mPackages) {
952                        if (userId == UserHandle.USER_ALL) {
953                            int[] users = sUserManager.getUserIds();
954                            for (int user : users) {
955                                mSettings.addPackageToCleanLPw(
956                                        new PackageCleanItem(user, packageName, andCode));
957                            }
958                        } else {
959                            mSettings.addPackageToCleanLPw(
960                                    new PackageCleanItem(userId, packageName, andCode));
961                        }
962                    }
963                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
964                    startCleaningPackages();
965                } break;
966                case POST_INSTALL: {
967                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
968                    PostInstallData data = mRunningInstalls.get(msg.arg1);
969                    mRunningInstalls.delete(msg.arg1);
970                    boolean deleteOld = false;
971
972                    if (data != null) {
973                        InstallArgs args = data.args;
974                        PackageInstalledInfo res = data.res;
975
976                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
977                            res.removedInfo.sendBroadcast(false, true, false);
978                            Bundle extras = new Bundle(1);
979                            extras.putInt(Intent.EXTRA_UID, res.uid);
980                            // Determine the set of users who are adding this
981                            // package for the first time vs. those who are seeing
982                            // an update.
983                            int[] firstUsers;
984                            int[] updateUsers = new int[0];
985                            if (res.origUsers == null || res.origUsers.length == 0) {
986                                firstUsers = res.newUsers;
987                            } else {
988                                firstUsers = new int[0];
989                                for (int i=0; i<res.newUsers.length; i++) {
990                                    int user = res.newUsers[i];
991                                    boolean isNew = true;
992                                    for (int j=0; j<res.origUsers.length; j++) {
993                                        if (res.origUsers[j] == user) {
994                                            isNew = false;
995                                            break;
996                                        }
997                                    }
998                                    if (isNew) {
999                                        int[] newFirst = new int[firstUsers.length+1];
1000                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1001                                                firstUsers.length);
1002                                        newFirst[firstUsers.length] = user;
1003                                        firstUsers = newFirst;
1004                                    } else {
1005                                        int[] newUpdate = new int[updateUsers.length+1];
1006                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1007                                                updateUsers.length);
1008                                        newUpdate[updateUsers.length] = user;
1009                                        updateUsers = newUpdate;
1010                                    }
1011                                }
1012                            }
1013                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1014                                    res.pkg.applicationInfo.packageName,
1015                                    extras, null, null, firstUsers);
1016                            final boolean update = res.removedInfo.removedPackage != null;
1017                            if (update) {
1018                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1019                            }
1020                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1021                                    res.pkg.applicationInfo.packageName,
1022                                    extras, null, null, updateUsers);
1023                            if (update) {
1024                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1025                                        res.pkg.applicationInfo.packageName,
1026                                        extras, null, null, updateUsers);
1027                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1028                                        null, null,
1029                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1030
1031                                // treat asec-hosted packages like removable media on upgrade
1032                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1033                                    if (DEBUG_INSTALL) {
1034                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1035                                                + " is ASEC-hosted -> AVAILABLE");
1036                                    }
1037                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1038                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1039                                    pkgList.add(res.pkg.applicationInfo.packageName);
1040                                    sendResourcesChangedBroadcast(true, true,
1041                                            pkgList,uidArray, null);
1042                                }
1043                            }
1044                            if (res.removedInfo.args != null) {
1045                                // Remove the replaced package's older resources safely now
1046                                deleteOld = true;
1047                            }
1048
1049                            // Log current value of "unknown sources" setting
1050                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1051                                getUnknownSourcesSettings());
1052                        }
1053                        // Force a gc to clear up things
1054                        Runtime.getRuntime().gc();
1055                        // We delete after a gc for applications  on sdcard.
1056                        if (deleteOld) {
1057                            synchronized (mInstallLock) {
1058                                res.removedInfo.args.doPostDeleteLI(true);
1059                            }
1060                        }
1061                        if (args.observer != null) {
1062                            try {
1063                                args.observer.packageInstalled(res.name, res.returnCode);
1064                            } catch (RemoteException e) {
1065                                Slog.i(TAG, "Observer no longer exists.");
1066                            }
1067                        }
1068                    } else {
1069                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1070                    }
1071                } break;
1072                case UPDATED_MEDIA_STATUS: {
1073                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1074                    boolean reportStatus = msg.arg1 == 1;
1075                    boolean doGc = msg.arg2 == 1;
1076                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1077                    if (doGc) {
1078                        // Force a gc to clear up stale containers.
1079                        Runtime.getRuntime().gc();
1080                    }
1081                    if (msg.obj != null) {
1082                        @SuppressWarnings("unchecked")
1083                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1084                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1085                        // Unload containers
1086                        unloadAllContainers(args);
1087                    }
1088                    if (reportStatus) {
1089                        try {
1090                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1091                            PackageHelper.getMountService().finishMediaUpdate();
1092                        } catch (RemoteException e) {
1093                            Log.e(TAG, "MountService not running?");
1094                        }
1095                    }
1096                } break;
1097                case WRITE_SETTINGS: {
1098                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1099                    synchronized (mPackages) {
1100                        removeMessages(WRITE_SETTINGS);
1101                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1102                        mSettings.writeLPr();
1103                        mDirtyUsers.clear();
1104                    }
1105                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1106                } break;
1107                case WRITE_PACKAGE_RESTRICTIONS: {
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109                    synchronized (mPackages) {
1110                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1111                        for (int userId : mDirtyUsers) {
1112                            mSettings.writePackageRestrictionsLPr(userId);
1113                        }
1114                        mDirtyUsers.clear();
1115                    }
1116                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117                } break;
1118                case CHECK_PENDING_VERIFICATION: {
1119                    final int verificationId = msg.arg1;
1120                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1121
1122                    if ((state != null) && !state.timeoutExtended()) {
1123                        final InstallArgs args = state.getInstallArgs();
1124                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1125                        mPendingVerification.remove(verificationId);
1126
1127                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1128
1129                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1130                            Slog.i(TAG, "Continuing with installation of "
1131                                    + args.packageURI.toString());
1132                            state.setVerifierResponse(Binder.getCallingUid(),
1133                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1134                            broadcastPackageVerified(verificationId, args.packageURI,
1135                                    PackageManager.VERIFICATION_ALLOW,
1136                                    state.getInstallArgs().getUser());
1137                            try {
1138                                ret = args.copyApk(mContainerService, true);
1139                            } catch (RemoteException e) {
1140                                Slog.e(TAG, "Could not contact the ContainerService");
1141                            }
1142                        } else {
1143                            broadcastPackageVerified(verificationId, args.packageURI,
1144                                    PackageManager.VERIFICATION_REJECT,
1145                                    state.getInstallArgs().getUser());
1146                        }
1147
1148                        processPendingInstall(args, ret);
1149                        mHandler.sendEmptyMessage(MCS_UNBIND);
1150                    }
1151                    break;
1152                }
1153                case PACKAGE_VERIFIED: {
1154                    final int verificationId = msg.arg1;
1155
1156                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1157                    if (state == null) {
1158                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1159                        break;
1160                    }
1161
1162                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1163
1164                    state.setVerifierResponse(response.callerUid, response.code);
1165
1166                    if (state.isVerificationComplete()) {
1167                        mPendingVerification.remove(verificationId);
1168
1169                        final InstallArgs args = state.getInstallArgs();
1170
1171                        int ret;
1172                        if (state.isInstallAllowed()) {
1173                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1174                            broadcastPackageVerified(verificationId, args.packageURI,
1175                                    response.code, state.getInstallArgs().getUser());
1176                            try {
1177                                ret = args.copyApk(mContainerService, true);
1178                            } catch (RemoteException e) {
1179                                Slog.e(TAG, "Could not contact the ContainerService");
1180                            }
1181                        } else {
1182                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1183                        }
1184
1185                        processPendingInstall(args, ret);
1186
1187                        mHandler.sendEmptyMessage(MCS_UNBIND);
1188                    }
1189
1190                    break;
1191                }
1192            }
1193        }
1194    }
1195
1196    void scheduleWriteSettingsLocked() {
1197        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1198            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1199        }
1200    }
1201
1202    void scheduleWritePackageRestrictionsLocked(int userId) {
1203        if (!sUserManager.exists(userId)) return;
1204        mDirtyUsers.add(userId);
1205        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1206            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1207        }
1208    }
1209
1210    public static final IPackageManager main(Context context, Installer installer,
1211            boolean factoryTest, boolean onlyCore) {
1212        PackageManagerService m = new PackageManagerService(context, installer,
1213                factoryTest, onlyCore);
1214        ServiceManager.addService("package", m);
1215        return m;
1216    }
1217
1218    static String[] splitString(String str, char sep) {
1219        int count = 1;
1220        int i = 0;
1221        while ((i=str.indexOf(sep, i)) >= 0) {
1222            count++;
1223            i++;
1224        }
1225
1226        String[] res = new String[count];
1227        i=0;
1228        count = 0;
1229        int lastI=0;
1230        while ((i=str.indexOf(sep, i)) >= 0) {
1231            res[count] = str.substring(lastI, i);
1232            count++;
1233            i++;
1234            lastI = i;
1235        }
1236        res[count] = str.substring(lastI, str.length());
1237        return res;
1238    }
1239
1240    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1241        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1242                Context.DISPLAY_SERVICE);
1243        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1244    }
1245
1246    public PackageManagerService(Context context, Installer installer,
1247            boolean factoryTest, boolean onlyCore) {
1248        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1249                SystemClock.uptimeMillis());
1250
1251        if (mSdkVersion <= 0) {
1252            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1253        }
1254
1255        mContext = context;
1256        mFactoryTest = factoryTest;
1257        mOnlyCore = onlyCore;
1258        mMetrics = new DisplayMetrics();
1259        mSettings = new Settings(context);
1260        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1261                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1262        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1263                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1264        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1265                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1266        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1267                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1268        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1269                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1270        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1271                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1272
1273        String separateProcesses = SystemProperties.get("debug.separate_processes");
1274        if (separateProcesses != null && separateProcesses.length() > 0) {
1275            if ("*".equals(separateProcesses)) {
1276                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1277                mSeparateProcesses = null;
1278                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1279            } else {
1280                mDefParseFlags = 0;
1281                mSeparateProcesses = separateProcesses.split(",");
1282                Slog.w(TAG, "Running with debug.separate_processes: "
1283                        + separateProcesses);
1284            }
1285        } else {
1286            mDefParseFlags = 0;
1287            mSeparateProcesses = null;
1288        }
1289
1290        mInstaller = installer;
1291
1292        getDefaultDisplayMetrics(context, mMetrics);
1293
1294        synchronized (mInstallLock) {
1295        // writer
1296        synchronized (mPackages) {
1297            mHandlerThread = new ServiceThread(TAG,
1298                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1299            mHandlerThread.start();
1300            mHandler = new PackageHandler(mHandlerThread.getLooper());
1301            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1302
1303            File dataDir = Environment.getDataDirectory();
1304            mAppDataDir = new File(dataDir, "data");
1305            mAppInstallDir = new File(dataDir, "app");
1306            mAppLibInstallDir = new File(dataDir, "app-lib");
1307            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1308            mUserAppDataDir = new File(dataDir, "user");
1309            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1310
1311            sUserManager = new UserManagerService(context, this,
1312                    mInstallLock, mPackages);
1313
1314            readPermissions();
1315
1316            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1317
1318            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1319                    mSdkVersion, mOnlyCore);
1320
1321            String customResolverActivity = Resources.getSystem().getString(
1322                    R.string.config_customResolverActivity);
1323            if (TextUtils.isEmpty(customResolverActivity)) {
1324                customResolverActivity = null;
1325            } else {
1326                mCustomResolverComponentName = ComponentName.unflattenFromString(
1327                        customResolverActivity);
1328            }
1329
1330            long startTime = SystemClock.uptimeMillis();
1331
1332            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1333                    startTime);
1334
1335            // Set flag to monitor and not change apk file paths when
1336            // scanning install directories.
1337            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1338
1339            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1340
1341            /**
1342             * Add everything in the in the boot class path to the
1343             * list of process files because dexopt will have been run
1344             * if necessary during zygote startup.
1345             */
1346            String bootClassPath = System.getProperty("java.boot.class.path");
1347            if (bootClassPath != null) {
1348                String[] paths = splitString(bootClassPath, ':');
1349                for (int i=0; i<paths.length; i++) {
1350                    alreadyDexOpted.add(paths[i]);
1351                }
1352            } else {
1353                Slog.w(TAG, "No BOOTCLASSPATH found!");
1354            }
1355
1356            boolean didDexOptLibraryOrTool = false;
1357
1358            final List<String> instructionSets = getAllInstructionSets();
1359
1360            /**
1361             * Ensure all external libraries have had dexopt run on them.
1362             */
1363            if (mSharedLibraries.size() > 0) {
1364                // NOTE: For now, we're compiling these system "shared libraries"
1365                // (and framework jars) into all available architectures. It's possible
1366                // to compile them only when we come across an app that uses them (there's
1367                // already logic for that in scanPackageLI) but that adds some complexity.
1368                for (String instructionSet : instructionSets) {
1369                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1370                        final String lib = libEntry.path;
1371                        if (lib == null) {
1372                            continue;
1373                        }
1374
1375                        try {
1376                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1377                                alreadyDexOpted.add(lib);
1378
1379                                // The list of "shared libraries" we have at this point is
1380                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1381                                didDexOptLibraryOrTool = true;
1382                            }
1383                        } catch (FileNotFoundException e) {
1384                            Slog.w(TAG, "Library not found: " + lib);
1385                        } catch (IOException e) {
1386                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1387                                    + e.getMessage());
1388                        }
1389                    }
1390                }
1391            }
1392
1393            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1394
1395            // Gross hack for now: we know this file doesn't contain any
1396            // code, so don't dexopt it to avoid the resulting log spew.
1397            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1398
1399            // Gross hack for now: we know this file is only part of
1400            // the boot class path for art, so don't dexopt it to
1401            // avoid the resulting log spew.
1402            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1403
1404            /**
1405             * And there are a number of commands implemented in Java, which
1406             * we currently need to do the dexopt on so that they can be
1407             * run from a non-root shell.
1408             */
1409            String[] frameworkFiles = frameworkDir.list();
1410            if (frameworkFiles != null) {
1411                // TODO: We could compile these only for the most preferred ABI. We should
1412                // first double check that the dex files for these commands are not referenced
1413                // by other system apps.
1414                for (String instructionSet : instructionSets) {
1415                    for (int i=0; i<frameworkFiles.length; i++) {
1416                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1417                        String path = libPath.getPath();
1418                        // Skip the file if we already did it.
1419                        if (alreadyDexOpted.contains(path)) {
1420                            continue;
1421                        }
1422                        // Skip the file if it is not a type we want to dexopt.
1423                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1424                            continue;
1425                        }
1426                        try {
1427                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1428                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1429                                didDexOptLibraryOrTool = true;
1430                            }
1431                        } catch (FileNotFoundException e) {
1432                            Slog.w(TAG, "Jar not found: " + path);
1433                        } catch (IOException e) {
1434                            Slog.w(TAG, "Exception reading jar: " + path, e);
1435                        }
1436                    }
1437                }
1438            }
1439
1440            if (didDexOptLibraryOrTool) {
1441                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1442            }
1443
1444            // Collect vendor overlay packages.
1445            // (Do this before scanning any apps.)
1446            // For security and version matching reason, only consider
1447            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1448            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1449            mVendorOverlayInstallObserver = new AppDirObserver(
1450                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1451            mVendorOverlayInstallObserver.startWatching();
1452            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1453                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1454
1455            // Find base frameworks (resource packages without code).
1456            mFrameworkInstallObserver = new AppDirObserver(
1457                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1458            mFrameworkInstallObserver.startWatching();
1459            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1460                    | PackageParser.PARSE_IS_SYSTEM_DIR
1461                    | PackageParser.PARSE_IS_PRIVILEGED,
1462                    scanMode | SCAN_NO_DEX, 0);
1463
1464            // Collected privileged system packages.
1465            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1466            mPrivilegedInstallObserver = new AppDirObserver(
1467                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1468            mPrivilegedInstallObserver.startWatching();
1469                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1470                        | PackageParser.PARSE_IS_SYSTEM_DIR
1471                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1472
1473            // Collect ordinary system packages.
1474            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1475            mSystemInstallObserver = new AppDirObserver(
1476                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1477            mSystemInstallObserver.startWatching();
1478            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1479                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1480
1481            // Collect all vendor packages.
1482            File vendorAppDir = new File("/vendor/app");
1483            try {
1484                vendorAppDir = vendorAppDir.getCanonicalFile();
1485            } catch (IOException e) {
1486                // failed to look up canonical path, continue with original one
1487            }
1488            mVendorInstallObserver = new AppDirObserver(
1489                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1490            mVendorInstallObserver.startWatching();
1491            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1492                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1493
1494            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1495            mInstaller.moveFiles();
1496
1497            // Prune any system packages that no longer exist.
1498            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1499            if (!mOnlyCore) {
1500                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1501                while (psit.hasNext()) {
1502                    PackageSetting ps = psit.next();
1503
1504                    /*
1505                     * If this is not a system app, it can't be a
1506                     * disable system app.
1507                     */
1508                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1509                        continue;
1510                    }
1511
1512                    /*
1513                     * If the package is scanned, it's not erased.
1514                     */
1515                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1516                    if (scannedPkg != null) {
1517                        /*
1518                         * If the system app is both scanned and in the
1519                         * disabled packages list, then it must have been
1520                         * added via OTA. Remove it from the currently
1521                         * scanned package so the previously user-installed
1522                         * application can be scanned.
1523                         */
1524                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1525                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1526                                    + "; removing system app");
1527                            removePackageLI(ps, true);
1528                        }
1529
1530                        continue;
1531                    }
1532
1533                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1534                        psit.remove();
1535                        String msg = "System package " + ps.name
1536                                + " no longer exists; wiping its data";
1537                        reportSettingsProblem(Log.WARN, msg);
1538                        removeDataDirsLI(ps.name);
1539                    } else {
1540                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1541                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1542                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1543                        }
1544                    }
1545                }
1546            }
1547
1548            //look for any incomplete package installations
1549            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1550            //clean up list
1551            for(int i = 0; i < deletePkgsList.size(); i++) {
1552                //clean up here
1553                cleanupInstallFailedPackage(deletePkgsList.get(i));
1554            }
1555            //delete tmp files
1556            deleteTempPackageFiles();
1557
1558            // Remove any shared userIDs that have no associated packages
1559            mSettings.pruneSharedUsersLPw();
1560
1561            if (!mOnlyCore) {
1562                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1563                        SystemClock.uptimeMillis());
1564                mAppInstallObserver = new AppDirObserver(
1565                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1566                mAppInstallObserver.startWatching();
1567                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1568
1569                mDrmAppInstallObserver = new AppDirObserver(
1570                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1571                mDrmAppInstallObserver.startWatching();
1572                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1573                        scanMode, 0);
1574
1575                /**
1576                 * Remove disable package settings for any updated system
1577                 * apps that were removed via an OTA. If they're not a
1578                 * previously-updated app, remove them completely.
1579                 * Otherwise, just revoke their system-level permissions.
1580                 */
1581                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1582                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1583                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1584
1585                    String msg;
1586                    if (deletedPkg == null) {
1587                        msg = "Updated system package " + deletedAppName
1588                                + " no longer exists; wiping its data";
1589                        removeDataDirsLI(deletedAppName);
1590                    } else {
1591                        msg = "Updated system app + " + deletedAppName
1592                                + " no longer present; removing system privileges for "
1593                                + deletedAppName;
1594
1595                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1596
1597                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1598                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1599                    }
1600                    reportSettingsProblem(Log.WARN, msg);
1601                }
1602            } else {
1603                mAppInstallObserver = null;
1604                mDrmAppInstallObserver = null;
1605            }
1606
1607            // Now that we know all of the shared libraries, update all clients to have
1608            // the correct library paths.
1609            updateAllSharedLibrariesLPw();
1610
1611            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1612                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1613                        false /* force dexopt */, false /* defer dexopt */);
1614            }
1615
1616            // Now that we know all the packages we are keeping,
1617            // read and update their last usage times.
1618            mPackageUsage.readLP();
1619
1620            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1621                    SystemClock.uptimeMillis());
1622            Slog.i(TAG, "Time to scan packages: "
1623                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1624                    + " seconds");
1625
1626            // If the platform SDK has changed since the last time we booted,
1627            // we need to re-grant app permission to catch any new ones that
1628            // appear.  This is really a hack, and means that apps can in some
1629            // cases get permissions that the user didn't initially explicitly
1630            // allow...  it would be nice to have some better way to handle
1631            // this situation.
1632            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1633                    != mSdkVersion;
1634            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1635                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1636                    + "; regranting permissions for internal storage");
1637            mSettings.mInternalSdkPlatform = mSdkVersion;
1638
1639            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1640                    | (regrantPermissions
1641                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1642                            : 0));
1643
1644            // If this is the first boot, and it is a normal boot, then
1645            // we need to initialize the default preferred apps.
1646            if (!mRestoredSettings && !onlyCore) {
1647                mSettings.readDefaultPreferredAppsLPw(this, 0);
1648            }
1649
1650            // can downgrade to reader
1651            mSettings.writeLPr();
1652
1653            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1654                    SystemClock.uptimeMillis());
1655
1656            // Now after opening every single application zip, make sure they
1657            // are all flushed.  Not really needed, but keeps things nice and
1658            // tidy.
1659            Runtime.getRuntime().gc();
1660
1661            mRequiredVerifierPackage = getRequiredVerifierLPr();
1662        } // synchronized (mPackages)
1663        } // synchronized (mInstallLock)
1664    }
1665
1666    private static void pruneDexFiles(File cacheDir) {
1667        // If we had to do a dexopt of one of the previous
1668        // things, then something on the system has changed.
1669        // Consider this significant, and wipe away all other
1670        // existing dexopt files to ensure we don't leave any
1671        // dangling around.
1672        //
1673        // Additionally, delete all dex files from the root directory
1674        // since there shouldn't be any there anyway.
1675        //
1676        // Note: This isn't as good an indicator as it used to be. It
1677        // used to include the boot classpath but at some point
1678        // DexFile.isDexOptNeeded started returning false for the boot
1679        // class path files in all cases. It is very possible in a
1680        // small maintenance release update that the library and tool
1681        // jars may be unchanged but APK could be removed resulting in
1682        // unused dalvik-cache files.
1683        File[] files = cacheDir.listFiles();
1684        if (files != null) {
1685            for (File file : files) {
1686                if (!file.isDirectory()) {
1687                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1688                    file.delete();
1689                } else {
1690                    File[] subDirList = file.listFiles();
1691                    if (subDirList != null) {
1692                        for (File subDirFile : subDirList) {
1693                            final String fn = subDirFile.getName();
1694                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1695                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1696                                subDirFile.delete();
1697                            }
1698                        }
1699                    }
1700                }
1701            }
1702        }
1703    }
1704
1705    @Override
1706    public boolean isFirstBoot() {
1707        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1708    }
1709
1710    @Override
1711    public boolean isOnlyCoreApps() {
1712        return mOnlyCore;
1713    }
1714
1715    private String getRequiredVerifierLPr() {
1716        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1717        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1718                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1719
1720        String requiredVerifier = null;
1721
1722        final int N = receivers.size();
1723        for (int i = 0; i < N; i++) {
1724            final ResolveInfo info = receivers.get(i);
1725
1726            if (info.activityInfo == null) {
1727                continue;
1728            }
1729
1730            final String packageName = info.activityInfo.packageName;
1731
1732            final PackageSetting ps = mSettings.mPackages.get(packageName);
1733            if (ps == null) {
1734                continue;
1735            }
1736
1737            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1738            if (!gp.grantedPermissions
1739                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1740                continue;
1741            }
1742
1743            if (requiredVerifier != null) {
1744                throw new RuntimeException("There can be only one required verifier");
1745            }
1746
1747            requiredVerifier = packageName;
1748        }
1749
1750        return requiredVerifier;
1751    }
1752
1753    @Override
1754    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1755            throws RemoteException {
1756        try {
1757            return super.onTransact(code, data, reply, flags);
1758        } catch (RuntimeException e) {
1759            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1760                Slog.wtf(TAG, "Package Manager Crash", e);
1761            }
1762            throw e;
1763        }
1764    }
1765
1766    void cleanupInstallFailedPackage(PackageSetting ps) {
1767        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1768        removeDataDirsLI(ps.name);
1769        if (ps.codePath != null) {
1770            if (!ps.codePath.delete()) {
1771                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1772            }
1773        }
1774        if (ps.resourcePath != null) {
1775            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1776                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1777            }
1778        }
1779        mSettings.removePackageLPw(ps.name);
1780    }
1781
1782    void readPermissions() {
1783        // Read permissions from .../etc/permission directory.
1784        File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1785        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1786            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1787            return;
1788        }
1789        if (!libraryDir.canRead()) {
1790            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1791            return;
1792        }
1793
1794        // Iterate over the files in the directory and scan .xml files
1795        for (File f : libraryDir.listFiles()) {
1796            // We'll read platform.xml last
1797            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1798                continue;
1799            }
1800
1801            if (!f.getPath().endsWith(".xml")) {
1802                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1803                continue;
1804            }
1805            if (!f.canRead()) {
1806                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1807                continue;
1808            }
1809
1810            readPermissionsFromXml(f);
1811        }
1812
1813        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1814        final File permFile = new File(Environment.getRootDirectory(),
1815                "etc/permissions/platform.xml");
1816        readPermissionsFromXml(permFile);
1817    }
1818
1819    private void readPermissionsFromXml(File permFile) {
1820        FileReader permReader = null;
1821        try {
1822            permReader = new FileReader(permFile);
1823        } catch (FileNotFoundException e) {
1824            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1825            return;
1826        }
1827
1828        try {
1829            XmlPullParser parser = Xml.newPullParser();
1830            parser.setInput(permReader);
1831
1832            XmlUtils.beginDocument(parser, "permissions");
1833
1834            while (true) {
1835                XmlUtils.nextElement(parser);
1836                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1837                    break;
1838                }
1839
1840                String name = parser.getName();
1841                if ("group".equals(name)) {
1842                    String gidStr = parser.getAttributeValue(null, "gid");
1843                    if (gidStr != null) {
1844                        int gid = Process.getGidForName(gidStr);
1845                        mGlobalGids = appendInt(mGlobalGids, gid);
1846                    } else {
1847                        Slog.w(TAG, "<group> without gid at "
1848                                + parser.getPositionDescription());
1849                    }
1850
1851                    XmlUtils.skipCurrentTag(parser);
1852                    continue;
1853                } else if ("permission".equals(name)) {
1854                    String perm = parser.getAttributeValue(null, "name");
1855                    if (perm == null) {
1856                        Slog.w(TAG, "<permission> without name at "
1857                                + parser.getPositionDescription());
1858                        XmlUtils.skipCurrentTag(parser);
1859                        continue;
1860                    }
1861                    perm = perm.intern();
1862                    readPermission(parser, perm);
1863
1864                } else if ("assign-permission".equals(name)) {
1865                    String perm = parser.getAttributeValue(null, "name");
1866                    if (perm == null) {
1867                        Slog.w(TAG, "<assign-permission> without name at "
1868                                + parser.getPositionDescription());
1869                        XmlUtils.skipCurrentTag(parser);
1870                        continue;
1871                    }
1872                    String uidStr = parser.getAttributeValue(null, "uid");
1873                    if (uidStr == null) {
1874                        Slog.w(TAG, "<assign-permission> without uid at "
1875                                + parser.getPositionDescription());
1876                        XmlUtils.skipCurrentTag(parser);
1877                        continue;
1878                    }
1879                    int uid = Process.getUidForName(uidStr);
1880                    if (uid < 0) {
1881                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1882                                + uidStr + "\" at "
1883                                + parser.getPositionDescription());
1884                        XmlUtils.skipCurrentTag(parser);
1885                        continue;
1886                    }
1887                    perm = perm.intern();
1888                    HashSet<String> perms = mSystemPermissions.get(uid);
1889                    if (perms == null) {
1890                        perms = new HashSet<String>();
1891                        mSystemPermissions.put(uid, perms);
1892                    }
1893                    perms.add(perm);
1894                    XmlUtils.skipCurrentTag(parser);
1895
1896                } else if ("library".equals(name)) {
1897                    String lname = parser.getAttributeValue(null, "name");
1898                    String lfile = parser.getAttributeValue(null, "file");
1899                    if (lname == null) {
1900                        Slog.w(TAG, "<library> without name at "
1901                                + parser.getPositionDescription());
1902                    } else if (lfile == null) {
1903                        Slog.w(TAG, "<library> without file at "
1904                                + parser.getPositionDescription());
1905                    } else {
1906                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1907                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1908                    }
1909                    XmlUtils.skipCurrentTag(parser);
1910                    continue;
1911
1912                } else if ("feature".equals(name)) {
1913                    String fname = parser.getAttributeValue(null, "name");
1914                    if (fname == null) {
1915                        Slog.w(TAG, "<feature> without name at "
1916                                + parser.getPositionDescription());
1917                    } else {
1918                        //Log.i(TAG, "Got feature " + fname);
1919                        FeatureInfo fi = new FeatureInfo();
1920                        fi.name = fname;
1921                        mAvailableFeatures.put(fname, fi);
1922                    }
1923                    XmlUtils.skipCurrentTag(parser);
1924                    continue;
1925
1926                } else {
1927                    XmlUtils.skipCurrentTag(parser);
1928                    continue;
1929                }
1930
1931            }
1932            permReader.close();
1933        } catch (XmlPullParserException e) {
1934            Slog.w(TAG, "Got execption parsing permissions.", e);
1935        } catch (IOException e) {
1936            Slog.w(TAG, "Got execption parsing permissions.", e);
1937        }
1938    }
1939
1940    void readPermission(XmlPullParser parser, String name)
1941            throws IOException, XmlPullParserException {
1942
1943        name = name.intern();
1944
1945        BasePermission bp = mSettings.mPermissions.get(name);
1946        if (bp == null) {
1947            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1948            mSettings.mPermissions.put(name, bp);
1949        }
1950        int outerDepth = parser.getDepth();
1951        int type;
1952        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1953               && (type != XmlPullParser.END_TAG
1954                       || parser.getDepth() > outerDepth)) {
1955            if (type == XmlPullParser.END_TAG
1956                    || type == XmlPullParser.TEXT) {
1957                continue;
1958            }
1959
1960            String tagName = parser.getName();
1961            if ("group".equals(tagName)) {
1962                String gidStr = parser.getAttributeValue(null, "gid");
1963                if (gidStr != null) {
1964                    int gid = Process.getGidForName(gidStr);
1965                    bp.gids = appendInt(bp.gids, gid);
1966                } else {
1967                    Slog.w(TAG, "<group> without gid at "
1968                            + parser.getPositionDescription());
1969                }
1970            }
1971            XmlUtils.skipCurrentTag(parser);
1972        }
1973    }
1974
1975    static int[] appendInts(int[] cur, int[] add) {
1976        if (add == null) return cur;
1977        if (cur == null) return add;
1978        final int N = add.length;
1979        for (int i=0; i<N; i++) {
1980            cur = appendInt(cur, add[i]);
1981        }
1982        return cur;
1983    }
1984
1985    static int[] removeInts(int[] cur, int[] rem) {
1986        if (rem == null) return cur;
1987        if (cur == null) return cur;
1988        final int N = rem.length;
1989        for (int i=0; i<N; i++) {
1990            cur = removeInt(cur, rem[i]);
1991        }
1992        return cur;
1993    }
1994
1995    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1996        if (!sUserManager.exists(userId)) return null;
1997        final PackageSetting ps = (PackageSetting) p.mExtras;
1998        if (ps == null) {
1999            return null;
2000        }
2001        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2002        final PackageUserState state = ps.readUserState(userId);
2003        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2004                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2005                state, userId);
2006    }
2007
2008    @Override
2009    public boolean isPackageAvailable(String packageName, int userId) {
2010        if (!sUserManager.exists(userId)) return false;
2011        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2012        synchronized (mPackages) {
2013            PackageParser.Package p = mPackages.get(packageName);
2014            if (p != null) {
2015                final PackageSetting ps = (PackageSetting) p.mExtras;
2016                if (ps != null) {
2017                    final PackageUserState state = ps.readUserState(userId);
2018                    if (state != null) {
2019                        return PackageParser.isAvailable(state);
2020                    }
2021                }
2022            }
2023        }
2024        return false;
2025    }
2026
2027    @Override
2028    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2029        if (!sUserManager.exists(userId)) return null;
2030        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2031        // reader
2032        synchronized (mPackages) {
2033            PackageParser.Package p = mPackages.get(packageName);
2034            if (DEBUG_PACKAGE_INFO)
2035                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2036            if (p != null) {
2037                return generatePackageInfo(p, flags, userId);
2038            }
2039            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2040                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2041            }
2042        }
2043        return null;
2044    }
2045
2046    @Override
2047    public String[] currentToCanonicalPackageNames(String[] names) {
2048        String[] out = new String[names.length];
2049        // reader
2050        synchronized (mPackages) {
2051            for (int i=names.length-1; i>=0; i--) {
2052                PackageSetting ps = mSettings.mPackages.get(names[i]);
2053                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2054            }
2055        }
2056        return out;
2057    }
2058
2059    @Override
2060    public String[] canonicalToCurrentPackageNames(String[] names) {
2061        String[] out = new String[names.length];
2062        // reader
2063        synchronized (mPackages) {
2064            for (int i=names.length-1; i>=0; i--) {
2065                String cur = mSettings.mRenamedPackages.get(names[i]);
2066                out[i] = cur != null ? cur : names[i];
2067            }
2068        }
2069        return out;
2070    }
2071
2072    @Override
2073    public int getPackageUid(String packageName, int userId) {
2074        if (!sUserManager.exists(userId)) return -1;
2075        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2076        // reader
2077        synchronized (mPackages) {
2078            PackageParser.Package p = mPackages.get(packageName);
2079            if(p != null) {
2080                return UserHandle.getUid(userId, p.applicationInfo.uid);
2081            }
2082            PackageSetting ps = mSettings.mPackages.get(packageName);
2083            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2084                return -1;
2085            }
2086            p = ps.pkg;
2087            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2088        }
2089    }
2090
2091    @Override
2092    public int[] getPackageGids(String packageName) {
2093        // reader
2094        synchronized (mPackages) {
2095            PackageParser.Package p = mPackages.get(packageName);
2096            if (DEBUG_PACKAGE_INFO)
2097                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2098            if (p != null) {
2099                final PackageSetting ps = (PackageSetting)p.mExtras;
2100                return ps.getGids();
2101            }
2102        }
2103        // stupid thing to indicate an error.
2104        return new int[0];
2105    }
2106
2107    static final PermissionInfo generatePermissionInfo(
2108            BasePermission bp, int flags) {
2109        if (bp.perm != null) {
2110            return PackageParser.generatePermissionInfo(bp.perm, flags);
2111        }
2112        PermissionInfo pi = new PermissionInfo();
2113        pi.name = bp.name;
2114        pi.packageName = bp.sourcePackage;
2115        pi.nonLocalizedLabel = bp.name;
2116        pi.protectionLevel = bp.protectionLevel;
2117        return pi;
2118    }
2119
2120    @Override
2121    public PermissionInfo getPermissionInfo(String name, int flags) {
2122        // reader
2123        synchronized (mPackages) {
2124            final BasePermission p = mSettings.mPermissions.get(name);
2125            if (p != null) {
2126                return generatePermissionInfo(p, flags);
2127            }
2128            return null;
2129        }
2130    }
2131
2132    @Override
2133    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2134        // reader
2135        synchronized (mPackages) {
2136            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2137            for (BasePermission p : mSettings.mPermissions.values()) {
2138                if (group == null) {
2139                    if (p.perm == null || p.perm.info.group == null) {
2140                        out.add(generatePermissionInfo(p, flags));
2141                    }
2142                } else {
2143                    if (p.perm != null && group.equals(p.perm.info.group)) {
2144                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2145                    }
2146                }
2147            }
2148
2149            if (out.size() > 0) {
2150                return out;
2151            }
2152            return mPermissionGroups.containsKey(group) ? out : null;
2153        }
2154    }
2155
2156    @Override
2157    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2158        // reader
2159        synchronized (mPackages) {
2160            return PackageParser.generatePermissionGroupInfo(
2161                    mPermissionGroups.get(name), flags);
2162        }
2163    }
2164
2165    @Override
2166    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2167        // reader
2168        synchronized (mPackages) {
2169            final int N = mPermissionGroups.size();
2170            ArrayList<PermissionGroupInfo> out
2171                    = new ArrayList<PermissionGroupInfo>(N);
2172            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2173                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2174            }
2175            return out;
2176        }
2177    }
2178
2179    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2180            int userId) {
2181        if (!sUserManager.exists(userId)) return null;
2182        PackageSetting ps = mSettings.mPackages.get(packageName);
2183        if (ps != null) {
2184            if (ps.pkg == null) {
2185                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2186                        flags, userId);
2187                if (pInfo != null) {
2188                    return pInfo.applicationInfo;
2189                }
2190                return null;
2191            }
2192            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2193                    ps.readUserState(userId), userId);
2194        }
2195        return null;
2196    }
2197
2198    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2199            int userId) {
2200        if (!sUserManager.exists(userId)) return null;
2201        PackageSetting ps = mSettings.mPackages.get(packageName);
2202        if (ps != null) {
2203            PackageParser.Package pkg = ps.pkg;
2204            if (pkg == null) {
2205                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2206                    return null;
2207                }
2208                pkg = new PackageParser.Package(packageName);
2209                pkg.applicationInfo.packageName = packageName;
2210                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2211                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2212                pkg.applicationInfo.sourceDir = ps.codePathString;
2213                pkg.applicationInfo.dataDir =
2214                        getDataPathForPackage(packageName, 0).getPath();
2215                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2216                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2217            }
2218            return generatePackageInfo(pkg, flags, userId);
2219        }
2220        return null;
2221    }
2222
2223    @Override
2224    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2225        if (!sUserManager.exists(userId)) return null;
2226        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2227        // writer
2228        synchronized (mPackages) {
2229            PackageParser.Package p = mPackages.get(packageName);
2230            if (DEBUG_PACKAGE_INFO) Log.v(
2231                    TAG, "getApplicationInfo " + packageName
2232                    + ": " + p);
2233            if (p != null) {
2234                PackageSetting ps = mSettings.mPackages.get(packageName);
2235                if (ps == null) return null;
2236                // Note: isEnabledLP() does not apply here - always return info
2237                return PackageParser.generateApplicationInfo(
2238                        p, flags, ps.readUserState(userId), userId);
2239            }
2240            if ("android".equals(packageName)||"system".equals(packageName)) {
2241                return mAndroidApplication;
2242            }
2243            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2244                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2245            }
2246        }
2247        return null;
2248    }
2249
2250
2251    @Override
2252    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2253        mContext.enforceCallingOrSelfPermission(
2254                android.Manifest.permission.CLEAR_APP_CACHE, null);
2255        // Queue up an async operation since clearing cache may take a little while.
2256        mHandler.post(new Runnable() {
2257            public void run() {
2258                mHandler.removeCallbacks(this);
2259                int retCode = -1;
2260                synchronized (mInstallLock) {
2261                    retCode = mInstaller.freeCache(freeStorageSize);
2262                    if (retCode < 0) {
2263                        Slog.w(TAG, "Couldn't clear application caches");
2264                    }
2265                }
2266                if (observer != null) {
2267                    try {
2268                        observer.onRemoveCompleted(null, (retCode >= 0));
2269                    } catch (RemoteException e) {
2270                        Slog.w(TAG, "RemoveException when invoking call back");
2271                    }
2272                }
2273            }
2274        });
2275    }
2276
2277    @Override
2278    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2279        mContext.enforceCallingOrSelfPermission(
2280                android.Manifest.permission.CLEAR_APP_CACHE, null);
2281        // Queue up an async operation since clearing cache may take a little while.
2282        mHandler.post(new Runnable() {
2283            public void run() {
2284                mHandler.removeCallbacks(this);
2285                int retCode = -1;
2286                synchronized (mInstallLock) {
2287                    retCode = mInstaller.freeCache(freeStorageSize);
2288                    if (retCode < 0) {
2289                        Slog.w(TAG, "Couldn't clear application caches");
2290                    }
2291                }
2292                if(pi != null) {
2293                    try {
2294                        // Callback via pending intent
2295                        int code = (retCode >= 0) ? 1 : 0;
2296                        pi.sendIntent(null, code, null,
2297                                null, null);
2298                    } catch (SendIntentException e1) {
2299                        Slog.i(TAG, "Failed to send pending intent");
2300                    }
2301                }
2302            }
2303        });
2304    }
2305
2306    @Override
2307    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2308        if (!sUserManager.exists(userId)) return null;
2309        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2310        synchronized (mPackages) {
2311            PackageParser.Activity a = mActivities.mActivities.get(component);
2312
2313            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2314            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2315                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2316                if (ps == null) return null;
2317                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2318                        userId);
2319            }
2320            if (mResolveComponentName.equals(component)) {
2321                return mResolveActivity;
2322            }
2323        }
2324        return null;
2325    }
2326
2327    @Override
2328    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2329        if (!sUserManager.exists(userId)) return null;
2330        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2331        synchronized (mPackages) {
2332            PackageParser.Activity a = mReceivers.mActivities.get(component);
2333            if (DEBUG_PACKAGE_INFO) Log.v(
2334                TAG, "getReceiverInfo " + component + ": " + a);
2335            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2336                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2337                if (ps == null) return null;
2338                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2339                        userId);
2340            }
2341        }
2342        return null;
2343    }
2344
2345    @Override
2346    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2347        if (!sUserManager.exists(userId)) return null;
2348        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2349        synchronized (mPackages) {
2350            PackageParser.Service s = mServices.mServices.get(component);
2351            if (DEBUG_PACKAGE_INFO) Log.v(
2352                TAG, "getServiceInfo " + component + ": " + s);
2353            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2354                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2355                if (ps == null) return null;
2356                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2357                        userId);
2358            }
2359        }
2360        return null;
2361    }
2362
2363    @Override
2364    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2365        if (!sUserManager.exists(userId)) return null;
2366        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2367        synchronized (mPackages) {
2368            PackageParser.Provider p = mProviders.mProviders.get(component);
2369            if (DEBUG_PACKAGE_INFO) Log.v(
2370                TAG, "getProviderInfo " + component + ": " + p);
2371            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2372                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2373                if (ps == null) return null;
2374                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2375                        userId);
2376            }
2377        }
2378        return null;
2379    }
2380
2381    @Override
2382    public String[] getSystemSharedLibraryNames() {
2383        Set<String> libSet;
2384        synchronized (mPackages) {
2385            libSet = mSharedLibraries.keySet();
2386            int size = libSet.size();
2387            if (size > 0) {
2388                String[] libs = new String[size];
2389                libSet.toArray(libs);
2390                return libs;
2391            }
2392        }
2393        return null;
2394    }
2395
2396    @Override
2397    public FeatureInfo[] getSystemAvailableFeatures() {
2398        Collection<FeatureInfo> featSet;
2399        synchronized (mPackages) {
2400            featSet = mAvailableFeatures.values();
2401            int size = featSet.size();
2402            if (size > 0) {
2403                FeatureInfo[] features = new FeatureInfo[size+1];
2404                featSet.toArray(features);
2405                FeatureInfo fi = new FeatureInfo();
2406                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2407                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2408                features[size] = fi;
2409                return features;
2410            }
2411        }
2412        return null;
2413    }
2414
2415    @Override
2416    public boolean hasSystemFeature(String name) {
2417        synchronized (mPackages) {
2418            return mAvailableFeatures.containsKey(name);
2419        }
2420    }
2421
2422    private void checkValidCaller(int uid, int userId) {
2423        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2424            return;
2425
2426        throw new SecurityException("Caller uid=" + uid
2427                + " is not privileged to communicate with user=" + userId);
2428    }
2429
2430    @Override
2431    public int checkPermission(String permName, String pkgName) {
2432        synchronized (mPackages) {
2433            PackageParser.Package p = mPackages.get(pkgName);
2434            if (p != null && p.mExtras != null) {
2435                PackageSetting ps = (PackageSetting)p.mExtras;
2436                if (ps.sharedUser != null) {
2437                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2438                        return PackageManager.PERMISSION_GRANTED;
2439                    }
2440                } else if (ps.grantedPermissions.contains(permName)) {
2441                    return PackageManager.PERMISSION_GRANTED;
2442                }
2443            }
2444        }
2445        return PackageManager.PERMISSION_DENIED;
2446    }
2447
2448    @Override
2449    public int checkUidPermission(String permName, int uid) {
2450        synchronized (mPackages) {
2451            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2452            if (obj != null) {
2453                GrantedPermissions gp = (GrantedPermissions)obj;
2454                if (gp.grantedPermissions.contains(permName)) {
2455                    return PackageManager.PERMISSION_GRANTED;
2456                }
2457            } else {
2458                HashSet<String> perms = mSystemPermissions.get(uid);
2459                if (perms != null && perms.contains(permName)) {
2460                    return PackageManager.PERMISSION_GRANTED;
2461                }
2462            }
2463        }
2464        return PackageManager.PERMISSION_DENIED;
2465    }
2466
2467    /**
2468     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2469     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2470     * @param message the message to log on security exception
2471     * @return
2472     */
2473    private void enforceCrossUserPermission(int callingUid, int userId,
2474            boolean requireFullPermission, String message) {
2475        if (userId < 0) {
2476            throw new IllegalArgumentException("Invalid userId " + userId);
2477        }
2478        if (userId == UserHandle.getUserId(callingUid)) return;
2479        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2480            if (requireFullPermission) {
2481                mContext.enforceCallingOrSelfPermission(
2482                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2483            } else {
2484                try {
2485                    mContext.enforceCallingOrSelfPermission(
2486                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2487                } catch (SecurityException se) {
2488                    mContext.enforceCallingOrSelfPermission(
2489                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2490                }
2491            }
2492        }
2493    }
2494
2495    private BasePermission findPermissionTreeLP(String permName) {
2496        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2497            if (permName.startsWith(bp.name) &&
2498                    permName.length() > bp.name.length() &&
2499                    permName.charAt(bp.name.length()) == '.') {
2500                return bp;
2501            }
2502        }
2503        return null;
2504    }
2505
2506    private BasePermission checkPermissionTreeLP(String permName) {
2507        if (permName != null) {
2508            BasePermission bp = findPermissionTreeLP(permName);
2509            if (bp != null) {
2510                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2511                    return bp;
2512                }
2513                throw new SecurityException("Calling uid "
2514                        + Binder.getCallingUid()
2515                        + " is not allowed to add to permission tree "
2516                        + bp.name + " owned by uid " + bp.uid);
2517            }
2518        }
2519        throw new SecurityException("No permission tree found for " + permName);
2520    }
2521
2522    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2523        if (s1 == null) {
2524            return s2 == null;
2525        }
2526        if (s2 == null) {
2527            return false;
2528        }
2529        if (s1.getClass() != s2.getClass()) {
2530            return false;
2531        }
2532        return s1.equals(s2);
2533    }
2534
2535    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2536        if (pi1.icon != pi2.icon) return false;
2537        if (pi1.logo != pi2.logo) return false;
2538        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2539        if (!compareStrings(pi1.name, pi2.name)) return false;
2540        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2541        // We'll take care of setting this one.
2542        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2543        // These are not currently stored in settings.
2544        //if (!compareStrings(pi1.group, pi2.group)) return false;
2545        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2546        //if (pi1.labelRes != pi2.labelRes) return false;
2547        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2548        return true;
2549    }
2550
2551    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2552        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2553            throw new SecurityException("Label must be specified in permission");
2554        }
2555        BasePermission tree = checkPermissionTreeLP(info.name);
2556        BasePermission bp = mSettings.mPermissions.get(info.name);
2557        boolean added = bp == null;
2558        boolean changed = true;
2559        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2560        if (added) {
2561            bp = new BasePermission(info.name, tree.sourcePackage,
2562                    BasePermission.TYPE_DYNAMIC);
2563        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2564            throw new SecurityException(
2565                    "Not allowed to modify non-dynamic permission "
2566                    + info.name);
2567        } else {
2568            if (bp.protectionLevel == fixedLevel
2569                    && bp.perm.owner.equals(tree.perm.owner)
2570                    && bp.uid == tree.uid
2571                    && comparePermissionInfos(bp.perm.info, info)) {
2572                changed = false;
2573            }
2574        }
2575        bp.protectionLevel = fixedLevel;
2576        info = new PermissionInfo(info);
2577        info.protectionLevel = fixedLevel;
2578        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2579        bp.perm.info.packageName = tree.perm.info.packageName;
2580        bp.uid = tree.uid;
2581        if (added) {
2582            mSettings.mPermissions.put(info.name, bp);
2583        }
2584        if (changed) {
2585            if (!async) {
2586                mSettings.writeLPr();
2587            } else {
2588                scheduleWriteSettingsLocked();
2589            }
2590        }
2591        return added;
2592    }
2593
2594    @Override
2595    public boolean addPermission(PermissionInfo info) {
2596        synchronized (mPackages) {
2597            return addPermissionLocked(info, false);
2598        }
2599    }
2600
2601    @Override
2602    public boolean addPermissionAsync(PermissionInfo info) {
2603        synchronized (mPackages) {
2604            return addPermissionLocked(info, true);
2605        }
2606    }
2607
2608    @Override
2609    public void removePermission(String name) {
2610        synchronized (mPackages) {
2611            checkPermissionTreeLP(name);
2612            BasePermission bp = mSettings.mPermissions.get(name);
2613            if (bp != null) {
2614                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2615                    throw new SecurityException(
2616                            "Not allowed to modify non-dynamic permission "
2617                            + name);
2618                }
2619                mSettings.mPermissions.remove(name);
2620                mSettings.writeLPr();
2621            }
2622        }
2623    }
2624
2625    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2626        int index = pkg.requestedPermissions.indexOf(bp.name);
2627        if (index == -1) {
2628            throw new SecurityException("Package " + pkg.packageName
2629                    + " has not requested permission " + bp.name);
2630        }
2631        boolean isNormal =
2632                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2633                        == PermissionInfo.PROTECTION_NORMAL);
2634        boolean isDangerous =
2635                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2636                        == PermissionInfo.PROTECTION_DANGEROUS);
2637        boolean isDevelopment =
2638                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2639
2640        if (!isNormal && !isDangerous && !isDevelopment) {
2641            throw new SecurityException("Permission " + bp.name
2642                    + " is not a changeable permission type");
2643        }
2644
2645        if (isNormal || isDangerous) {
2646            if (pkg.requestedPermissionsRequired.get(index)) {
2647                throw new SecurityException("Can't change " + bp.name
2648                        + ". It is required by the application");
2649            }
2650        }
2651    }
2652
2653    @Override
2654    public void grantPermission(String packageName, String permissionName) {
2655        mContext.enforceCallingOrSelfPermission(
2656                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2657        synchronized (mPackages) {
2658            final PackageParser.Package pkg = mPackages.get(packageName);
2659            if (pkg == null) {
2660                throw new IllegalArgumentException("Unknown package: " + packageName);
2661            }
2662            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2663            if (bp == null) {
2664                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2665            }
2666
2667            checkGrantRevokePermissions(pkg, bp);
2668
2669            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2670            if (ps == null) {
2671                return;
2672            }
2673            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2674            if (gp.grantedPermissions.add(permissionName)) {
2675                if (ps.haveGids) {
2676                    gp.gids = appendInts(gp.gids, bp.gids);
2677                }
2678                mSettings.writeLPr();
2679            }
2680        }
2681    }
2682
2683    @Override
2684    public void revokePermission(String packageName, String permissionName) {
2685        int changedAppId = -1;
2686
2687        synchronized (mPackages) {
2688            final PackageParser.Package pkg = mPackages.get(packageName);
2689            if (pkg == null) {
2690                throw new IllegalArgumentException("Unknown package: " + packageName);
2691            }
2692            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2693                mContext.enforceCallingOrSelfPermission(
2694                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2695            }
2696            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2697            if (bp == null) {
2698                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2699            }
2700
2701            checkGrantRevokePermissions(pkg, bp);
2702
2703            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2704            if (ps == null) {
2705                return;
2706            }
2707            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2708            if (gp.grantedPermissions.remove(permissionName)) {
2709                gp.grantedPermissions.remove(permissionName);
2710                if (ps.haveGids) {
2711                    gp.gids = removeInts(gp.gids, bp.gids);
2712                }
2713                mSettings.writeLPr();
2714                changedAppId = ps.appId;
2715            }
2716        }
2717
2718        if (changedAppId >= 0) {
2719            // We changed the perm on someone, kill its processes.
2720            IActivityManager am = ActivityManagerNative.getDefault();
2721            if (am != null) {
2722                final int callingUserId = UserHandle.getCallingUserId();
2723                final long ident = Binder.clearCallingIdentity();
2724                try {
2725                    //XXX we should only revoke for the calling user's app permissions,
2726                    // but for now we impact all users.
2727                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2728                    //        "revoke " + permissionName);
2729                    int[] users = sUserManager.getUserIds();
2730                    for (int user : users) {
2731                        am.killUid(UserHandle.getUid(user, changedAppId),
2732                                "revoke " + permissionName);
2733                    }
2734                } catch (RemoteException e) {
2735                } finally {
2736                    Binder.restoreCallingIdentity(ident);
2737                }
2738            }
2739        }
2740    }
2741
2742    @Override
2743    public boolean isProtectedBroadcast(String actionName) {
2744        synchronized (mPackages) {
2745            return mProtectedBroadcasts.contains(actionName);
2746        }
2747    }
2748
2749    @Override
2750    public int checkSignatures(String pkg1, String pkg2) {
2751        synchronized (mPackages) {
2752            final PackageParser.Package p1 = mPackages.get(pkg1);
2753            final PackageParser.Package p2 = mPackages.get(pkg2);
2754            if (p1 == null || p1.mExtras == null
2755                    || p2 == null || p2.mExtras == null) {
2756                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2757            }
2758            return compareSignatures(p1.mSignatures, p2.mSignatures);
2759        }
2760    }
2761
2762    @Override
2763    public int checkUidSignatures(int uid1, int uid2) {
2764        // Map to base uids.
2765        uid1 = UserHandle.getAppId(uid1);
2766        uid2 = UserHandle.getAppId(uid2);
2767        // reader
2768        synchronized (mPackages) {
2769            Signature[] s1;
2770            Signature[] s2;
2771            Object obj = mSettings.getUserIdLPr(uid1);
2772            if (obj != null) {
2773                if (obj instanceof SharedUserSetting) {
2774                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2775                } else if (obj instanceof PackageSetting) {
2776                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2777                } else {
2778                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2779                }
2780            } else {
2781                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2782            }
2783            obj = mSettings.getUserIdLPr(uid2);
2784            if (obj != null) {
2785                if (obj instanceof SharedUserSetting) {
2786                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2787                } else if (obj instanceof PackageSetting) {
2788                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2789                } else {
2790                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2791                }
2792            } else {
2793                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2794            }
2795            return compareSignatures(s1, s2);
2796        }
2797    }
2798
2799    /**
2800     * Compares two sets of signatures. Returns:
2801     * <br />
2802     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2803     * <br />
2804     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2805     * <br />
2806     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2807     * <br />
2808     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2809     * <br />
2810     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2811     */
2812    static int compareSignatures(Signature[] s1, Signature[] s2) {
2813        if (s1 == null) {
2814            return s2 == null
2815                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2816                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2817        }
2818
2819        if (s2 == null) {
2820            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2821        }
2822
2823        if (s1.length != s2.length) {
2824            return PackageManager.SIGNATURE_NO_MATCH;
2825        }
2826
2827        // Since both signature sets are of size 1, we can compare without HashSets.
2828        if (s1.length == 1) {
2829            return s1[0].equals(s2[0]) ?
2830                    PackageManager.SIGNATURE_MATCH :
2831                    PackageManager.SIGNATURE_NO_MATCH;
2832        }
2833
2834        HashSet<Signature> set1 = new HashSet<Signature>();
2835        for (Signature sig : s1) {
2836            set1.add(sig);
2837        }
2838        HashSet<Signature> set2 = new HashSet<Signature>();
2839        for (Signature sig : s2) {
2840            set2.add(sig);
2841        }
2842        // Make sure s2 contains all signatures in s1.
2843        if (set1.equals(set2)) {
2844            return PackageManager.SIGNATURE_MATCH;
2845        }
2846        return PackageManager.SIGNATURE_NO_MATCH;
2847    }
2848
2849    @Override
2850    public String[] getPackagesForUid(int uid) {
2851        uid = UserHandle.getAppId(uid);
2852        // reader
2853        synchronized (mPackages) {
2854            Object obj = mSettings.getUserIdLPr(uid);
2855            if (obj instanceof SharedUserSetting) {
2856                final SharedUserSetting sus = (SharedUserSetting) obj;
2857                final int N = sus.packages.size();
2858                final String[] res = new String[N];
2859                final Iterator<PackageSetting> it = sus.packages.iterator();
2860                int i = 0;
2861                while (it.hasNext()) {
2862                    res[i++] = it.next().name;
2863                }
2864                return res;
2865            } else if (obj instanceof PackageSetting) {
2866                final PackageSetting ps = (PackageSetting) obj;
2867                return new String[] { ps.name };
2868            }
2869        }
2870        return null;
2871    }
2872
2873    @Override
2874    public String getNameForUid(int uid) {
2875        // reader
2876        synchronized (mPackages) {
2877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2878            if (obj instanceof SharedUserSetting) {
2879                final SharedUserSetting sus = (SharedUserSetting) obj;
2880                return sus.name + ":" + sus.userId;
2881            } else if (obj instanceof PackageSetting) {
2882                final PackageSetting ps = (PackageSetting) obj;
2883                return ps.name;
2884            }
2885        }
2886        return null;
2887    }
2888
2889    @Override
2890    public int getUidForSharedUser(String sharedUserName) {
2891        if(sharedUserName == null) {
2892            return -1;
2893        }
2894        // reader
2895        synchronized (mPackages) {
2896            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2897            if (suid == null) {
2898                return -1;
2899            }
2900            return suid.userId;
2901        }
2902    }
2903
2904    @Override
2905    public int getFlagsForUid(int uid) {
2906        synchronized (mPackages) {
2907            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2908            if (obj instanceof SharedUserSetting) {
2909                final SharedUserSetting sus = (SharedUserSetting) obj;
2910                return sus.pkgFlags;
2911            } else if (obj instanceof PackageSetting) {
2912                final PackageSetting ps = (PackageSetting) obj;
2913                return ps.pkgFlags;
2914            }
2915        }
2916        return 0;
2917    }
2918
2919    @Override
2920    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2921            int flags, int userId) {
2922        if (!sUserManager.exists(userId)) return null;
2923        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2924        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2925        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2926    }
2927
2928    @Override
2929    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2930            IntentFilter filter, int match, ComponentName activity) {
2931        final int userId = UserHandle.getCallingUserId();
2932        if (DEBUG_PREFERRED) {
2933            Log.v(TAG, "setLastChosenActivity intent=" + intent
2934                + " resolvedType=" + resolvedType
2935                + " flags=" + flags
2936                + " filter=" + filter
2937                + " match=" + match
2938                + " activity=" + activity);
2939            filter.dump(new PrintStreamPrinter(System.out), "    ");
2940        }
2941        intent.setComponent(null);
2942        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2943        // Find any earlier preferred or last chosen entries and nuke them
2944        findPreferredActivity(intent, resolvedType,
2945                flags, query, 0, false, true, false, userId);
2946        // Add the new activity as the last chosen for this filter
2947        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2948    }
2949
2950    @Override
2951    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2952        final int userId = UserHandle.getCallingUserId();
2953        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2954        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2955        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2956                false, false, false, userId);
2957    }
2958
2959    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2960            int flags, List<ResolveInfo> query, int userId) {
2961        if (query != null) {
2962            final int N = query.size();
2963            if (N == 1) {
2964                return query.get(0);
2965            } else if (N > 1) {
2966                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2967                // If there is more than one activity with the same priority,
2968                // then let the user decide between them.
2969                ResolveInfo r0 = query.get(0);
2970                ResolveInfo r1 = query.get(1);
2971                if (DEBUG_INTENT_MATCHING || debug) {
2972                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2973                            + r1.activityInfo.name + "=" + r1.priority);
2974                }
2975                // If the first activity has a higher priority, or a different
2976                // default, then it is always desireable to pick it.
2977                if (r0.priority != r1.priority
2978                        || r0.preferredOrder != r1.preferredOrder
2979                        || r0.isDefault != r1.isDefault) {
2980                    return query.get(0);
2981                }
2982                // If we have saved a preference for a preferred activity for
2983                // this Intent, use that.
2984                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2985                        flags, query, r0.priority, true, false, debug, userId);
2986                if (ri != null) {
2987                    return ri;
2988                }
2989                if (userId != 0) {
2990                    ri = new ResolveInfo(mResolveInfo);
2991                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2992                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2993                            ri.activityInfo.applicationInfo);
2994                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2995                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2996                    return ri;
2997                }
2998                return mResolveInfo;
2999            }
3000        }
3001        return null;
3002    }
3003
3004    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3005            List<ResolveInfo> query, int priority, boolean always,
3006            boolean removeMatches, boolean debug, int userId) {
3007        if (!sUserManager.exists(userId)) return null;
3008        // writer
3009        synchronized (mPackages) {
3010            if (intent.getSelector() != null) {
3011                intent = intent.getSelector();
3012            }
3013            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3014            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3015            // Get the list of preferred activities that handle the intent
3016            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3017            List<PreferredActivity> prefs = pir != null
3018                    ? pir.queryIntent(intent, resolvedType,
3019                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3020                    : null;
3021            if (prefs != null && prefs.size() > 0) {
3022                // First figure out how good the original match set is.
3023                // We will only allow preferred activities that came
3024                // from the same match quality.
3025                int match = 0;
3026
3027                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3028
3029                final int N = query.size();
3030                for (int j=0; j<N; j++) {
3031                    final ResolveInfo ri = query.get(j);
3032                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3033                            + ": 0x" + Integer.toHexString(match));
3034                    if (ri.match > match) {
3035                        match = ri.match;
3036                    }
3037                }
3038
3039                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3040                        + Integer.toHexString(match));
3041
3042                match &= IntentFilter.MATCH_CATEGORY_MASK;
3043                final int M = prefs.size();
3044                for (int i=0; i<M; i++) {
3045                    final PreferredActivity pa = prefs.get(i);
3046                    if (DEBUG_PREFERRED || debug) {
3047                        Slog.v(TAG, "Checking PreferredActivity ds="
3048                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3049                                + "\n  component=" + pa.mPref.mComponent);
3050                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3051                    }
3052                    if (pa.mPref.mMatch != match) {
3053                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3054                                + Integer.toHexString(pa.mPref.mMatch));
3055                        continue;
3056                    }
3057                    // If it's not an "always" type preferred activity and that's what we're
3058                    // looking for, skip it.
3059                    if (always && !pa.mPref.mAlways) {
3060                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3061                        continue;
3062                    }
3063                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3064                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3065                    if (DEBUG_PREFERRED || debug) {
3066                        Slog.v(TAG, "Found preferred activity:");
3067                        if (ai != null) {
3068                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3069                        } else {
3070                            Slog.v(TAG, "  null");
3071                        }
3072                    }
3073                    if (ai == null) {
3074                        // This previously registered preferred activity
3075                        // component is no longer known.  Most likely an update
3076                        // to the app was installed and in the new version this
3077                        // component no longer exists.  Clean it up by removing
3078                        // it from the preferred activities list, and skip it.
3079                        Slog.w(TAG, "Removing dangling preferred activity: "
3080                                + pa.mPref.mComponent);
3081                        pir.removeFilter(pa);
3082                        continue;
3083                    }
3084                    for (int j=0; j<N; j++) {
3085                        final ResolveInfo ri = query.get(j);
3086                        if (!ri.activityInfo.applicationInfo.packageName
3087                                .equals(ai.applicationInfo.packageName)) {
3088                            continue;
3089                        }
3090                        if (!ri.activityInfo.name.equals(ai.name)) {
3091                            continue;
3092                        }
3093
3094                        if (removeMatches) {
3095                            pir.removeFilter(pa);
3096                            if (DEBUG_PREFERRED) {
3097                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3098                            }
3099                            break;
3100                        }
3101
3102                        // Okay we found a previously set preferred or last chosen app.
3103                        // If the result set is different from when this
3104                        // was created, we need to clear it and re-ask the
3105                        // user their preference, if we're looking for an "always" type entry.
3106                        if (always && !pa.mPref.sameSet(query, priority)) {
3107                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3108                                    + intent + " type " + resolvedType);
3109                            if (DEBUG_PREFERRED) {
3110                                Slog.v(TAG, "Removing preferred activity since set changed "
3111                                        + pa.mPref.mComponent);
3112                            }
3113                            pir.removeFilter(pa);
3114                            // Re-add the filter as a "last chosen" entry (!always)
3115                            PreferredActivity lastChosen = new PreferredActivity(
3116                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3117                            pir.addFilter(lastChosen);
3118                            mSettings.writePackageRestrictionsLPr(userId);
3119                            return null;
3120                        }
3121
3122                        // Yay! Either the set matched or we're looking for the last chosen
3123                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3124                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3125                        mSettings.writePackageRestrictionsLPr(userId);
3126                        return ri;
3127                    }
3128                }
3129            }
3130            mSettings.writePackageRestrictionsLPr(userId);
3131        }
3132        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3133        return null;
3134    }
3135
3136    @Override
3137    public List<ResolveInfo> queryIntentActivities(Intent intent,
3138            String resolvedType, int flags, int userId) {
3139        if (!sUserManager.exists(userId)) return Collections.emptyList();
3140        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3141        ComponentName comp = intent.getComponent();
3142        if (comp == null) {
3143            if (intent.getSelector() != null) {
3144                intent = intent.getSelector();
3145                comp = intent.getComponent();
3146            }
3147        }
3148
3149        if (comp != null) {
3150            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3151            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3152            if (ai != null) {
3153                final ResolveInfo ri = new ResolveInfo();
3154                ri.activityInfo = ai;
3155                list.add(ri);
3156            }
3157            return list;
3158        }
3159
3160        // reader
3161        synchronized (mPackages) {
3162            final String pkgName = intent.getPackage();
3163            if (pkgName == null) {
3164                return mActivities.queryIntent(intent, resolvedType, flags, userId);
3165            }
3166            final PackageParser.Package pkg = mPackages.get(pkgName);
3167            if (pkg != null) {
3168                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3169                        pkg.activities, userId);
3170            }
3171            return new ArrayList<ResolveInfo>();
3172        }
3173    }
3174
3175    @Override
3176    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3177            Intent[] specifics, String[] specificTypes, Intent intent,
3178            String resolvedType, int flags, int userId) {
3179        if (!sUserManager.exists(userId)) return Collections.emptyList();
3180        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3181                "query intent activity options");
3182        final String resultsAction = intent.getAction();
3183
3184        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3185                | PackageManager.GET_RESOLVED_FILTER, userId);
3186
3187        if (DEBUG_INTENT_MATCHING) {
3188            Log.v(TAG, "Query " + intent + ": " + results);
3189        }
3190
3191        int specificsPos = 0;
3192        int N;
3193
3194        // todo: note that the algorithm used here is O(N^2).  This
3195        // isn't a problem in our current environment, but if we start running
3196        // into situations where we have more than 5 or 10 matches then this
3197        // should probably be changed to something smarter...
3198
3199        // First we go through and resolve each of the specific items
3200        // that were supplied, taking care of removing any corresponding
3201        // duplicate items in the generic resolve list.
3202        if (specifics != null) {
3203            for (int i=0; i<specifics.length; i++) {
3204                final Intent sintent = specifics[i];
3205                if (sintent == null) {
3206                    continue;
3207                }
3208
3209                if (DEBUG_INTENT_MATCHING) {
3210                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3211                }
3212
3213                String action = sintent.getAction();
3214                if (resultsAction != null && resultsAction.equals(action)) {
3215                    // If this action was explicitly requested, then don't
3216                    // remove things that have it.
3217                    action = null;
3218                }
3219
3220                ResolveInfo ri = null;
3221                ActivityInfo ai = null;
3222
3223                ComponentName comp = sintent.getComponent();
3224                if (comp == null) {
3225                    ri = resolveIntent(
3226                        sintent,
3227                        specificTypes != null ? specificTypes[i] : null,
3228                            flags, userId);
3229                    if (ri == null) {
3230                        continue;
3231                    }
3232                    if (ri == mResolveInfo) {
3233                        // ACK!  Must do something better with this.
3234                    }
3235                    ai = ri.activityInfo;
3236                    comp = new ComponentName(ai.applicationInfo.packageName,
3237                            ai.name);
3238                } else {
3239                    ai = getActivityInfo(comp, flags, userId);
3240                    if (ai == null) {
3241                        continue;
3242                    }
3243                }
3244
3245                // Look for any generic query activities that are duplicates
3246                // of this specific one, and remove them from the results.
3247                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3248                N = results.size();
3249                int j;
3250                for (j=specificsPos; j<N; j++) {
3251                    ResolveInfo sri = results.get(j);
3252                    if ((sri.activityInfo.name.equals(comp.getClassName())
3253                            && sri.activityInfo.applicationInfo.packageName.equals(
3254                                    comp.getPackageName()))
3255                        || (action != null && sri.filter.matchAction(action))) {
3256                        results.remove(j);
3257                        if (DEBUG_INTENT_MATCHING) Log.v(
3258                            TAG, "Removing duplicate item from " + j
3259                            + " due to specific " + specificsPos);
3260                        if (ri == null) {
3261                            ri = sri;
3262                        }
3263                        j--;
3264                        N--;
3265                    }
3266                }
3267
3268                // Add this specific item to its proper place.
3269                if (ri == null) {
3270                    ri = new ResolveInfo();
3271                    ri.activityInfo = ai;
3272                }
3273                results.add(specificsPos, ri);
3274                ri.specificIndex = i;
3275                specificsPos++;
3276            }
3277        }
3278
3279        // Now we go through the remaining generic results and remove any
3280        // duplicate actions that are found here.
3281        N = results.size();
3282        for (int i=specificsPos; i<N-1; i++) {
3283            final ResolveInfo rii = results.get(i);
3284            if (rii.filter == null) {
3285                continue;
3286            }
3287
3288            // Iterate over all of the actions of this result's intent
3289            // filter...  typically this should be just one.
3290            final Iterator<String> it = rii.filter.actionsIterator();
3291            if (it == null) {
3292                continue;
3293            }
3294            while (it.hasNext()) {
3295                final String action = it.next();
3296                if (resultsAction != null && resultsAction.equals(action)) {
3297                    // If this action was explicitly requested, then don't
3298                    // remove things that have it.
3299                    continue;
3300                }
3301                for (int j=i+1; j<N; j++) {
3302                    final ResolveInfo rij = results.get(j);
3303                    if (rij.filter != null && rij.filter.hasAction(action)) {
3304                        results.remove(j);
3305                        if (DEBUG_INTENT_MATCHING) Log.v(
3306                            TAG, "Removing duplicate item from " + j
3307                            + " due to action " + action + " at " + i);
3308                        j--;
3309                        N--;
3310                    }
3311                }
3312            }
3313
3314            // If the caller didn't request filter information, drop it now
3315            // so we don't have to marshall/unmarshall it.
3316            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3317                rii.filter = null;
3318            }
3319        }
3320
3321        // Filter out the caller activity if so requested.
3322        if (caller != null) {
3323            N = results.size();
3324            for (int i=0; i<N; i++) {
3325                ActivityInfo ainfo = results.get(i).activityInfo;
3326                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3327                        && caller.getClassName().equals(ainfo.name)) {
3328                    results.remove(i);
3329                    break;
3330                }
3331            }
3332        }
3333
3334        // If the caller didn't request filter information,
3335        // drop them now so we don't have to
3336        // marshall/unmarshall it.
3337        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3338            N = results.size();
3339            for (int i=0; i<N; i++) {
3340                results.get(i).filter = null;
3341            }
3342        }
3343
3344        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3345        return results;
3346    }
3347
3348    @Override
3349    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3350            int userId) {
3351        if (!sUserManager.exists(userId)) return Collections.emptyList();
3352        ComponentName comp = intent.getComponent();
3353        if (comp == null) {
3354            if (intent.getSelector() != null) {
3355                intent = intent.getSelector();
3356                comp = intent.getComponent();
3357            }
3358        }
3359        if (comp != null) {
3360            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3361            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3362            if (ai != null) {
3363                ResolveInfo ri = new ResolveInfo();
3364                ri.activityInfo = ai;
3365                list.add(ri);
3366            }
3367            return list;
3368        }
3369
3370        // reader
3371        synchronized (mPackages) {
3372            String pkgName = intent.getPackage();
3373            if (pkgName == null) {
3374                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3375            }
3376            final PackageParser.Package pkg = mPackages.get(pkgName);
3377            if (pkg != null) {
3378                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3379                        userId);
3380            }
3381            return null;
3382        }
3383    }
3384
3385    @Override
3386    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3387        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3388        if (!sUserManager.exists(userId)) return null;
3389        if (query != null) {
3390            if (query.size() >= 1) {
3391                // If there is more than one service with the same priority,
3392                // just arbitrarily pick the first one.
3393                return query.get(0);
3394            }
3395        }
3396        return null;
3397    }
3398
3399    @Override
3400    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3401            int userId) {
3402        if (!sUserManager.exists(userId)) return Collections.emptyList();
3403        ComponentName comp = intent.getComponent();
3404        if (comp == null) {
3405            if (intent.getSelector() != null) {
3406                intent = intent.getSelector();
3407                comp = intent.getComponent();
3408            }
3409        }
3410        if (comp != null) {
3411            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3412            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3413            if (si != null) {
3414                final ResolveInfo ri = new ResolveInfo();
3415                ri.serviceInfo = si;
3416                list.add(ri);
3417            }
3418            return list;
3419        }
3420
3421        // reader
3422        synchronized (mPackages) {
3423            String pkgName = intent.getPackage();
3424            if (pkgName == null) {
3425                return mServices.queryIntent(intent, resolvedType, flags, userId);
3426            }
3427            final PackageParser.Package pkg = mPackages.get(pkgName);
3428            if (pkg != null) {
3429                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3430                        userId);
3431            }
3432            return null;
3433        }
3434    }
3435
3436    @Override
3437    public List<ResolveInfo> queryIntentContentProviders(
3438            Intent intent, String resolvedType, int flags, int userId) {
3439        if (!sUserManager.exists(userId)) return Collections.emptyList();
3440        ComponentName comp = intent.getComponent();
3441        if (comp == null) {
3442            if (intent.getSelector() != null) {
3443                intent = intent.getSelector();
3444                comp = intent.getComponent();
3445            }
3446        }
3447        if (comp != null) {
3448            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3449            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3450            if (pi != null) {
3451                final ResolveInfo ri = new ResolveInfo();
3452                ri.providerInfo = pi;
3453                list.add(ri);
3454            }
3455            return list;
3456        }
3457
3458        // reader
3459        synchronized (mPackages) {
3460            String pkgName = intent.getPackage();
3461            if (pkgName == null) {
3462                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3463            }
3464            final PackageParser.Package pkg = mPackages.get(pkgName);
3465            if (pkg != null) {
3466                return mProviders.queryIntentForPackage(
3467                        intent, resolvedType, flags, pkg.providers, userId);
3468            }
3469            return null;
3470        }
3471    }
3472
3473    @Override
3474    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3475        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3476
3477        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3478
3479        // writer
3480        synchronized (mPackages) {
3481            ArrayList<PackageInfo> list;
3482            if (listUninstalled) {
3483                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3484                for (PackageSetting ps : mSettings.mPackages.values()) {
3485                    PackageInfo pi;
3486                    if (ps.pkg != null) {
3487                        pi = generatePackageInfo(ps.pkg, flags, userId);
3488                    } else {
3489                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3490                    }
3491                    if (pi != null) {
3492                        list.add(pi);
3493                    }
3494                }
3495            } else {
3496                list = new ArrayList<PackageInfo>(mPackages.size());
3497                for (PackageParser.Package p : mPackages.values()) {
3498                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3499                    if (pi != null) {
3500                        list.add(pi);
3501                    }
3502                }
3503            }
3504
3505            return new ParceledListSlice<PackageInfo>(list);
3506        }
3507    }
3508
3509    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3510            String[] permissions, boolean[] tmp, int flags, int userId) {
3511        int numMatch = 0;
3512        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3513        for (int i=0; i<permissions.length; i++) {
3514            if (gp.grantedPermissions.contains(permissions[i])) {
3515                tmp[i] = true;
3516                numMatch++;
3517            } else {
3518                tmp[i] = false;
3519            }
3520        }
3521        if (numMatch == 0) {
3522            return;
3523        }
3524        PackageInfo pi;
3525        if (ps.pkg != null) {
3526            pi = generatePackageInfo(ps.pkg, flags, userId);
3527        } else {
3528            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3529        }
3530        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3531            if (numMatch == permissions.length) {
3532                pi.requestedPermissions = permissions;
3533            } else {
3534                pi.requestedPermissions = new String[numMatch];
3535                numMatch = 0;
3536                for (int i=0; i<permissions.length; i++) {
3537                    if (tmp[i]) {
3538                        pi.requestedPermissions[numMatch] = permissions[i];
3539                        numMatch++;
3540                    }
3541                }
3542            }
3543        }
3544        list.add(pi);
3545    }
3546
3547    @Override
3548    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3549            String[] permissions, int flags, int userId) {
3550        if (!sUserManager.exists(userId)) return null;
3551        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3552
3553        // writer
3554        synchronized (mPackages) {
3555            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3556            boolean[] tmpBools = new boolean[permissions.length];
3557            if (listUninstalled) {
3558                for (PackageSetting ps : mSettings.mPackages.values()) {
3559                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3560                }
3561            } else {
3562                for (PackageParser.Package pkg : mPackages.values()) {
3563                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3564                    if (ps != null) {
3565                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3566                                userId);
3567                    }
3568                }
3569            }
3570
3571            return new ParceledListSlice<PackageInfo>(list);
3572        }
3573    }
3574
3575    @Override
3576    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3577        if (!sUserManager.exists(userId)) return null;
3578        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3579
3580        // writer
3581        synchronized (mPackages) {
3582            ArrayList<ApplicationInfo> list;
3583            if (listUninstalled) {
3584                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3585                for (PackageSetting ps : mSettings.mPackages.values()) {
3586                    ApplicationInfo ai;
3587                    if (ps.pkg != null) {
3588                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3589                                ps.readUserState(userId), userId);
3590                    } else {
3591                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3592                    }
3593                    if (ai != null) {
3594                        list.add(ai);
3595                    }
3596                }
3597            } else {
3598                list = new ArrayList<ApplicationInfo>(mPackages.size());
3599                for (PackageParser.Package p : mPackages.values()) {
3600                    if (p.mExtras != null) {
3601                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3602                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3603                        if (ai != null) {
3604                            list.add(ai);
3605                        }
3606                    }
3607                }
3608            }
3609
3610            return new ParceledListSlice<ApplicationInfo>(list);
3611        }
3612    }
3613
3614    public List<ApplicationInfo> getPersistentApplications(int flags) {
3615        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3616
3617        // reader
3618        synchronized (mPackages) {
3619            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3620            final int userId = UserHandle.getCallingUserId();
3621            while (i.hasNext()) {
3622                final PackageParser.Package p = i.next();
3623                if (p.applicationInfo != null
3624                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3625                        && (!mSafeMode || isSystemApp(p))) {
3626                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3627                    if (ps != null) {
3628                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3629                                ps.readUserState(userId), userId);
3630                        if (ai != null) {
3631                            finalList.add(ai);
3632                        }
3633                    }
3634                }
3635            }
3636        }
3637
3638        return finalList;
3639    }
3640
3641    @Override
3642    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3643        if (!sUserManager.exists(userId)) return null;
3644        // reader
3645        synchronized (mPackages) {
3646            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3647            PackageSetting ps = provider != null
3648                    ? mSettings.mPackages.get(provider.owner.packageName)
3649                    : null;
3650            return ps != null
3651                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3652                    && (!mSafeMode || (provider.info.applicationInfo.flags
3653                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3654                    ? PackageParser.generateProviderInfo(provider, flags,
3655                            ps.readUserState(userId), userId)
3656                    : null;
3657        }
3658    }
3659
3660    /**
3661     * @deprecated
3662     */
3663    @Deprecated
3664    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3665        // reader
3666        synchronized (mPackages) {
3667            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3668                    .entrySet().iterator();
3669            final int userId = UserHandle.getCallingUserId();
3670            while (i.hasNext()) {
3671                Map.Entry<String, PackageParser.Provider> entry = i.next();
3672                PackageParser.Provider p = entry.getValue();
3673                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3674
3675                if (ps != null && p.syncable
3676                        && (!mSafeMode || (p.info.applicationInfo.flags
3677                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3678                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3679                            ps.readUserState(userId), userId);
3680                    if (info != null) {
3681                        outNames.add(entry.getKey());
3682                        outInfo.add(info);
3683                    }
3684                }
3685            }
3686        }
3687    }
3688
3689    @Override
3690    public List<ProviderInfo> queryContentProviders(String processName,
3691            int uid, int flags) {
3692        ArrayList<ProviderInfo> finalList = null;
3693        // reader
3694        synchronized (mPackages) {
3695            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3696            final int userId = processName != null ?
3697                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3698            while (i.hasNext()) {
3699                final PackageParser.Provider p = i.next();
3700                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3701                if (ps != null && p.info.authority != null
3702                        && (processName == null
3703                                || (p.info.processName.equals(processName)
3704                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3705                        && mSettings.isEnabledLPr(p.info, flags, userId)
3706                        && (!mSafeMode
3707                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3708                    if (finalList == null) {
3709                        finalList = new ArrayList<ProviderInfo>(3);
3710                    }
3711                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3712                            ps.readUserState(userId), userId);
3713                    if (info != null) {
3714                        finalList.add(info);
3715                    }
3716                }
3717            }
3718        }
3719
3720        if (finalList != null) {
3721            Collections.sort(finalList, mProviderInitOrderSorter);
3722        }
3723
3724        return finalList;
3725    }
3726
3727    @Override
3728    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3729            int flags) {
3730        // reader
3731        synchronized (mPackages) {
3732            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3733            return PackageParser.generateInstrumentationInfo(i, flags);
3734        }
3735    }
3736
3737    @Override
3738    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3739            int flags) {
3740        ArrayList<InstrumentationInfo> finalList =
3741            new ArrayList<InstrumentationInfo>();
3742
3743        // reader
3744        synchronized (mPackages) {
3745            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3746            while (i.hasNext()) {
3747                final PackageParser.Instrumentation p = i.next();
3748                if (targetPackage == null
3749                        || targetPackage.equals(p.info.targetPackage)) {
3750                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3751                            flags);
3752                    if (ii != null) {
3753                        finalList.add(ii);
3754                    }
3755                }
3756            }
3757        }
3758
3759        return finalList;
3760    }
3761
3762    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3763        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3764        if (overlays == null) {
3765            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3766            return;
3767        }
3768        for (PackageParser.Package opkg : overlays.values()) {
3769            // Not much to do if idmap fails: we already logged the error
3770            // and we certainly don't want to abort installation of pkg simply
3771            // because an overlay didn't fit properly. For these reasons,
3772            // ignore the return value of createIdmapForPackagePairLI.
3773            createIdmapForPackagePairLI(pkg, opkg);
3774        }
3775    }
3776
3777    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3778            PackageParser.Package opkg) {
3779        if (!opkg.mTrustedOverlay) {
3780            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3781                    opkg.mScanPath + ": overlay not trusted");
3782            return false;
3783        }
3784        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3785        if (overlaySet == null) {
3786            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3787                    opkg.mScanPath + " but target package has no known overlays");
3788            return false;
3789        }
3790        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3791        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3792            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3793            return false;
3794        }
3795        PackageParser.Package[] overlayArray =
3796            overlaySet.values().toArray(new PackageParser.Package[0]);
3797        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3798            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3799                return p1.mOverlayPriority - p2.mOverlayPriority;
3800            }
3801        };
3802        Arrays.sort(overlayArray, cmp);
3803
3804        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3805        int i = 0;
3806        for (PackageParser.Package p : overlayArray) {
3807            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3808        }
3809        return true;
3810    }
3811
3812    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3813        String[] files = dir.list();
3814        if (files == null) {
3815            Log.d(TAG, "No files in app dir " + dir);
3816            return;
3817        }
3818
3819        if (DEBUG_PACKAGE_SCANNING) {
3820            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3821                    + " flags=0x" + Integer.toHexString(flags));
3822        }
3823
3824        int i;
3825        for (i=0; i<files.length; i++) {
3826            File file = new File(dir, files[i]);
3827            if (!isPackageFilename(files[i])) {
3828                // Ignore entries which are not apk's
3829                continue;
3830            }
3831            PackageParser.Package pkg = scanPackageLI(file,
3832                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3833            // Don't mess around with apps in system partition.
3834            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3835                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3836                // Delete the apk
3837                Slog.w(TAG, "Cleaning up failed install of " + file);
3838                file.delete();
3839            }
3840        }
3841    }
3842
3843    private static File getSettingsProblemFile() {
3844        File dataDir = Environment.getDataDirectory();
3845        File systemDir = new File(dataDir, "system");
3846        File fname = new File(systemDir, "uiderrors.txt");
3847        return fname;
3848    }
3849
3850    static void reportSettingsProblem(int priority, String msg) {
3851        try {
3852            File fname = getSettingsProblemFile();
3853            FileOutputStream out = new FileOutputStream(fname, true);
3854            PrintWriter pw = new FastPrintWriter(out);
3855            SimpleDateFormat formatter = new SimpleDateFormat();
3856            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3857            pw.println(dateString + ": " + msg);
3858            pw.close();
3859            FileUtils.setPermissions(
3860                    fname.toString(),
3861                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3862                    -1, -1);
3863        } catch (java.io.IOException e) {
3864        }
3865        Slog.println(priority, TAG, msg);
3866    }
3867
3868    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3869            PackageParser.Package pkg, File srcFile, int parseFlags) {
3870        if (GET_CERTIFICATES) {
3871            if (ps != null
3872                    && ps.codePath.equals(srcFile)
3873                    && ps.timeStamp == srcFile.lastModified()) {
3874                if (ps.signatures.mSignatures != null
3875                        && ps.signatures.mSignatures.length != 0) {
3876                    // Optimization: reuse the existing cached certificates
3877                    // if the package appears to be unchanged.
3878                    pkg.mSignatures = ps.signatures.mSignatures;
3879                    return true;
3880                }
3881
3882                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3883            } else {
3884                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3885            }
3886
3887            if (!pp.collectCertificates(pkg, parseFlags)) {
3888                mLastScanError = pp.getParseError();
3889                return false;
3890            }
3891        }
3892        return true;
3893    }
3894
3895    /*
3896     *  Scan a package and return the newly parsed package.
3897     *  Returns null in case of errors and the error code is stored in mLastScanError
3898     */
3899    private PackageParser.Package scanPackageLI(File scanFile,
3900            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3901        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3902        String scanPath = scanFile.getPath();
3903        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3904        parseFlags |= mDefParseFlags;
3905        PackageParser pp = new PackageParser(scanPath);
3906        pp.setSeparateProcesses(mSeparateProcesses);
3907        pp.setOnlyCoreApps(mOnlyCore);
3908        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3909                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3910
3911        if (pkg == null) {
3912            mLastScanError = pp.getParseError();
3913            return null;
3914        }
3915
3916        PackageSetting ps = null;
3917        PackageSetting updatedPkg;
3918        // reader
3919        synchronized (mPackages) {
3920            // Look to see if we already know about this package.
3921            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3922            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3923                // This package has been renamed to its original name.  Let's
3924                // use that.
3925                ps = mSettings.peekPackageLPr(oldName);
3926            }
3927            // If there was no original package, see one for the real package name.
3928            if (ps == null) {
3929                ps = mSettings.peekPackageLPr(pkg.packageName);
3930            }
3931            // Check to see if this package could be hiding/updating a system
3932            // package.  Must look for it either under the original or real
3933            // package name depending on our state.
3934            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3935            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3936        }
3937        boolean updatedPkgBetter = false;
3938        // First check if this is a system package that may involve an update
3939        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3940            if (ps != null && !ps.codePath.equals(scanFile)) {
3941                // The path has changed from what was last scanned...  check the
3942                // version of the new path against what we have stored to determine
3943                // what to do.
3944                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3945                if (pkg.mVersionCode < ps.versionCode) {
3946                    // The system package has been updated and the code path does not match
3947                    // Ignore entry. Skip it.
3948                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3949                            + " ignored: updated version " + ps.versionCode
3950                            + " better than this " + pkg.mVersionCode);
3951                    if (!updatedPkg.codePath.equals(scanFile)) {
3952                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3953                                + ps.name + " changing from " + updatedPkg.codePathString
3954                                + " to " + scanFile);
3955                        updatedPkg.codePath = scanFile;
3956                        updatedPkg.codePathString = scanFile.toString();
3957                        // This is the point at which we know that the system-disk APK
3958                        // for this package has moved during a reboot (e.g. due to an OTA),
3959                        // so we need to reevaluate it for privilege policy.
3960                        if (locationIsPrivileged(scanFile)) {
3961                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3962                        }
3963                    }
3964                    updatedPkg.pkg = pkg;
3965                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3966                    return null;
3967                } else {
3968                    // The current app on the system partion is better than
3969                    // what we have updated to on the data partition; switch
3970                    // back to the system partition version.
3971                    // At this point, its safely assumed that package installation for
3972                    // apps in system partition will go through. If not there won't be a working
3973                    // version of the app
3974                    // writer
3975                    synchronized (mPackages) {
3976                        // Just remove the loaded entries from package lists.
3977                        mPackages.remove(ps.name);
3978                    }
3979                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3980                            + "reverting from " + ps.codePathString
3981                            + ": new version " + pkg.mVersionCode
3982                            + " better than installed " + ps.versionCode);
3983
3984                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3985                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
3986                            getAppInstructionSetFromSettings(ps));
3987                    synchronized (mInstallLock) {
3988                        args.cleanUpResourcesLI();
3989                    }
3990                    synchronized (mPackages) {
3991                        mSettings.enableSystemPackageLPw(ps.name);
3992                    }
3993                    updatedPkgBetter = true;
3994                }
3995            }
3996        }
3997
3998        if (updatedPkg != null) {
3999            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4000            // initially
4001            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4002
4003            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4004            // flag set initially
4005            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4006                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4007            }
4008        }
4009        // Verify certificates against what was last scanned
4010        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4011            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4012            return null;
4013        }
4014
4015        /*
4016         * A new system app appeared, but we already had a non-system one of the
4017         * same name installed earlier.
4018         */
4019        boolean shouldHideSystemApp = false;
4020        if (updatedPkg == null && ps != null
4021                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4022            /*
4023             * Check to make sure the signatures match first. If they don't,
4024             * wipe the installed application and its data.
4025             */
4026            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4027                    != PackageManager.SIGNATURE_MATCH) {
4028                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4029                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4030                ps = null;
4031            } else {
4032                /*
4033                 * If the newly-added system app is an older version than the
4034                 * already installed version, hide it. It will be scanned later
4035                 * and re-added like an update.
4036                 */
4037                if (pkg.mVersionCode < ps.versionCode) {
4038                    shouldHideSystemApp = true;
4039                } else {
4040                    /*
4041                     * The newly found system app is a newer version that the
4042                     * one previously installed. Simply remove the
4043                     * already-installed application and replace it with our own
4044                     * while keeping the application data.
4045                     */
4046                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4047                            + ps.codePathString + ": new version " + pkg.mVersionCode
4048                            + " better than installed " + ps.versionCode);
4049                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4050                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4051                            getAppInstructionSetFromSettings(ps));
4052                    synchronized (mInstallLock) {
4053                        args.cleanUpResourcesLI();
4054                    }
4055                }
4056            }
4057        }
4058
4059        // The apk is forward locked (not public) if its code and resources
4060        // are kept in different files. (except for app in either system or
4061        // vendor path).
4062        // TODO grab this value from PackageSettings
4063        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4064            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4065                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4066            }
4067        }
4068
4069        String codePath = null;
4070        String resPath = null;
4071        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4072            if (ps != null && ps.resourcePathString != null) {
4073                resPath = ps.resourcePathString;
4074            } else {
4075                // Should not happen at all. Just log an error.
4076                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4077            }
4078        } else {
4079            resPath = pkg.mScanPath;
4080        }
4081
4082        codePath = pkg.mScanPath;
4083        // Set application objects path explicitly.
4084        setApplicationInfoPaths(pkg, codePath, resPath);
4085        // Note that we invoke the following method only if we are about to unpack an application
4086        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4087                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4088
4089        /*
4090         * If the system app should be overridden by a previously installed
4091         * data, hide the system app now and let the /data/app scan pick it up
4092         * again.
4093         */
4094        if (shouldHideSystemApp) {
4095            synchronized (mPackages) {
4096                /*
4097                 * We have to grant systems permissions before we hide, because
4098                 * grantPermissions will assume the package update is trying to
4099                 * expand its permissions.
4100                 */
4101                grantPermissionsLPw(pkg, true);
4102                mSettings.disableSystemPackageLPw(pkg.packageName);
4103            }
4104        }
4105
4106        return scannedPkg;
4107    }
4108
4109    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4110            String destResPath) {
4111        pkg.mPath = pkg.mScanPath = destCodePath;
4112        pkg.applicationInfo.sourceDir = destCodePath;
4113        pkg.applicationInfo.publicSourceDir = destResPath;
4114    }
4115
4116    private static String fixProcessName(String defProcessName,
4117            String processName, int uid) {
4118        if (processName == null) {
4119            return defProcessName;
4120        }
4121        return processName;
4122    }
4123
4124    private boolean verifySignaturesLP(PackageSetting pkgSetting,
4125            PackageParser.Package pkg) {
4126        if (pkgSetting.signatures.mSignatures != null) {
4127            // Already existing package. Make sure signatures match
4128            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
4129                PackageManager.SIGNATURE_MATCH) {
4130                    Slog.e(TAG, "Package " + pkg.packageName
4131                            + " signatures do not match the previously installed version; ignoring!");
4132                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4133                    return false;
4134                }
4135        }
4136        // Check for shared user signatures
4137        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4138            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4139                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4140                Slog.e(TAG, "Package " + pkg.packageName
4141                        + " has no signatures that match those in shared user "
4142                        + pkgSetting.sharedUser.name + "; ignoring!");
4143                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4144                return false;
4145            }
4146        }
4147        return true;
4148    }
4149
4150    /**
4151     * Enforces that only the system UID or root's UID can call a method exposed
4152     * via Binder.
4153     *
4154     * @param message used as message if SecurityException is thrown
4155     * @throws SecurityException if the caller is not system or root
4156     */
4157    private static final void enforceSystemOrRoot(String message) {
4158        final int uid = Binder.getCallingUid();
4159        if (uid != Process.SYSTEM_UID && uid != 0) {
4160            throw new SecurityException(message);
4161        }
4162    }
4163
4164    @Override
4165    public void performBootDexOpt() {
4166        enforceSystemOrRoot("Only the system can request dexopt be performed");
4167
4168        final HashSet<PackageParser.Package> pkgs;
4169        synchronized (mPackages) {
4170            pkgs = mDeferredDexOpt;
4171            mDeferredDexOpt = null;
4172        }
4173
4174        if (pkgs != null) {
4175            // Filter out packages that aren't recently used.
4176            //
4177            // The exception is first boot of a non-eng device, which
4178            // should do a full dexopt.
4179            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4180            if (eng || !isFirstBoot()) {
4181                // TODO: add a property to control this?
4182                long dexOptLRUThresholdInMinutes;
4183                if (eng) {
4184                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4185                } else {
4186                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4187                }
4188                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4189
4190                int total = pkgs.size();
4191                int skipped = 0;
4192                long now = System.currentTimeMillis();
4193                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4194                    PackageParser.Package pkg = i.next();
4195                    long then = pkg.mLastPackageUsageTimeInMills;
4196                    if (then + dexOptLRUThresholdInMills < now) {
4197                        if (DEBUG_DEXOPT) {
4198                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4199                                  ((then == 0) ? "never" : new Date(then)));
4200                        }
4201                        i.remove();
4202                        skipped++;
4203                    }
4204                }
4205                if (DEBUG_DEXOPT) {
4206                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4207                }
4208            }
4209
4210            int i = 0;
4211            for (PackageParser.Package pkg : pkgs) {
4212                i++;
4213                if (DEBUG_DEXOPT) {
4214                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4215                          + ": " + pkg.packageName);
4216                }
4217                if (!isFirstBoot()) {
4218                    try {
4219                        ActivityManagerNative.getDefault().showBootMessage(
4220                                mContext.getResources().getString(
4221                                        R.string.android_upgrading_apk,
4222                                        i, pkgs.size()), true);
4223                    } catch (RemoteException e) {
4224                    }
4225                }
4226                PackageParser.Package p = pkg;
4227                synchronized (mInstallLock) {
4228                    if (p.mDexOptNeeded) {
4229                        performDexOptLI(p, false /* force dex */, false /* defer */,
4230                                true /* include dependencies */);
4231                    }
4232                }
4233            }
4234        }
4235    }
4236
4237    @Override
4238    public boolean performDexOpt(String packageName) {
4239        enforceSystemOrRoot("Only the system can request dexopt be performed");
4240        return performDexOpt(packageName, true);
4241    }
4242
4243    public boolean performDexOpt(String packageName, boolean updateUsage) {
4244
4245        PackageParser.Package p;
4246        synchronized (mPackages) {
4247            p = mPackages.get(packageName);
4248            if (p == null) {
4249                return false;
4250            }
4251            if (updateUsage) {
4252                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4253            }
4254            mPackageUsage.write(false);
4255            if (!p.mDexOptNeeded) {
4256                return false;
4257            }
4258        }
4259
4260        synchronized (mInstallLock) {
4261            return performDexOptLI(p, false /* force dex */, false /* defer */,
4262                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4263        }
4264    }
4265
4266    public HashSet<String> getPackagesThatNeedDexOpt() {
4267        HashSet<String> pkgs = null;
4268        synchronized (mPackages) {
4269            for (PackageParser.Package p : mPackages.values()) {
4270                if (DEBUG_DEXOPT) {
4271                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4272                }
4273                if (!p.mDexOptNeeded) {
4274                    continue;
4275                }
4276                if (pkgs == null) {
4277                    pkgs = new HashSet<String>();
4278                }
4279                pkgs.add(p.packageName);
4280            }
4281        }
4282        return pkgs;
4283    }
4284
4285    public void shutdown() {
4286        mPackageUsage.write(true);
4287    }
4288
4289    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4290             boolean forceDex, boolean defer, HashSet<String> done) {
4291        for (int i=0; i<libs.size(); i++) {
4292            PackageParser.Package libPkg;
4293            String libName;
4294            synchronized (mPackages) {
4295                libName = libs.get(i);
4296                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4297                if (lib != null && lib.apk != null) {
4298                    libPkg = mPackages.get(lib.apk);
4299                } else {
4300                    libPkg = null;
4301                }
4302            }
4303            if (libPkg != null && !done.contains(libName)) {
4304                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4305            }
4306        }
4307    }
4308
4309    static final int DEX_OPT_SKIPPED = 0;
4310    static final int DEX_OPT_PERFORMED = 1;
4311    static final int DEX_OPT_DEFERRED = 2;
4312    static final int DEX_OPT_FAILED = -1;
4313
4314    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4315            boolean forceDex, boolean defer, HashSet<String> done) {
4316        final String instructionSet = instructionSetOverride != null ?
4317                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4318
4319        if (done != null) {
4320            done.add(pkg.packageName);
4321            if (pkg.usesLibraries != null) {
4322                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4323            }
4324            if (pkg.usesOptionalLibraries != null) {
4325                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4326            }
4327        }
4328
4329        boolean performed = false;
4330        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4331            String path = pkg.mScanPath;
4332            try {
4333                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4334                                                                                pkg.packageName,
4335                                                                                instructionSet,
4336                                                                                defer);
4337                // There are three basic cases here:
4338                // 1.) we need to dexopt, either because we are forced or it is needed
4339                // 2.) we are defering a needed dexopt
4340                // 3.) we are skipping an unneeded dexopt
4341                if (forceDex || (!defer && isDexOptNeededInternal)) {
4342                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4343                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4344                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4345                                                pkg.packageName, instructionSet);
4346                    // Note that we ran dexopt, since rerunning will
4347                    // probably just result in an error again.
4348                    pkg.mDexOptNeeded = false;
4349                    if (ret < 0) {
4350                        return DEX_OPT_FAILED;
4351                    }
4352                    return DEX_OPT_PERFORMED;
4353                }
4354                if (defer && isDexOptNeededInternal) {
4355                    if (mDeferredDexOpt == null) {
4356                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4357                    }
4358                    mDeferredDexOpt.add(pkg);
4359                    return DEX_OPT_DEFERRED;
4360                }
4361                pkg.mDexOptNeeded = false;
4362                return DEX_OPT_SKIPPED;
4363            } catch (FileNotFoundException e) {
4364                Slog.w(TAG, "Apk not found for dexopt: " + path);
4365                return DEX_OPT_FAILED;
4366            } catch (IOException e) {
4367                Slog.w(TAG, "IOException reading apk: " + path, e);
4368                return DEX_OPT_FAILED;
4369            } catch (StaleDexCacheError e) {
4370                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4371                return DEX_OPT_FAILED;
4372            } catch (Exception e) {
4373                Slog.w(TAG, "Exception when doing dexopt : ", e);
4374                return DEX_OPT_FAILED;
4375            }
4376        }
4377        return DEX_OPT_SKIPPED;
4378    }
4379
4380    private String getAppInstructionSet(ApplicationInfo info) {
4381        String instructionSet = getPreferredInstructionSet();
4382
4383        if (info.requiredCpuAbi != null) {
4384            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4385        }
4386
4387        return instructionSet;
4388    }
4389
4390    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4391        String instructionSet = getPreferredInstructionSet();
4392
4393        if (ps.requiredCpuAbiString != null) {
4394            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4395        }
4396
4397        return instructionSet;
4398    }
4399
4400    private static String getPreferredInstructionSet() {
4401        if (sPreferredInstructionSet == null) {
4402            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4403        }
4404
4405        return sPreferredInstructionSet;
4406    }
4407
4408    private static List<String> getAllInstructionSets() {
4409        final String[] allAbis = Build.SUPPORTED_ABIS;
4410        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4411
4412        for (String abi : allAbis) {
4413            final String instructionSet = VMRuntime.getInstructionSet(abi);
4414            if (!allInstructionSets.contains(instructionSet)) {
4415                allInstructionSets.add(instructionSet);
4416            }
4417        }
4418
4419        return allInstructionSets;
4420    }
4421
4422    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4423            boolean inclDependencies) {
4424        HashSet<String> done;
4425        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4426            done = new HashSet<String>();
4427            done.add(pkg.packageName);
4428        } else {
4429            done = null;
4430        }
4431        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4432    }
4433
4434    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4435        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4436            Slog.w(TAG, "Unable to update from " + oldPkg.name
4437                    + " to " + newPkg.packageName
4438                    + ": old package not in system partition");
4439            return false;
4440        } else if (mPackages.get(oldPkg.name) != null) {
4441            Slog.w(TAG, "Unable to update from " + oldPkg.name
4442                    + " to " + newPkg.packageName
4443                    + ": old package still exists");
4444            return false;
4445        }
4446        return true;
4447    }
4448
4449    File getDataPathForUser(int userId) {
4450        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4451    }
4452
4453    private File getDataPathForPackage(String packageName, int userId) {
4454        /*
4455         * Until we fully support multiple users, return the directory we
4456         * previously would have. The PackageManagerTests will need to be
4457         * revised when this is changed back..
4458         */
4459        if (userId == 0) {
4460            return new File(mAppDataDir, packageName);
4461        } else {
4462            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4463                + File.separator + packageName);
4464        }
4465    }
4466
4467    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4468        int[] users = sUserManager.getUserIds();
4469        int res = mInstaller.install(packageName, uid, uid, seinfo);
4470        if (res < 0) {
4471            return res;
4472        }
4473        for (int user : users) {
4474            if (user != 0) {
4475                res = mInstaller.createUserData(packageName,
4476                        UserHandle.getUid(user, uid), user, seinfo);
4477                if (res < 0) {
4478                    return res;
4479                }
4480            }
4481        }
4482        return res;
4483    }
4484
4485    private int removeDataDirsLI(String packageName) {
4486        int[] users = sUserManager.getUserIds();
4487        int res = 0;
4488        for (int user : users) {
4489            int resInner = mInstaller.remove(packageName, user);
4490            if (resInner < 0) {
4491                res = resInner;
4492            }
4493        }
4494
4495        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4496        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4497        if (!nativeLibraryFile.delete()) {
4498            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4499        }
4500
4501        return res;
4502    }
4503
4504    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4505            PackageParser.Package changingLib) {
4506        if (file.path != null) {
4507            mTmpSharedLibraries[num] = file.path;
4508            return num+1;
4509        }
4510        PackageParser.Package p = mPackages.get(file.apk);
4511        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4512            // If we are doing this while in the middle of updating a library apk,
4513            // then we need to make sure to use that new apk for determining the
4514            // dependencies here.  (We haven't yet finished committing the new apk
4515            // to the package manager state.)
4516            if (p == null || p.packageName.equals(changingLib.packageName)) {
4517                p = changingLib;
4518            }
4519        }
4520        if (p != null) {
4521            String path = p.mPath;
4522            for (int i=0; i<num; i++) {
4523                if (mTmpSharedLibraries[i].equals(path)) {
4524                    return num;
4525                }
4526            }
4527            mTmpSharedLibraries[num] = p.mPath;
4528            return num+1;
4529        }
4530        return num;
4531    }
4532
4533    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4534            PackageParser.Package changingLib) {
4535        // We might be upgrading from a version of the platform that did not
4536        // provide per-package native library directories for system apps.
4537        // Fix that up here.
4538        if (isSystemApp(pkg)) {
4539            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4540            setInternalAppNativeLibraryPath(pkg, ps);
4541        }
4542
4543        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4544            if (mTmpSharedLibraries == null ||
4545                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4546                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4547            }
4548            int num = 0;
4549            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4550            for (int i=0; i<N; i++) {
4551                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4552                if (file == null) {
4553                    Slog.e(TAG, "Package " + pkg.packageName
4554                            + " requires unavailable shared library "
4555                            + pkg.usesLibraries.get(i) + "; failing!");
4556                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4557                    return false;
4558                }
4559                num = addSharedLibraryLPw(file, num, changingLib);
4560            }
4561            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4562            for (int i=0; i<N; i++) {
4563                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4564                if (file == null) {
4565                    Slog.w(TAG, "Package " + pkg.packageName
4566                            + " desires unavailable shared library "
4567                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4568                } else {
4569                    num = addSharedLibraryLPw(file, num, changingLib);
4570                }
4571            }
4572            if (num > 0) {
4573                pkg.usesLibraryFiles = new String[num];
4574                System.arraycopy(mTmpSharedLibraries, 0,
4575                        pkg.usesLibraryFiles, 0, num);
4576            } else {
4577                pkg.usesLibraryFiles = null;
4578            }
4579        }
4580        return true;
4581    }
4582
4583    private static boolean hasString(List<String> list, List<String> which) {
4584        if (list == null) {
4585            return false;
4586        }
4587        for (int i=list.size()-1; i>=0; i--) {
4588            for (int j=which.size()-1; j>=0; j--) {
4589                if (which.get(j).equals(list.get(i))) {
4590                    return true;
4591                }
4592            }
4593        }
4594        return false;
4595    }
4596
4597    private void updateAllSharedLibrariesLPw() {
4598        for (PackageParser.Package pkg : mPackages.values()) {
4599            updateSharedLibrariesLPw(pkg, null);
4600        }
4601    }
4602
4603    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4604            PackageParser.Package changingPkg) {
4605        ArrayList<PackageParser.Package> res = null;
4606        for (PackageParser.Package pkg : mPackages.values()) {
4607            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4608                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4609                if (res == null) {
4610                    res = new ArrayList<PackageParser.Package>();
4611                }
4612                res.add(pkg);
4613                updateSharedLibrariesLPw(pkg, changingPkg);
4614            }
4615        }
4616        return res;
4617    }
4618
4619    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4620            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4621        File scanFile = new File(pkg.mScanPath);
4622        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4623                pkg.applicationInfo.publicSourceDir == null) {
4624            // Bail out. The resource and code paths haven't been set.
4625            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4626            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4627            return null;
4628        }
4629
4630        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4631            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4632        }
4633
4634        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4635            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4636        }
4637
4638        if (mCustomResolverComponentName != null &&
4639                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4640            setUpCustomResolverActivity(pkg);
4641        }
4642
4643        if (pkg.packageName.equals("android")) {
4644            synchronized (mPackages) {
4645                if (mAndroidApplication != null) {
4646                    Slog.w(TAG, "*************************************************");
4647                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4648                    Slog.w(TAG, " file=" + scanFile);
4649                    Slog.w(TAG, "*************************************************");
4650                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4651                    return null;
4652                }
4653
4654                // Set up information for our fall-back user intent resolution activity.
4655                mPlatformPackage = pkg;
4656                pkg.mVersionCode = mSdkVersion;
4657                mAndroidApplication = pkg.applicationInfo;
4658
4659                if (!mResolverReplaced) {
4660                    mResolveActivity.applicationInfo = mAndroidApplication;
4661                    mResolveActivity.name = ResolverActivity.class.getName();
4662                    mResolveActivity.packageName = mAndroidApplication.packageName;
4663                    mResolveActivity.processName = "system:ui";
4664                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4665                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4666                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4667                    mResolveActivity.exported = true;
4668                    mResolveActivity.enabled = true;
4669                    mResolveInfo.activityInfo = mResolveActivity;
4670                    mResolveInfo.priority = 0;
4671                    mResolveInfo.preferredOrder = 0;
4672                    mResolveInfo.match = 0;
4673                    mResolveComponentName = new ComponentName(
4674                            mAndroidApplication.packageName, mResolveActivity.name);
4675                }
4676            }
4677        }
4678
4679        if (DEBUG_PACKAGE_SCANNING) {
4680            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4681                Log.d(TAG, "Scanning package " + pkg.packageName);
4682        }
4683
4684        if (mPackages.containsKey(pkg.packageName)
4685                || mSharedLibraries.containsKey(pkg.packageName)) {
4686            Slog.w(TAG, "Application package " + pkg.packageName
4687                    + " already installed.  Skipping duplicate.");
4688            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4689            return null;
4690        }
4691
4692        // Initialize package source and resource directories
4693        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4694        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4695
4696        SharedUserSetting suid = null;
4697        PackageSetting pkgSetting = null;
4698
4699        if (!isSystemApp(pkg)) {
4700            // Only system apps can use these features.
4701            pkg.mOriginalPackages = null;
4702            pkg.mRealPackage = null;
4703            pkg.mAdoptPermissions = null;
4704        }
4705
4706        // writer
4707        synchronized (mPackages) {
4708            if (pkg.mSharedUserId != null) {
4709                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4710                if (suid == null) {
4711                    Slog.w(TAG, "Creating application package " + pkg.packageName
4712                            + " for shared user failed");
4713                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4714                    return null;
4715                }
4716                if (DEBUG_PACKAGE_SCANNING) {
4717                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4718                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4719                                + "): packages=" + suid.packages);
4720                }
4721            }
4722
4723            // Check if we are renaming from an original package name.
4724            PackageSetting origPackage = null;
4725            String realName = null;
4726            if (pkg.mOriginalPackages != null) {
4727                // This package may need to be renamed to a previously
4728                // installed name.  Let's check on that...
4729                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4730                if (pkg.mOriginalPackages.contains(renamed)) {
4731                    // This package had originally been installed as the
4732                    // original name, and we have already taken care of
4733                    // transitioning to the new one.  Just update the new
4734                    // one to continue using the old name.
4735                    realName = pkg.mRealPackage;
4736                    if (!pkg.packageName.equals(renamed)) {
4737                        // Callers into this function may have already taken
4738                        // care of renaming the package; only do it here if
4739                        // it is not already done.
4740                        pkg.setPackageName(renamed);
4741                    }
4742
4743                } else {
4744                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4745                        if ((origPackage = mSettings.peekPackageLPr(
4746                                pkg.mOriginalPackages.get(i))) != null) {
4747                            // We do have the package already installed under its
4748                            // original name...  should we use it?
4749                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4750                                // New package is not compatible with original.
4751                                origPackage = null;
4752                                continue;
4753                            } else if (origPackage.sharedUser != null) {
4754                                // Make sure uid is compatible between packages.
4755                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4756                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4757                                            + " to " + pkg.packageName + ": old uid "
4758                                            + origPackage.sharedUser.name
4759                                            + " differs from " + pkg.mSharedUserId);
4760                                    origPackage = null;
4761                                    continue;
4762                                }
4763                            } else {
4764                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4765                                        + pkg.packageName + " to old name " + origPackage.name);
4766                            }
4767                            break;
4768                        }
4769                    }
4770                }
4771            }
4772
4773            if (mTransferedPackages.contains(pkg.packageName)) {
4774                Slog.w(TAG, "Package " + pkg.packageName
4775                        + " was transferred to another, but its .apk remains");
4776            }
4777
4778            // Just create the setting, don't add it yet. For already existing packages
4779            // the PkgSetting exists already and doesn't have to be created.
4780            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4781                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4782                    pkg.applicationInfo.requiredCpuAbi,
4783                    pkg.applicationInfo.flags, user, false);
4784            if (pkgSetting == null) {
4785                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4786                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4787                return null;
4788            }
4789
4790            if (pkgSetting.origPackage != null) {
4791                // If we are first transitioning from an original package,
4792                // fix up the new package's name now.  We need to do this after
4793                // looking up the package under its new name, so getPackageLP
4794                // can take care of fiddling things correctly.
4795                pkg.setPackageName(origPackage.name);
4796
4797                // File a report about this.
4798                String msg = "New package " + pkgSetting.realName
4799                        + " renamed to replace old package " + pkgSetting.name;
4800                reportSettingsProblem(Log.WARN, msg);
4801
4802                // Make a note of it.
4803                mTransferedPackages.add(origPackage.name);
4804
4805                // No longer need to retain this.
4806                pkgSetting.origPackage = null;
4807            }
4808
4809            if (realName != null) {
4810                // Make a note of it.
4811                mTransferedPackages.add(pkg.packageName);
4812            }
4813
4814            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4815                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4816            }
4817
4818            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4819                // Check all shared libraries and map to their actual file path.
4820                // We only do this here for apps not on a system dir, because those
4821                // are the only ones that can fail an install due to this.  We
4822                // will take care of the system apps by updating all of their
4823                // library paths after the scan is done.
4824                if (!updateSharedLibrariesLPw(pkg, null)) {
4825                    return null;
4826                }
4827            }
4828
4829            if (mFoundPolicyFile) {
4830                SELinuxMMAC.assignSeinfoValue(pkg);
4831            }
4832
4833            pkg.applicationInfo.uid = pkgSetting.appId;
4834            pkg.mExtras = pkgSetting;
4835
4836            if (!verifySignaturesLP(pkgSetting, pkg)) {
4837                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4838                    return null;
4839                }
4840                // The signature has changed, but this package is in the system
4841                // image...  let's recover!
4842                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4843                // However...  if this package is part of a shared user, but it
4844                // doesn't match the signature of the shared user, let's fail.
4845                // What this means is that you can't change the signatures
4846                // associated with an overall shared user, which doesn't seem all
4847                // that unreasonable.
4848                if (pkgSetting.sharedUser != null) {
4849                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4850                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4851                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4852                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4853                        return null;
4854                    }
4855                }
4856                // File a report about this.
4857                String msg = "System package " + pkg.packageName
4858                        + " signature changed; retaining data.";
4859                reportSettingsProblem(Log.WARN, msg);
4860            }
4861
4862            // Verify that this new package doesn't have any content providers
4863            // that conflict with existing packages.  Only do this if the
4864            // package isn't already installed, since we don't want to break
4865            // things that are installed.
4866            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4867                final int N = pkg.providers.size();
4868                int i;
4869                for (i=0; i<N; i++) {
4870                    PackageParser.Provider p = pkg.providers.get(i);
4871                    if (p.info.authority != null) {
4872                        String names[] = p.info.authority.split(";");
4873                        for (int j = 0; j < names.length; j++) {
4874                            if (mProvidersByAuthority.containsKey(names[j])) {
4875                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4876                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4877                                        " (in package " + pkg.applicationInfo.packageName +
4878                                        ") is already used by "
4879                                        + ((other != null && other.getComponentName() != null)
4880                                                ? other.getComponentName().getPackageName() : "?"));
4881                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4882                                return null;
4883                            }
4884                        }
4885                    }
4886                }
4887            }
4888
4889            if (pkg.mAdoptPermissions != null) {
4890                // This package wants to adopt ownership of permissions from
4891                // another package.
4892                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4893                    final String origName = pkg.mAdoptPermissions.get(i);
4894                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4895                    if (orig != null) {
4896                        if (verifyPackageUpdateLPr(orig, pkg)) {
4897                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4898                                    + pkg.packageName);
4899                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4900                        }
4901                    }
4902                }
4903            }
4904        }
4905
4906        final String pkgName = pkg.packageName;
4907
4908        final long scanFileTime = scanFile.lastModified();
4909        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4910        pkg.applicationInfo.processName = fixProcessName(
4911                pkg.applicationInfo.packageName,
4912                pkg.applicationInfo.processName,
4913                pkg.applicationInfo.uid);
4914
4915        File dataPath;
4916        if (mPlatformPackage == pkg) {
4917            // The system package is special.
4918            dataPath = new File (Environment.getDataDirectory(), "system");
4919            pkg.applicationInfo.dataDir = dataPath.getPath();
4920        } else {
4921            // This is a normal package, need to make its data directory.
4922            dataPath = getDataPathForPackage(pkg.packageName, 0);
4923
4924            boolean uidError = false;
4925
4926            if (dataPath.exists()) {
4927                int currentUid = 0;
4928                try {
4929                    StructStat stat = Os.stat(dataPath.getPath());
4930                    currentUid = stat.st_uid;
4931                } catch (ErrnoException e) {
4932                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4933                }
4934
4935                // If we have mismatched owners for the data path, we have a problem.
4936                if (currentUid != pkg.applicationInfo.uid) {
4937                    boolean recovered = false;
4938                    if (currentUid == 0) {
4939                        // The directory somehow became owned by root.  Wow.
4940                        // This is probably because the system was stopped while
4941                        // installd was in the middle of messing with its libs
4942                        // directory.  Ask installd to fix that.
4943                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4944                                pkg.applicationInfo.uid);
4945                        if (ret >= 0) {
4946                            recovered = true;
4947                            String msg = "Package " + pkg.packageName
4948                                    + " unexpectedly changed to uid 0; recovered to " +
4949                                    + pkg.applicationInfo.uid;
4950                            reportSettingsProblem(Log.WARN, msg);
4951                        }
4952                    }
4953                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4954                            || (scanMode&SCAN_BOOTING) != 0)) {
4955                        // If this is a system app, we can at least delete its
4956                        // current data so the application will still work.
4957                        int ret = removeDataDirsLI(pkgName);
4958                        if (ret >= 0) {
4959                            // TODO: Kill the processes first
4960                            // Old data gone!
4961                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4962                                    ? "System package " : "Third party package ";
4963                            String msg = prefix + pkg.packageName
4964                                    + " has changed from uid: "
4965                                    + currentUid + " to "
4966                                    + pkg.applicationInfo.uid + "; old data erased";
4967                            reportSettingsProblem(Log.WARN, msg);
4968                            recovered = true;
4969
4970                            // And now re-install the app.
4971                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4972                                                   pkg.applicationInfo.seinfo);
4973                            if (ret == -1) {
4974                                // Ack should not happen!
4975                                msg = prefix + pkg.packageName
4976                                        + " could not have data directory re-created after delete.";
4977                                reportSettingsProblem(Log.WARN, msg);
4978                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4979                                return null;
4980                            }
4981                        }
4982                        if (!recovered) {
4983                            mHasSystemUidErrors = true;
4984                        }
4985                    } else if (!recovered) {
4986                        // If we allow this install to proceed, we will be broken.
4987                        // Abort, abort!
4988                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4989                        return null;
4990                    }
4991                    if (!recovered) {
4992                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4993                            + pkg.applicationInfo.uid + "/fs_"
4994                            + currentUid;
4995                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4996                        String msg = "Package " + pkg.packageName
4997                                + " has mismatched uid: "
4998                                + currentUid + " on disk, "
4999                                + pkg.applicationInfo.uid + " in settings";
5000                        // writer
5001                        synchronized (mPackages) {
5002                            mSettings.mReadMessages.append(msg);
5003                            mSettings.mReadMessages.append('\n');
5004                            uidError = true;
5005                            if (!pkgSetting.uidError) {
5006                                reportSettingsProblem(Log.ERROR, msg);
5007                            }
5008                        }
5009                    }
5010                }
5011                pkg.applicationInfo.dataDir = dataPath.getPath();
5012                if (mShouldRestoreconData) {
5013                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5014                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5015                                pkg.applicationInfo.uid);
5016                }
5017            } else {
5018                if (DEBUG_PACKAGE_SCANNING) {
5019                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5020                        Log.v(TAG, "Want this data dir: " + dataPath);
5021                }
5022                //invoke installer to do the actual installation
5023                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5024                                           pkg.applicationInfo.seinfo);
5025                if (ret < 0) {
5026                    // Error from installer
5027                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5028                    return null;
5029                }
5030
5031                if (dataPath.exists()) {
5032                    pkg.applicationInfo.dataDir = dataPath.getPath();
5033                } else {
5034                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5035                    pkg.applicationInfo.dataDir = null;
5036                }
5037            }
5038
5039            /*
5040             * Set the data dir to the default "/data/data/<package name>/lib"
5041             * if we got here without anyone telling us different (e.g., apps
5042             * stored on SD card have their native libraries stored in the ASEC
5043             * container with the APK).
5044             *
5045             * This happens during an upgrade from a package settings file that
5046             * doesn't have a native library path attribute at all.
5047             */
5048            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5049                if (pkgSetting.nativeLibraryPathString == null) {
5050                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5051                } else {
5052                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5053                }
5054            }
5055            pkgSetting.uidError = uidError;
5056        }
5057
5058        String path = scanFile.getPath();
5059        /* Note: We don't want to unpack the native binaries for
5060         *        system applications, unless they have been updated
5061         *        (the binaries are already under /system/lib).
5062         *        Also, don't unpack libs for apps on the external card
5063         *        since they should have their libraries in the ASEC
5064         *        container already.
5065         *
5066         *        In other words, we're going to unpack the binaries
5067         *        only for non-system apps and system app upgrades.
5068         */
5069        if (pkg.applicationInfo.nativeLibraryDir != null) {
5070            try {
5071                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5072                final String dataPathString = dataPath.getCanonicalPath();
5073
5074                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5075                    /*
5076                     * Upgrading from a previous version of the OS sometimes
5077                     * leaves native libraries in the /data/data/<app>/lib
5078                     * directory for system apps even when they shouldn't be.
5079                     * Recent changes in the JNI library search path
5080                     * necessitates we remove those to match previous behavior.
5081                     */
5082                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5083                        Log.i(TAG, "removed obsolete native libraries for system package "
5084                                + path);
5085                    }
5086
5087                    setInternalAppAbi(pkg, pkgSetting);
5088                } else {
5089                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5090                        /*
5091                         * Update native library dir if it starts with
5092                         * /data/data
5093                         */
5094                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5095                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5096                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5097                        }
5098
5099                        try {
5100                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5101                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5102                                Slog.e(TAG, "Unable to copy native libraries");
5103                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5104                                return null;
5105                            }
5106
5107                            // We've successfully copied native libraries across, so we make a
5108                            // note of what ABI we're using
5109                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5110                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
5111                            } else {
5112                                pkg.applicationInfo.requiredCpuAbi = null;
5113                            }
5114                        } catch (IOException e) {
5115                            Slog.e(TAG, "Unable to copy native libraries", e);
5116                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5117                            return null;
5118                        }
5119                    } else {
5120                        // We don't have to copy the shared libraries if we're in the ASEC container
5121                        // but we still need to scan the file to figure out what ABI the app needs.
5122                        //
5123                        // TODO: This duplicates work done in the default container service. It's possible
5124                        // to clean this up but we'll need to change the interface between this service
5125                        // and IMediaContainerService (but doing so will spread this logic out, rather
5126                        // than centralizing it).
5127                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5128                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5129                        if (abi >= 0) {
5130                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
5131                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5132                            // Note that (non upgraded) system apps will not have any native
5133                            // libraries bundled in their APK, but we're guaranteed not to be
5134                            // such an app at this point.
5135                            pkg.applicationInfo.requiredCpuAbi = null;
5136                        } else {
5137                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5138                            return null;
5139                        }
5140                        handle.close();
5141                    }
5142
5143                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5144                    final int[] userIds = sUserManager.getUserIds();
5145                    synchronized (mInstallLock) {
5146                        for (int userId : userIds) {
5147                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5148                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5149                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5150                                        + ")");
5151                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5152                                return null;
5153                            }
5154                        }
5155                    }
5156                }
5157            } catch (IOException ioe) {
5158                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5159            }
5160        }
5161        pkg.mScanPath = path;
5162
5163        if ((scanMode&SCAN_NO_DEX) == 0) {
5164            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5165                    == DEX_OPT_FAILED) {
5166                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5167                    removeDataDirsLI(pkg.packageName);
5168                }
5169
5170                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5171                return null;
5172            }
5173        }
5174
5175        if (mFactoryTest && pkg.requestedPermissions.contains(
5176                android.Manifest.permission.FACTORY_TEST)) {
5177            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5178        }
5179
5180        ArrayList<PackageParser.Package> clientLibPkgs = null;
5181
5182        // writer
5183        synchronized (mPackages) {
5184            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5185                // Only system apps can add new shared libraries.
5186                if (pkg.libraryNames != null) {
5187                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5188                        String name = pkg.libraryNames.get(i);
5189                        boolean allowed = false;
5190                        if (isUpdatedSystemApp(pkg)) {
5191                            // New library entries can only be added through the
5192                            // system image.  This is important to get rid of a lot
5193                            // of nasty edge cases: for example if we allowed a non-
5194                            // system update of the app to add a library, then uninstalling
5195                            // the update would make the library go away, and assumptions
5196                            // we made such as through app install filtering would now
5197                            // have allowed apps on the device which aren't compatible
5198                            // with it.  Better to just have the restriction here, be
5199                            // conservative, and create many fewer cases that can negatively
5200                            // impact the user experience.
5201                            final PackageSetting sysPs = mSettings
5202                                    .getDisabledSystemPkgLPr(pkg.packageName);
5203                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5204                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5205                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5206                                        allowed = true;
5207                                        allowed = true;
5208                                        break;
5209                                    }
5210                                }
5211                            }
5212                        } else {
5213                            allowed = true;
5214                        }
5215                        if (allowed) {
5216                            if (!mSharedLibraries.containsKey(name)) {
5217                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5218                            } else if (!name.equals(pkg.packageName)) {
5219                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5220                                        + name + " already exists; skipping");
5221                            }
5222                        } else {
5223                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5224                                    + name + " that is not declared on system image; skipping");
5225                        }
5226                    }
5227                    if ((scanMode&SCAN_BOOTING) == 0) {
5228                        // If we are not booting, we need to update any applications
5229                        // that are clients of our shared library.  If we are booting,
5230                        // this will all be done once the scan is complete.
5231                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5232                    }
5233                }
5234            }
5235        }
5236
5237        // We also need to dexopt any apps that are dependent on this library.  Note that
5238        // if these fail, we should abort the install since installing the library will
5239        // result in some apps being broken.
5240        if (clientLibPkgs != null) {
5241            if ((scanMode&SCAN_NO_DEX) == 0) {
5242                for (int i=0; i<clientLibPkgs.size(); i++) {
5243                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5244                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5245                            == DEX_OPT_FAILED) {
5246                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5247                            removeDataDirsLI(pkg.packageName);
5248                        }
5249
5250                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5251                        return null;
5252                    }
5253                }
5254            }
5255        }
5256
5257        // Request the ActivityManager to kill the process(only for existing packages)
5258        // so that we do not end up in a confused state while the user is still using the older
5259        // version of the application while the new one gets installed.
5260        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5261            // If the package lives in an asec, tell everyone that the container is going
5262            // away so they can clean up any references to its resources (which would prevent
5263            // vold from being able to unmount the asec)
5264            if (isForwardLocked(pkg) || isExternal(pkg)) {
5265                if (DEBUG_INSTALL) {
5266                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5267                }
5268                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5269                final ArrayList<String> pkgList = new ArrayList<String>(1);
5270                pkgList.add(pkg.applicationInfo.packageName);
5271                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5272            }
5273
5274            // Post the request that it be killed now that the going-away broadcast is en route
5275            killApplication(pkg.applicationInfo.packageName,
5276                        pkg.applicationInfo.uid, "update pkg");
5277        }
5278
5279        // Also need to kill any apps that are dependent on the library.
5280        if (clientLibPkgs != null) {
5281            for (int i=0; i<clientLibPkgs.size(); i++) {
5282                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5283                killApplication(clientPkg.applicationInfo.packageName,
5284                        clientPkg.applicationInfo.uid, "update lib");
5285            }
5286        }
5287
5288        // writer
5289        synchronized (mPackages) {
5290            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5291                // We don't do this here during boot because we can do it all
5292                // at once after scanning all existing packages.
5293                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5294                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5295            }
5296            // We don't expect installation to fail beyond this point,
5297            if ((scanMode&SCAN_MONITOR) != 0) {
5298                mAppDirs.put(pkg.mPath, pkg);
5299            }
5300            // Add the new setting to mSettings
5301            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5302            // Add the new setting to mPackages
5303            mPackages.put(pkg.applicationInfo.packageName, pkg);
5304            // Make sure we don't accidentally delete its data.
5305            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5306            while (iter.hasNext()) {
5307                PackageCleanItem item = iter.next();
5308                if (pkgName.equals(item.packageName)) {
5309                    iter.remove();
5310                }
5311            }
5312
5313            // Take care of first install / last update times.
5314            if (currentTime != 0) {
5315                if (pkgSetting.firstInstallTime == 0) {
5316                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5317                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5318                    pkgSetting.lastUpdateTime = currentTime;
5319                }
5320            } else if (pkgSetting.firstInstallTime == 0) {
5321                // We need *something*.  Take time time stamp of the file.
5322                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5323            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5324                if (scanFileTime != pkgSetting.timeStamp) {
5325                    // A package on the system image has changed; consider this
5326                    // to be an update.
5327                    pkgSetting.lastUpdateTime = scanFileTime;
5328                }
5329            }
5330
5331            // Add the package's KeySets to the global KeySetManager
5332            KeySetManager ksm = mSettings.mKeySetManager;
5333            try {
5334                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5335                if (pkg.mKeySetMapping != null) {
5336                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5337                        if (entry.getValue() != null) {
5338                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5339                                entry.getValue(), entry.getKey());
5340                        }
5341                    }
5342                }
5343            } catch (NullPointerException e) {
5344                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5345            } catch (IllegalArgumentException e) {
5346                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5347            }
5348
5349            int N = pkg.providers.size();
5350            StringBuilder r = null;
5351            int i;
5352            for (i=0; i<N; i++) {
5353                PackageParser.Provider p = pkg.providers.get(i);
5354                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5355                        p.info.processName, pkg.applicationInfo.uid);
5356                mProviders.addProvider(p);
5357                p.syncable = p.info.isSyncable;
5358                if (p.info.authority != null) {
5359                    String names[] = p.info.authority.split(";");
5360                    p.info.authority = null;
5361                    for (int j = 0; j < names.length; j++) {
5362                        if (j == 1 && p.syncable) {
5363                            // We only want the first authority for a provider to possibly be
5364                            // syncable, so if we already added this provider using a different
5365                            // authority clear the syncable flag. We copy the provider before
5366                            // changing it because the mProviders object contains a reference
5367                            // to a provider that we don't want to change.
5368                            // Only do this for the second authority since the resulting provider
5369                            // object can be the same for all future authorities for this provider.
5370                            p = new PackageParser.Provider(p);
5371                            p.syncable = false;
5372                        }
5373                        if (!mProvidersByAuthority.containsKey(names[j])) {
5374                            mProvidersByAuthority.put(names[j], p);
5375                            if (p.info.authority == null) {
5376                                p.info.authority = names[j];
5377                            } else {
5378                                p.info.authority = p.info.authority + ";" + names[j];
5379                            }
5380                            if (DEBUG_PACKAGE_SCANNING) {
5381                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5382                                    Log.d(TAG, "Registered content provider: " + names[j]
5383                                            + ", className = " + p.info.name + ", isSyncable = "
5384                                            + p.info.isSyncable);
5385                            }
5386                        } else {
5387                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5388                            Slog.w(TAG, "Skipping provider name " + names[j] +
5389                                    " (in package " + pkg.applicationInfo.packageName +
5390                                    "): name already used by "
5391                                    + ((other != null && other.getComponentName() != null)
5392                                            ? other.getComponentName().getPackageName() : "?"));
5393                        }
5394                    }
5395                }
5396                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5397                    if (r == null) {
5398                        r = new StringBuilder(256);
5399                    } else {
5400                        r.append(' ');
5401                    }
5402                    r.append(p.info.name);
5403                }
5404            }
5405            if (r != null) {
5406                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5407            }
5408
5409            N = pkg.services.size();
5410            r = null;
5411            for (i=0; i<N; i++) {
5412                PackageParser.Service s = pkg.services.get(i);
5413                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5414                        s.info.processName, pkg.applicationInfo.uid);
5415                mServices.addService(s);
5416                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5417                    if (r == null) {
5418                        r = new StringBuilder(256);
5419                    } else {
5420                        r.append(' ');
5421                    }
5422                    r.append(s.info.name);
5423                }
5424            }
5425            if (r != null) {
5426                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5427            }
5428
5429            N = pkg.receivers.size();
5430            r = null;
5431            for (i=0; i<N; i++) {
5432                PackageParser.Activity a = pkg.receivers.get(i);
5433                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5434                        a.info.processName, pkg.applicationInfo.uid);
5435                mReceivers.addActivity(a, "receiver");
5436                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5437                    if (r == null) {
5438                        r = new StringBuilder(256);
5439                    } else {
5440                        r.append(' ');
5441                    }
5442                    r.append(a.info.name);
5443                }
5444            }
5445            if (r != null) {
5446                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5447            }
5448
5449            N = pkg.activities.size();
5450            r = null;
5451            for (i=0; i<N; i++) {
5452                PackageParser.Activity a = pkg.activities.get(i);
5453                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5454                        a.info.processName, pkg.applicationInfo.uid);
5455                mActivities.addActivity(a, "activity");
5456                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5457                    if (r == null) {
5458                        r = new StringBuilder(256);
5459                    } else {
5460                        r.append(' ');
5461                    }
5462                    r.append(a.info.name);
5463                }
5464            }
5465            if (r != null) {
5466                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5467            }
5468
5469            N = pkg.permissionGroups.size();
5470            r = null;
5471            for (i=0; i<N; i++) {
5472                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5473                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5474                if (cur == null) {
5475                    mPermissionGroups.put(pg.info.name, pg);
5476                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5477                        if (r == null) {
5478                            r = new StringBuilder(256);
5479                        } else {
5480                            r.append(' ');
5481                        }
5482                        r.append(pg.info.name);
5483                    }
5484                } else {
5485                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5486                            + pg.info.packageName + " ignored: original from "
5487                            + cur.info.packageName);
5488                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5489                        if (r == null) {
5490                            r = new StringBuilder(256);
5491                        } else {
5492                            r.append(' ');
5493                        }
5494                        r.append("DUP:");
5495                        r.append(pg.info.name);
5496                    }
5497                }
5498            }
5499            if (r != null) {
5500                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5501            }
5502
5503            N = pkg.permissions.size();
5504            r = null;
5505            for (i=0; i<N; i++) {
5506                PackageParser.Permission p = pkg.permissions.get(i);
5507                HashMap<String, BasePermission> permissionMap =
5508                        p.tree ? mSettings.mPermissionTrees
5509                        : mSettings.mPermissions;
5510                p.group = mPermissionGroups.get(p.info.group);
5511                if (p.info.group == null || p.group != null) {
5512                    BasePermission bp = permissionMap.get(p.info.name);
5513                    if (bp == null) {
5514                        bp = new BasePermission(p.info.name, p.info.packageName,
5515                                BasePermission.TYPE_NORMAL);
5516                        permissionMap.put(p.info.name, bp);
5517                    }
5518                    if (bp.perm == null) {
5519                        if (bp.sourcePackage != null
5520                                && !bp.sourcePackage.equals(p.info.packageName)) {
5521                            // If this is a permission that was formerly defined by a non-system
5522                            // app, but is now defined by a system app (following an upgrade),
5523                            // discard the previous declaration and consider the system's to be
5524                            // canonical.
5525                            if (isSystemApp(p.owner)) {
5526                                Slog.i(TAG, "New decl " + p.owner + " of permission  "
5527                                        + p.info.name + " is system");
5528                                bp.sourcePackage = null;
5529                            }
5530                        }
5531                        if (bp.sourcePackage == null
5532                                || bp.sourcePackage.equals(p.info.packageName)) {
5533                            BasePermission tree = findPermissionTreeLP(p.info.name);
5534                            if (tree == null
5535                                    || tree.sourcePackage.equals(p.info.packageName)) {
5536                                bp.packageSetting = pkgSetting;
5537                                bp.perm = p;
5538                                bp.uid = pkg.applicationInfo.uid;
5539                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5540                                    if (r == null) {
5541                                        r = new StringBuilder(256);
5542                                    } else {
5543                                        r.append(' ');
5544                                    }
5545                                    r.append(p.info.name);
5546                                }
5547                            } else {
5548                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5549                                        + p.info.packageName + " ignored: base tree "
5550                                        + tree.name + " is from package "
5551                                        + tree.sourcePackage);
5552                            }
5553                        } else {
5554                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5555                                    + p.info.packageName + " ignored: original from "
5556                                    + bp.sourcePackage);
5557                        }
5558                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5559                        if (r == null) {
5560                            r = new StringBuilder(256);
5561                        } else {
5562                            r.append(' ');
5563                        }
5564                        r.append("DUP:");
5565                        r.append(p.info.name);
5566                    }
5567                    if (bp.perm == p) {
5568                        bp.protectionLevel = p.info.protectionLevel;
5569                    }
5570                } else {
5571                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5572                            + p.info.packageName + " ignored: no group "
5573                            + p.group);
5574                }
5575            }
5576            if (r != null) {
5577                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5578            }
5579
5580            N = pkg.instrumentation.size();
5581            r = null;
5582            for (i=0; i<N; i++) {
5583                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5584                a.info.packageName = pkg.applicationInfo.packageName;
5585                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5586                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5587                a.info.dataDir = pkg.applicationInfo.dataDir;
5588                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5589                mInstrumentation.put(a.getComponentName(), a);
5590                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5591                    if (r == null) {
5592                        r = new StringBuilder(256);
5593                    } else {
5594                        r.append(' ');
5595                    }
5596                    r.append(a.info.name);
5597                }
5598            }
5599            if (r != null) {
5600                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5601            }
5602
5603            if (pkg.protectedBroadcasts != null) {
5604                N = pkg.protectedBroadcasts.size();
5605                for (i=0; i<N; i++) {
5606                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5607                }
5608            }
5609
5610            pkgSetting.setTimeStamp(scanFileTime);
5611
5612            // Create idmap files for pairs of (packages, overlay packages).
5613            // Note: "android", ie framework-res.apk, is handled by native layers.
5614            if (pkg.mOverlayTarget != null) {
5615                // This is an overlay package.
5616                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5617                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5618                        mOverlays.put(pkg.mOverlayTarget,
5619                                new HashMap<String, PackageParser.Package>());
5620                    }
5621                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5622                    map.put(pkg.packageName, pkg);
5623                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5624                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5625                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5626                        return null;
5627                    }
5628                }
5629            } else if (mOverlays.containsKey(pkg.packageName) &&
5630                    !pkg.packageName.equals("android")) {
5631                // This is a regular package, with one or more known overlay packages.
5632                createIdmapsForPackageLI(pkg);
5633            }
5634        }
5635
5636        return pkg;
5637    }
5638
5639    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5640            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5641        String requiredInstructionSet = null;
5642        PackageSetting requirer = null;
5643        for (PackageSetting ps : packagesForUser) {
5644            if (ps.requiredCpuAbiString != null) {
5645                final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
5646                if (requiredInstructionSet != null) {
5647                    if (!instructionSet.equals(requiredInstructionSet)) {
5648                        // We have a mismatch between instruction sets (say arm vs arm64).
5649                        //
5650                        // TODO: We should rescan all the packages in a shared UID to check if
5651                        // they do contain shared libs for other ABIs in addition to the ones we've
5652                        // already extracted. For example, the package might contain both arm64-v8a
5653                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5654                        // devices.
5655                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5656                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5657                                + " requires " + instructionSet;
5658                        Slog.e(TAG, errorMessage);
5659
5660                        reportSettingsProblem(Log.WARN, errorMessage);
5661                        // Give up, don't bother making any other changes to the package settings.
5662                        return;
5663                    }
5664                } else {
5665                    requiredInstructionSet = instructionSet;
5666                    requirer = ps;
5667                }
5668            }
5669        }
5670
5671        if (requiredInstructionSet != null) {
5672            for (PackageSetting ps : packagesForUser) {
5673                if (ps.requiredCpuAbiString == null) {
5674                    ps.requiredCpuAbiString = requirer.requiredCpuAbiString;
5675                    if (ps.pkg != null) {
5676                        ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString;
5677                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString);
5678                        if (doDexOpt) {
5679                            performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
5680                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5681                        }
5682                    }
5683                }
5684            }
5685        }
5686    }
5687
5688    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5689        synchronized (mPackages) {
5690            mResolverReplaced = true;
5691            // Set up information for custom user intent resolution activity.
5692            mResolveActivity.applicationInfo = pkg.applicationInfo;
5693            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5694            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5695            mResolveActivity.processName = null;
5696            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5697            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5698                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5699            mResolveActivity.theme = 0;
5700            mResolveActivity.exported = true;
5701            mResolveActivity.enabled = true;
5702            mResolveInfo.activityInfo = mResolveActivity;
5703            mResolveInfo.priority = 0;
5704            mResolveInfo.preferredOrder = 0;
5705            mResolveInfo.match = 0;
5706            mResolveComponentName = mCustomResolverComponentName;
5707            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5708                    mResolveComponentName);
5709        }
5710    }
5711
5712    private String calculateApkRoot(final String codePathString) {
5713        final File codePath = new File(codePathString);
5714        final File codeRoot;
5715        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5716            codeRoot = Environment.getRootDirectory();
5717        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5718            codeRoot = Environment.getOemDirectory();
5719        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5720            codeRoot = Environment.getVendorDirectory();
5721        } else {
5722            // Unrecognized code path; take its top real segment as the apk root:
5723            // e.g. /something/app/blah.apk => /something
5724            try {
5725                File f = codePath.getCanonicalFile();
5726                File parent = f.getParentFile();    // non-null because codePath is a file
5727                File tmp;
5728                while ((tmp = parent.getParentFile()) != null) {
5729                    f = parent;
5730                    parent = tmp;
5731                }
5732                codeRoot = f;
5733                Slog.w(TAG, "Unrecognized code path "
5734                        + codePath + " - using " + codeRoot);
5735            } catch (IOException e) {
5736                // Can't canonicalize the lib path -- shenanigans?
5737                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5738                return Environment.getRootDirectory().getPath();
5739            }
5740        }
5741        return codeRoot.getPath();
5742    }
5743
5744    // This is the initial scan-time determination of how to handle a given
5745    // package for purposes of native library location.
5746    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5747            PackageSetting pkgSetting) {
5748        // "bundled" here means system-installed with no overriding update
5749        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5750        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5751        final File libDir;
5752        if (bundledApk) {
5753            // If "/system/lib64/apkname" exists, assume that is the per-package
5754            // native library directory to use; otherwise use "/system/lib/apkname".
5755            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5756            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5757            File packLib64 = new File(lib64, apkName);
5758            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5759        } else {
5760            libDir = mAppLibInstallDir;
5761        }
5762        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5763        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5764        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5765    }
5766
5767    // Deduces the required ABI of an upgraded system app.
5768    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
5769        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5770        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5771
5772        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
5773        // or similar.
5774        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
5775        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
5776
5777        // Assume that the bundled native libraries always correspond to the
5778        // most preferred 32 or 64 bit ABI.
5779        if (lib64.exists()) {
5780            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
5781            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
5782        } else if (lib.exists()) {
5783            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5784            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
5785        } else {
5786            // This is the case where the app has no native code.
5787            pkg.applicationInfo.requiredCpuAbi = null;
5788            pkgSetting.requiredCpuAbiString = null;
5789        }
5790    }
5791
5792    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5793            throws IOException {
5794        if (!nativeLibraryDir.isDirectory()) {
5795            nativeLibraryDir.delete();
5796
5797            if (!nativeLibraryDir.mkdir()) {
5798                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5799            }
5800
5801            try {
5802                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5803            } catch (ErrnoException e) {
5804                throw new IOException("Cannot chmod native library directory "
5805                        + nativeLibraryDir.getPath(), e);
5806            }
5807        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5808            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5809        }
5810
5811        /*
5812         * If this is an internal application or our nativeLibraryPath points to
5813         * the app-lib directory, unpack the libraries if necessary.
5814         */
5815        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5816        try {
5817            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5818            if (abi >= 0) {
5819                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5820                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5821                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5822                    return copyRet;
5823                }
5824            }
5825
5826            return abi;
5827        } finally {
5828            handle.close();
5829        }
5830    }
5831
5832    private void killApplication(String pkgName, int appId, String reason) {
5833        // Request the ActivityManager to kill the process(only for existing packages)
5834        // so that we do not end up in a confused state while the user is still using the older
5835        // version of the application while the new one gets installed.
5836        IActivityManager am = ActivityManagerNative.getDefault();
5837        if (am != null) {
5838            try {
5839                am.killApplicationWithAppId(pkgName, appId, reason);
5840            } catch (RemoteException e) {
5841            }
5842        }
5843    }
5844
5845    void removePackageLI(PackageSetting ps, boolean chatty) {
5846        if (DEBUG_INSTALL) {
5847            if (chatty)
5848                Log.d(TAG, "Removing package " + ps.name);
5849        }
5850
5851        // writer
5852        synchronized (mPackages) {
5853            mPackages.remove(ps.name);
5854            if (ps.codePathString != null) {
5855                mAppDirs.remove(ps.codePathString);
5856            }
5857
5858            final PackageParser.Package pkg = ps.pkg;
5859            if (pkg != null) {
5860                cleanPackageDataStructuresLILPw(pkg, chatty);
5861            }
5862        }
5863    }
5864
5865    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5866        if (DEBUG_INSTALL) {
5867            if (chatty)
5868                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5869        }
5870
5871        // writer
5872        synchronized (mPackages) {
5873            mPackages.remove(pkg.applicationInfo.packageName);
5874            if (pkg.mPath != null) {
5875                mAppDirs.remove(pkg.mPath);
5876            }
5877            cleanPackageDataStructuresLILPw(pkg, chatty);
5878        }
5879    }
5880
5881    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5882        int N = pkg.providers.size();
5883        StringBuilder r = null;
5884        int i;
5885        for (i=0; i<N; i++) {
5886            PackageParser.Provider p = pkg.providers.get(i);
5887            mProviders.removeProvider(p);
5888            if (p.info.authority == null) {
5889
5890                /* There was another ContentProvider with this authority when
5891                 * this app was installed so this authority is null,
5892                 * Ignore it as we don't have to unregister the provider.
5893                 */
5894                continue;
5895            }
5896            String names[] = p.info.authority.split(";");
5897            for (int j = 0; j < names.length; j++) {
5898                if (mProvidersByAuthority.get(names[j]) == p) {
5899                    mProvidersByAuthority.remove(names[j]);
5900                    if (DEBUG_REMOVE) {
5901                        if (chatty)
5902                            Log.d(TAG, "Unregistered content provider: " + names[j]
5903                                    + ", className = " + p.info.name + ", isSyncable = "
5904                                    + p.info.isSyncable);
5905                    }
5906                }
5907            }
5908            if (DEBUG_REMOVE && chatty) {
5909                if (r == null) {
5910                    r = new StringBuilder(256);
5911                } else {
5912                    r.append(' ');
5913                }
5914                r.append(p.info.name);
5915            }
5916        }
5917        if (r != null) {
5918            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5919        }
5920
5921        N = pkg.services.size();
5922        r = null;
5923        for (i=0; i<N; i++) {
5924            PackageParser.Service s = pkg.services.get(i);
5925            mServices.removeService(s);
5926            if (chatty) {
5927                if (r == null) {
5928                    r = new StringBuilder(256);
5929                } else {
5930                    r.append(' ');
5931                }
5932                r.append(s.info.name);
5933            }
5934        }
5935        if (r != null) {
5936            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5937        }
5938
5939        N = pkg.receivers.size();
5940        r = null;
5941        for (i=0; i<N; i++) {
5942            PackageParser.Activity a = pkg.receivers.get(i);
5943            mReceivers.removeActivity(a, "receiver");
5944            if (DEBUG_REMOVE && chatty) {
5945                if (r == null) {
5946                    r = new StringBuilder(256);
5947                } else {
5948                    r.append(' ');
5949                }
5950                r.append(a.info.name);
5951            }
5952        }
5953        if (r != null) {
5954            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5955        }
5956
5957        N = pkg.activities.size();
5958        r = null;
5959        for (i=0; i<N; i++) {
5960            PackageParser.Activity a = pkg.activities.get(i);
5961            mActivities.removeActivity(a, "activity");
5962            if (DEBUG_REMOVE && chatty) {
5963                if (r == null) {
5964                    r = new StringBuilder(256);
5965                } else {
5966                    r.append(' ');
5967                }
5968                r.append(a.info.name);
5969            }
5970        }
5971        if (r != null) {
5972            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5973        }
5974
5975        N = pkg.permissions.size();
5976        r = null;
5977        for (i=0; i<N; i++) {
5978            PackageParser.Permission p = pkg.permissions.get(i);
5979            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5980            if (bp == null) {
5981                bp = mSettings.mPermissionTrees.get(p.info.name);
5982            }
5983            if (bp != null && bp.perm == p) {
5984                bp.perm = null;
5985                if (DEBUG_REMOVE && chatty) {
5986                    if (r == null) {
5987                        r = new StringBuilder(256);
5988                    } else {
5989                        r.append(' ');
5990                    }
5991                    r.append(p.info.name);
5992                }
5993            }
5994        }
5995        if (r != null) {
5996            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5997        }
5998
5999        N = pkg.instrumentation.size();
6000        r = null;
6001        for (i=0; i<N; i++) {
6002            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6003            mInstrumentation.remove(a.getComponentName());
6004            if (DEBUG_REMOVE && chatty) {
6005                if (r == null) {
6006                    r = new StringBuilder(256);
6007                } else {
6008                    r.append(' ');
6009                }
6010                r.append(a.info.name);
6011            }
6012        }
6013        if (r != null) {
6014            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6015        }
6016
6017        r = null;
6018        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6019            // Only system apps can hold shared libraries.
6020            if (pkg.libraryNames != null) {
6021                for (i=0; i<pkg.libraryNames.size(); i++) {
6022                    String name = pkg.libraryNames.get(i);
6023                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6024                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6025                        mSharedLibraries.remove(name);
6026                        if (DEBUG_REMOVE && chatty) {
6027                            if (r == null) {
6028                                r = new StringBuilder(256);
6029                            } else {
6030                                r.append(' ');
6031                            }
6032                            r.append(name);
6033                        }
6034                    }
6035                }
6036            }
6037        }
6038        if (r != null) {
6039            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6040        }
6041    }
6042
6043    private static final boolean isPackageFilename(String name) {
6044        return name != null && name.endsWith(".apk");
6045    }
6046
6047    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6048        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6049            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6050                return true;
6051            }
6052        }
6053        return false;
6054    }
6055
6056    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6057    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6058    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6059
6060    private void updatePermissionsLPw(String changingPkg,
6061            PackageParser.Package pkgInfo, int flags) {
6062        // Make sure there are no dangling permission trees.
6063        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6064        while (it.hasNext()) {
6065            final BasePermission bp = it.next();
6066            if (bp.packageSetting == null) {
6067                // We may not yet have parsed the package, so just see if
6068                // we still know about its settings.
6069                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6070            }
6071            if (bp.packageSetting == null) {
6072                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6073                        + " from package " + bp.sourcePackage);
6074                it.remove();
6075            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6076                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6077                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6078                            + " from package " + bp.sourcePackage);
6079                    flags |= UPDATE_PERMISSIONS_ALL;
6080                    it.remove();
6081                }
6082            }
6083        }
6084
6085        // Make sure all dynamic permissions have been assigned to a package,
6086        // and make sure there are no dangling permissions.
6087        it = mSettings.mPermissions.values().iterator();
6088        while (it.hasNext()) {
6089            final BasePermission bp = it.next();
6090            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6091                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6092                        + bp.name + " pkg=" + bp.sourcePackage
6093                        + " info=" + bp.pendingInfo);
6094                if (bp.packageSetting == null && bp.pendingInfo != null) {
6095                    final BasePermission tree = findPermissionTreeLP(bp.name);
6096                    if (tree != null && tree.perm != null) {
6097                        bp.packageSetting = tree.packageSetting;
6098                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6099                                new PermissionInfo(bp.pendingInfo));
6100                        bp.perm.info.packageName = tree.perm.info.packageName;
6101                        bp.perm.info.name = bp.name;
6102                        bp.uid = tree.uid;
6103                    }
6104                }
6105            }
6106            if (bp.packageSetting == null) {
6107                // We may not yet have parsed the package, so just see if
6108                // we still know about its settings.
6109                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6110            }
6111            if (bp.packageSetting == null) {
6112                Slog.w(TAG, "Removing dangling permission: " + bp.name
6113                        + " from package " + bp.sourcePackage);
6114                it.remove();
6115            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6116                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6117                    Slog.i(TAG, "Removing old permission: " + bp.name
6118                            + " from package " + bp.sourcePackage);
6119                    flags |= UPDATE_PERMISSIONS_ALL;
6120                    it.remove();
6121                }
6122            }
6123        }
6124
6125        // Now update the permissions for all packages, in particular
6126        // replace the granted permissions of the system packages.
6127        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6128            for (PackageParser.Package pkg : mPackages.values()) {
6129                if (pkg != pkgInfo) {
6130                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6131                }
6132            }
6133        }
6134
6135        if (pkgInfo != null) {
6136            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6137        }
6138    }
6139
6140    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6141        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6142        if (ps == null) {
6143            return;
6144        }
6145        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6146        HashSet<String> origPermissions = gp.grantedPermissions;
6147        boolean changedPermission = false;
6148
6149        if (replace) {
6150            ps.permissionsFixed = false;
6151            if (gp == ps) {
6152                origPermissions = new HashSet<String>(gp.grantedPermissions);
6153                gp.grantedPermissions.clear();
6154                gp.gids = mGlobalGids;
6155            }
6156        }
6157
6158        if (gp.gids == null) {
6159            gp.gids = mGlobalGids;
6160        }
6161
6162        final int N = pkg.requestedPermissions.size();
6163        for (int i=0; i<N; i++) {
6164            final String name = pkg.requestedPermissions.get(i);
6165            final boolean required = pkg.requestedPermissionsRequired.get(i);
6166            final BasePermission bp = mSettings.mPermissions.get(name);
6167            if (DEBUG_INSTALL) {
6168                if (gp != ps) {
6169                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6170                }
6171            }
6172
6173            if (bp == null || bp.packageSetting == null) {
6174                Slog.w(TAG, "Unknown permission " + name
6175                        + " in package " + pkg.packageName);
6176                continue;
6177            }
6178
6179            final String perm = bp.name;
6180            boolean allowed;
6181            boolean allowedSig = false;
6182            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6183            if (level == PermissionInfo.PROTECTION_NORMAL
6184                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6185                // We grant a normal or dangerous permission if any of the following
6186                // are true:
6187                // 1) The permission is required
6188                // 2) The permission is optional, but was granted in the past
6189                // 3) The permission is optional, but was requested by an
6190                //    app in /system (not /data)
6191                //
6192                // Otherwise, reject the permission.
6193                allowed = (required || origPermissions.contains(perm)
6194                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6195            } else if (bp.packageSetting == null) {
6196                // This permission is invalid; skip it.
6197                allowed = false;
6198            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6199                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6200                if (allowed) {
6201                    allowedSig = true;
6202                }
6203            } else {
6204                allowed = false;
6205            }
6206            if (DEBUG_INSTALL) {
6207                if (gp != ps) {
6208                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6209                }
6210            }
6211            if (allowed) {
6212                if (!isSystemApp(ps) && ps.permissionsFixed) {
6213                    // If this is an existing, non-system package, then
6214                    // we can't add any new permissions to it.
6215                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6216                        // Except...  if this is a permission that was added
6217                        // to the platform (note: need to only do this when
6218                        // updating the platform).
6219                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6220                    }
6221                }
6222                if (allowed) {
6223                    if (!gp.grantedPermissions.contains(perm)) {
6224                        changedPermission = true;
6225                        gp.grantedPermissions.add(perm);
6226                        gp.gids = appendInts(gp.gids, bp.gids);
6227                    } else if (!ps.haveGids) {
6228                        gp.gids = appendInts(gp.gids, bp.gids);
6229                    }
6230                } else {
6231                    Slog.w(TAG, "Not granting permission " + perm
6232                            + " to package " + pkg.packageName
6233                            + " because it was previously installed without");
6234                }
6235            } else {
6236                if (gp.grantedPermissions.remove(perm)) {
6237                    changedPermission = true;
6238                    gp.gids = removeInts(gp.gids, bp.gids);
6239                    Slog.i(TAG, "Un-granting permission " + perm
6240                            + " from package " + pkg.packageName
6241                            + " (protectionLevel=" + bp.protectionLevel
6242                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6243                            + ")");
6244                } else {
6245                    Slog.w(TAG, "Not granting permission " + perm
6246                            + " to package " + pkg.packageName
6247                            + " (protectionLevel=" + bp.protectionLevel
6248                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6249                            + ")");
6250                }
6251            }
6252        }
6253
6254        if ((changedPermission || replace) && !ps.permissionsFixed &&
6255                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6256            // This is the first that we have heard about this package, so the
6257            // permissions we have now selected are fixed until explicitly
6258            // changed.
6259            ps.permissionsFixed = true;
6260        }
6261        ps.haveGids = true;
6262    }
6263
6264    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6265        boolean allowed = false;
6266        final int NP = PackageParser.NEW_PERMISSIONS.length;
6267        for (int ip=0; ip<NP; ip++) {
6268            final PackageParser.NewPermissionInfo npi
6269                    = PackageParser.NEW_PERMISSIONS[ip];
6270            if (npi.name.equals(perm)
6271                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6272                allowed = true;
6273                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6274                        + pkg.packageName);
6275                break;
6276            }
6277        }
6278        return allowed;
6279    }
6280
6281    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6282                                          BasePermission bp, HashSet<String> origPermissions) {
6283        boolean allowed;
6284        allowed = (compareSignatures(
6285                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6286                        == PackageManager.SIGNATURE_MATCH)
6287                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6288                        == PackageManager.SIGNATURE_MATCH);
6289        if (!allowed && (bp.protectionLevel
6290                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6291            if (isSystemApp(pkg)) {
6292                // For updated system applications, a system permission
6293                // is granted only if it had been defined by the original application.
6294                if (isUpdatedSystemApp(pkg)) {
6295                    final PackageSetting sysPs = mSettings
6296                            .getDisabledSystemPkgLPr(pkg.packageName);
6297                    final GrantedPermissions origGp = sysPs.sharedUser != null
6298                            ? sysPs.sharedUser : sysPs;
6299
6300                    if (origGp.grantedPermissions.contains(perm)) {
6301                        // If the original was granted this permission, we take
6302                        // that grant decision as read and propagate it to the
6303                        // update.
6304                        allowed = true;
6305                    } else {
6306                        // The system apk may have been updated with an older
6307                        // version of the one on the data partition, but which
6308                        // granted a new system permission that it didn't have
6309                        // before.  In this case we do want to allow the app to
6310                        // now get the new permission if the ancestral apk is
6311                        // privileged to get it.
6312                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6313                            for (int j=0;
6314                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6315                                if (perm.equals(
6316                                        sysPs.pkg.requestedPermissions.get(j))) {
6317                                    allowed = true;
6318                                    break;
6319                                }
6320                            }
6321                        }
6322                    }
6323                } else {
6324                    allowed = isPrivilegedApp(pkg);
6325                }
6326            }
6327        }
6328        if (!allowed && (bp.protectionLevel
6329                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6330            // For development permissions, a development permission
6331            // is granted only if it was already granted.
6332            allowed = origPermissions.contains(perm);
6333        }
6334        return allowed;
6335    }
6336
6337    final class ActivityIntentResolver
6338            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6339        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6340                boolean defaultOnly, int userId) {
6341            if (!sUserManager.exists(userId)) return null;
6342            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6343            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6344        }
6345
6346        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6347                int userId) {
6348            if (!sUserManager.exists(userId)) return null;
6349            mFlags = flags;
6350            return super.queryIntent(intent, resolvedType,
6351                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6352        }
6353
6354        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6355                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6356            if (!sUserManager.exists(userId)) return null;
6357            if (packageActivities == null) {
6358                return null;
6359            }
6360            mFlags = flags;
6361            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6362            final int N = packageActivities.size();
6363            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6364                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6365
6366            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6367            for (int i = 0; i < N; ++i) {
6368                intentFilters = packageActivities.get(i).intents;
6369                if (intentFilters != null && intentFilters.size() > 0) {
6370                    PackageParser.ActivityIntentInfo[] array =
6371                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6372                    intentFilters.toArray(array);
6373                    listCut.add(array);
6374                }
6375            }
6376            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6377        }
6378
6379        public final void addActivity(PackageParser.Activity a, String type) {
6380            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6381            mActivities.put(a.getComponentName(), a);
6382            if (DEBUG_SHOW_INFO)
6383                Log.v(
6384                TAG, "  " + type + " " +
6385                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6386            if (DEBUG_SHOW_INFO)
6387                Log.v(TAG, "    Class=" + a.info.name);
6388            final int NI = a.intents.size();
6389            for (int j=0; j<NI; j++) {
6390                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6391                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6392                    intent.setPriority(0);
6393                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6394                            + a.className + " with priority > 0, forcing to 0");
6395                }
6396                if (DEBUG_SHOW_INFO) {
6397                    Log.v(TAG, "    IntentFilter:");
6398                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6399                }
6400                if (!intent.debugCheck()) {
6401                    Log.w(TAG, "==> For Activity " + a.info.name);
6402                }
6403                addFilter(intent);
6404            }
6405        }
6406
6407        public final void removeActivity(PackageParser.Activity a, String type) {
6408            mActivities.remove(a.getComponentName());
6409            if (DEBUG_SHOW_INFO) {
6410                Log.v(TAG, "  " + type + " "
6411                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6412                                : a.info.name) + ":");
6413                Log.v(TAG, "    Class=" + a.info.name);
6414            }
6415            final int NI = a.intents.size();
6416            for (int j=0; j<NI; j++) {
6417                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6418                if (DEBUG_SHOW_INFO) {
6419                    Log.v(TAG, "    IntentFilter:");
6420                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6421                }
6422                removeFilter(intent);
6423            }
6424        }
6425
6426        @Override
6427        protected boolean allowFilterResult(
6428                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6429            ActivityInfo filterAi = filter.activity.info;
6430            for (int i=dest.size()-1; i>=0; i--) {
6431                ActivityInfo destAi = dest.get(i).activityInfo;
6432                if (destAi.name == filterAi.name
6433                        && destAi.packageName == filterAi.packageName) {
6434                    return false;
6435                }
6436            }
6437            return true;
6438        }
6439
6440        @Override
6441        protected ActivityIntentInfo[] newArray(int size) {
6442            return new ActivityIntentInfo[size];
6443        }
6444
6445        @Override
6446        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6447            if (!sUserManager.exists(userId)) return true;
6448            PackageParser.Package p = filter.activity.owner;
6449            if (p != null) {
6450                PackageSetting ps = (PackageSetting)p.mExtras;
6451                if (ps != null) {
6452                    // System apps are never considered stopped for purposes of
6453                    // filtering, because there may be no way for the user to
6454                    // actually re-launch them.
6455                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6456                            && ps.getStopped(userId);
6457                }
6458            }
6459            return false;
6460        }
6461
6462        @Override
6463        protected boolean isPackageForFilter(String packageName,
6464                PackageParser.ActivityIntentInfo info) {
6465            return packageName.equals(info.activity.owner.packageName);
6466        }
6467
6468        @Override
6469        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6470                int match, int userId) {
6471            if (!sUserManager.exists(userId)) return null;
6472            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6473                return null;
6474            }
6475            final PackageParser.Activity activity = info.activity;
6476            if (mSafeMode && (activity.info.applicationInfo.flags
6477                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6478                return null;
6479            }
6480            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6481            if (ps == null) {
6482                return null;
6483            }
6484            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6485                    ps.readUserState(userId), userId);
6486            if (ai == null) {
6487                return null;
6488            }
6489            final ResolveInfo res = new ResolveInfo();
6490            res.activityInfo = ai;
6491            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6492                res.filter = info;
6493            }
6494            res.priority = info.getPriority();
6495            res.preferredOrder = activity.owner.mPreferredOrder;
6496            //System.out.println("Result: " + res.activityInfo.className +
6497            //                   " = " + res.priority);
6498            res.match = match;
6499            res.isDefault = info.hasDefault;
6500            res.labelRes = info.labelRes;
6501            res.nonLocalizedLabel = info.nonLocalizedLabel;
6502            res.icon = info.icon;
6503            res.system = isSystemApp(res.activityInfo.applicationInfo);
6504            return res;
6505        }
6506
6507        @Override
6508        protected void sortResults(List<ResolveInfo> results) {
6509            Collections.sort(results, mResolvePrioritySorter);
6510        }
6511
6512        @Override
6513        protected void dumpFilter(PrintWriter out, String prefix,
6514                PackageParser.ActivityIntentInfo filter) {
6515            out.print(prefix); out.print(
6516                    Integer.toHexString(System.identityHashCode(filter.activity)));
6517                    out.print(' ');
6518                    filter.activity.printComponentShortName(out);
6519                    out.print(" filter ");
6520                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6521        }
6522
6523//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6524//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6525//            final List<ResolveInfo> retList = Lists.newArrayList();
6526//            while (i.hasNext()) {
6527//                final ResolveInfo resolveInfo = i.next();
6528//                if (isEnabledLP(resolveInfo.activityInfo)) {
6529//                    retList.add(resolveInfo);
6530//                }
6531//            }
6532//            return retList;
6533//        }
6534
6535        // Keys are String (activity class name), values are Activity.
6536        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6537                = new HashMap<ComponentName, PackageParser.Activity>();
6538        private int mFlags;
6539    }
6540
6541    private final class ServiceIntentResolver
6542            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6543        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6544                boolean defaultOnly, int userId) {
6545            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6546            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6547        }
6548
6549        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6550                int userId) {
6551            if (!sUserManager.exists(userId)) return null;
6552            mFlags = flags;
6553            return super.queryIntent(intent, resolvedType,
6554                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6555        }
6556
6557        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6558                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6559            if (!sUserManager.exists(userId)) return null;
6560            if (packageServices == null) {
6561                return null;
6562            }
6563            mFlags = flags;
6564            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6565            final int N = packageServices.size();
6566            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6567                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6568
6569            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6570            for (int i = 0; i < N; ++i) {
6571                intentFilters = packageServices.get(i).intents;
6572                if (intentFilters != null && intentFilters.size() > 0) {
6573                    PackageParser.ServiceIntentInfo[] array =
6574                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6575                    intentFilters.toArray(array);
6576                    listCut.add(array);
6577                }
6578            }
6579            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6580        }
6581
6582        public final void addService(PackageParser.Service s) {
6583            mServices.put(s.getComponentName(), s);
6584            if (DEBUG_SHOW_INFO) {
6585                Log.v(TAG, "  "
6586                        + (s.info.nonLocalizedLabel != null
6587                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6588                Log.v(TAG, "    Class=" + s.info.name);
6589            }
6590            final int NI = s.intents.size();
6591            int j;
6592            for (j=0; j<NI; j++) {
6593                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6594                if (DEBUG_SHOW_INFO) {
6595                    Log.v(TAG, "    IntentFilter:");
6596                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6597                }
6598                if (!intent.debugCheck()) {
6599                    Log.w(TAG, "==> For Service " + s.info.name);
6600                }
6601                addFilter(intent);
6602            }
6603        }
6604
6605        public final void removeService(PackageParser.Service s) {
6606            mServices.remove(s.getComponentName());
6607            if (DEBUG_SHOW_INFO) {
6608                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6609                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6610                Log.v(TAG, "    Class=" + s.info.name);
6611            }
6612            final int NI = s.intents.size();
6613            int j;
6614            for (j=0; j<NI; j++) {
6615                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6616                if (DEBUG_SHOW_INFO) {
6617                    Log.v(TAG, "    IntentFilter:");
6618                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6619                }
6620                removeFilter(intent);
6621            }
6622        }
6623
6624        @Override
6625        protected boolean allowFilterResult(
6626                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6627            ServiceInfo filterSi = filter.service.info;
6628            for (int i=dest.size()-1; i>=0; i--) {
6629                ServiceInfo destAi = dest.get(i).serviceInfo;
6630                if (destAi.name == filterSi.name
6631                        && destAi.packageName == filterSi.packageName) {
6632                    return false;
6633                }
6634            }
6635            return true;
6636        }
6637
6638        @Override
6639        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6640            return new PackageParser.ServiceIntentInfo[size];
6641        }
6642
6643        @Override
6644        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6645            if (!sUserManager.exists(userId)) return true;
6646            PackageParser.Package p = filter.service.owner;
6647            if (p != null) {
6648                PackageSetting ps = (PackageSetting)p.mExtras;
6649                if (ps != null) {
6650                    // System apps are never considered stopped for purposes of
6651                    // filtering, because there may be no way for the user to
6652                    // actually re-launch them.
6653                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6654                            && ps.getStopped(userId);
6655                }
6656            }
6657            return false;
6658        }
6659
6660        @Override
6661        protected boolean isPackageForFilter(String packageName,
6662                PackageParser.ServiceIntentInfo info) {
6663            return packageName.equals(info.service.owner.packageName);
6664        }
6665
6666        @Override
6667        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6668                int match, int userId) {
6669            if (!sUserManager.exists(userId)) return null;
6670            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6671            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6672                return null;
6673            }
6674            final PackageParser.Service service = info.service;
6675            if (mSafeMode && (service.info.applicationInfo.flags
6676                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6677                return null;
6678            }
6679            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6680            if (ps == null) {
6681                return null;
6682            }
6683            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6684                    ps.readUserState(userId), userId);
6685            if (si == null) {
6686                return null;
6687            }
6688            final ResolveInfo res = new ResolveInfo();
6689            res.serviceInfo = si;
6690            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6691                res.filter = filter;
6692            }
6693            res.priority = info.getPriority();
6694            res.preferredOrder = service.owner.mPreferredOrder;
6695            //System.out.println("Result: " + res.activityInfo.className +
6696            //                   " = " + res.priority);
6697            res.match = match;
6698            res.isDefault = info.hasDefault;
6699            res.labelRes = info.labelRes;
6700            res.nonLocalizedLabel = info.nonLocalizedLabel;
6701            res.icon = info.icon;
6702            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6703            return res;
6704        }
6705
6706        @Override
6707        protected void sortResults(List<ResolveInfo> results) {
6708            Collections.sort(results, mResolvePrioritySorter);
6709        }
6710
6711        @Override
6712        protected void dumpFilter(PrintWriter out, String prefix,
6713                PackageParser.ServiceIntentInfo filter) {
6714            out.print(prefix); out.print(
6715                    Integer.toHexString(System.identityHashCode(filter.service)));
6716                    out.print(' ');
6717                    filter.service.printComponentShortName(out);
6718                    out.print(" filter ");
6719                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6720        }
6721
6722//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6723//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6724//            final List<ResolveInfo> retList = Lists.newArrayList();
6725//            while (i.hasNext()) {
6726//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6727//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6728//                    retList.add(resolveInfo);
6729//                }
6730//            }
6731//            return retList;
6732//        }
6733
6734        // Keys are String (activity class name), values are Activity.
6735        private final HashMap<ComponentName, PackageParser.Service> mServices
6736                = new HashMap<ComponentName, PackageParser.Service>();
6737        private int mFlags;
6738    };
6739
6740    private final class ProviderIntentResolver
6741            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6742        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6743                boolean defaultOnly, int userId) {
6744            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6745            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6746        }
6747
6748        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6749                int userId) {
6750            if (!sUserManager.exists(userId))
6751                return null;
6752            mFlags = flags;
6753            return super.queryIntent(intent, resolvedType,
6754                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6755        }
6756
6757        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6758                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6759            if (!sUserManager.exists(userId))
6760                return null;
6761            if (packageProviders == null) {
6762                return null;
6763            }
6764            mFlags = flags;
6765            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6766            final int N = packageProviders.size();
6767            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6768                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6769
6770            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6771            for (int i = 0; i < N; ++i) {
6772                intentFilters = packageProviders.get(i).intents;
6773                if (intentFilters != null && intentFilters.size() > 0) {
6774                    PackageParser.ProviderIntentInfo[] array =
6775                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6776                    intentFilters.toArray(array);
6777                    listCut.add(array);
6778                }
6779            }
6780            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6781        }
6782
6783        public final void addProvider(PackageParser.Provider p) {
6784            mProviders.put(p.getComponentName(), p);
6785            if (DEBUG_SHOW_INFO) {
6786                Log.v(TAG, "  "
6787                        + (p.info.nonLocalizedLabel != null
6788                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6789                Log.v(TAG, "    Class=" + p.info.name);
6790            }
6791            final int NI = p.intents.size();
6792            int j;
6793            for (j = 0; j < NI; j++) {
6794                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6795                if (DEBUG_SHOW_INFO) {
6796                    Log.v(TAG, "    IntentFilter:");
6797                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6798                }
6799                if (!intent.debugCheck()) {
6800                    Log.w(TAG, "==> For Provider " + p.info.name);
6801                }
6802                addFilter(intent);
6803            }
6804        }
6805
6806        public final void removeProvider(PackageParser.Provider p) {
6807            mProviders.remove(p.getComponentName());
6808            if (DEBUG_SHOW_INFO) {
6809                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6810                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6811                Log.v(TAG, "    Class=" + p.info.name);
6812            }
6813            final int NI = p.intents.size();
6814            int j;
6815            for (j = 0; j < NI; j++) {
6816                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6817                if (DEBUG_SHOW_INFO) {
6818                    Log.v(TAG, "    IntentFilter:");
6819                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6820                }
6821                removeFilter(intent);
6822            }
6823        }
6824
6825        @Override
6826        protected boolean allowFilterResult(
6827                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6828            ProviderInfo filterPi = filter.provider.info;
6829            for (int i = dest.size() - 1; i >= 0; i--) {
6830                ProviderInfo destPi = dest.get(i).providerInfo;
6831                if (destPi.name == filterPi.name
6832                        && destPi.packageName == filterPi.packageName) {
6833                    return false;
6834                }
6835            }
6836            return true;
6837        }
6838
6839        @Override
6840        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6841            return new PackageParser.ProviderIntentInfo[size];
6842        }
6843
6844        @Override
6845        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6846            if (!sUserManager.exists(userId))
6847                return true;
6848            PackageParser.Package p = filter.provider.owner;
6849            if (p != null) {
6850                PackageSetting ps = (PackageSetting) p.mExtras;
6851                if (ps != null) {
6852                    // System apps are never considered stopped for purposes of
6853                    // filtering, because there may be no way for the user to
6854                    // actually re-launch them.
6855                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6856                            && ps.getStopped(userId);
6857                }
6858            }
6859            return false;
6860        }
6861
6862        @Override
6863        protected boolean isPackageForFilter(String packageName,
6864                PackageParser.ProviderIntentInfo info) {
6865            return packageName.equals(info.provider.owner.packageName);
6866        }
6867
6868        @Override
6869        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6870                int match, int userId) {
6871            if (!sUserManager.exists(userId))
6872                return null;
6873            final PackageParser.ProviderIntentInfo info = filter;
6874            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6875                return null;
6876            }
6877            final PackageParser.Provider provider = info.provider;
6878            if (mSafeMode && (provider.info.applicationInfo.flags
6879                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6880                return null;
6881            }
6882            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6883            if (ps == null) {
6884                return null;
6885            }
6886            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6887                    ps.readUserState(userId), userId);
6888            if (pi == null) {
6889                return null;
6890            }
6891            final ResolveInfo res = new ResolveInfo();
6892            res.providerInfo = pi;
6893            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6894                res.filter = filter;
6895            }
6896            res.priority = info.getPriority();
6897            res.preferredOrder = provider.owner.mPreferredOrder;
6898            res.match = match;
6899            res.isDefault = info.hasDefault;
6900            res.labelRes = info.labelRes;
6901            res.nonLocalizedLabel = info.nonLocalizedLabel;
6902            res.icon = info.icon;
6903            res.system = isSystemApp(res.providerInfo.applicationInfo);
6904            return res;
6905        }
6906
6907        @Override
6908        protected void sortResults(List<ResolveInfo> results) {
6909            Collections.sort(results, mResolvePrioritySorter);
6910        }
6911
6912        @Override
6913        protected void dumpFilter(PrintWriter out, String prefix,
6914                PackageParser.ProviderIntentInfo filter) {
6915            out.print(prefix);
6916            out.print(
6917                    Integer.toHexString(System.identityHashCode(filter.provider)));
6918            out.print(' ');
6919            filter.provider.printComponentShortName(out);
6920            out.print(" filter ");
6921            out.println(Integer.toHexString(System.identityHashCode(filter)));
6922        }
6923
6924        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6925                = new HashMap<ComponentName, PackageParser.Provider>();
6926        private int mFlags;
6927    };
6928
6929    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6930            new Comparator<ResolveInfo>() {
6931        public int compare(ResolveInfo r1, ResolveInfo r2) {
6932            int v1 = r1.priority;
6933            int v2 = r2.priority;
6934            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6935            if (v1 != v2) {
6936                return (v1 > v2) ? -1 : 1;
6937            }
6938            v1 = r1.preferredOrder;
6939            v2 = r2.preferredOrder;
6940            if (v1 != v2) {
6941                return (v1 > v2) ? -1 : 1;
6942            }
6943            if (r1.isDefault != r2.isDefault) {
6944                return r1.isDefault ? -1 : 1;
6945            }
6946            v1 = r1.match;
6947            v2 = r2.match;
6948            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6949            if (v1 != v2) {
6950                return (v1 > v2) ? -1 : 1;
6951            }
6952            if (r1.system != r2.system) {
6953                return r1.system ? -1 : 1;
6954            }
6955            return 0;
6956        }
6957    };
6958
6959    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6960            new Comparator<ProviderInfo>() {
6961        public int compare(ProviderInfo p1, ProviderInfo p2) {
6962            final int v1 = p1.initOrder;
6963            final int v2 = p2.initOrder;
6964            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6965        }
6966    };
6967
6968    static final void sendPackageBroadcast(String action, String pkg,
6969            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6970            int[] userIds) {
6971        IActivityManager am = ActivityManagerNative.getDefault();
6972        if (am != null) {
6973            try {
6974                if (userIds == null) {
6975                    userIds = am.getRunningUserIds();
6976                }
6977                for (int id : userIds) {
6978                    final Intent intent = new Intent(action,
6979                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6980                    if (extras != null) {
6981                        intent.putExtras(extras);
6982                    }
6983                    if (targetPkg != null) {
6984                        intent.setPackage(targetPkg);
6985                    }
6986                    // Modify the UID when posting to other users
6987                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6988                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6989                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6990                        intent.putExtra(Intent.EXTRA_UID, uid);
6991                    }
6992                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6993                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6994                    if (DEBUG_BROADCASTS) {
6995                        RuntimeException here = new RuntimeException("here");
6996                        here.fillInStackTrace();
6997                        Slog.d(TAG, "Sending to user " + id + ": "
6998                                + intent.toShortString(false, true, false, false)
6999                                + " " + intent.getExtras(), here);
7000                    }
7001                    am.broadcastIntent(null, intent, null, finishedReceiver,
7002                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7003                            finishedReceiver != null, false, id);
7004                }
7005            } catch (RemoteException ex) {
7006            }
7007        }
7008    }
7009
7010    /**
7011     * Check if the external storage media is available. This is true if there
7012     * is a mounted external storage medium or if the external storage is
7013     * emulated.
7014     */
7015    private boolean isExternalMediaAvailable() {
7016        return mMediaMounted || Environment.isExternalStorageEmulated();
7017    }
7018
7019    @Override
7020    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7021        // writer
7022        synchronized (mPackages) {
7023            if (!isExternalMediaAvailable()) {
7024                // If the external storage is no longer mounted at this point,
7025                // the caller may not have been able to delete all of this
7026                // packages files and can not delete any more.  Bail.
7027                return null;
7028            }
7029            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7030            if (lastPackage != null) {
7031                pkgs.remove(lastPackage);
7032            }
7033            if (pkgs.size() > 0) {
7034                return pkgs.get(0);
7035            }
7036        }
7037        return null;
7038    }
7039
7040    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7041        if (false) {
7042            RuntimeException here = new RuntimeException("here");
7043            here.fillInStackTrace();
7044            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7045                    + " andCode=" + andCode, here);
7046        }
7047        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7048                userId, andCode ? 1 : 0, packageName));
7049    }
7050
7051    void startCleaningPackages() {
7052        // reader
7053        synchronized (mPackages) {
7054            if (!isExternalMediaAvailable()) {
7055                return;
7056            }
7057            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7058                return;
7059            }
7060        }
7061        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7062        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7063        IActivityManager am = ActivityManagerNative.getDefault();
7064        if (am != null) {
7065            try {
7066                am.startService(null, intent, null, UserHandle.USER_OWNER);
7067            } catch (RemoteException e) {
7068            }
7069        }
7070    }
7071
7072    private final class AppDirObserver extends FileObserver {
7073        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7074            super(path, mask);
7075            mRootDir = path;
7076            mIsRom = isrom;
7077            mIsPrivileged = isPrivileged;
7078        }
7079
7080        public void onEvent(int event, String path) {
7081            String removedPackage = null;
7082            int removedAppId = -1;
7083            int[] removedUsers = null;
7084            String addedPackage = null;
7085            int addedAppId = -1;
7086            int[] addedUsers = null;
7087
7088            // TODO post a message to the handler to obtain serial ordering
7089            synchronized (mInstallLock) {
7090                String fullPathStr = null;
7091                File fullPath = null;
7092                if (path != null) {
7093                    fullPath = new File(mRootDir, path);
7094                    fullPathStr = fullPath.getPath();
7095                }
7096
7097                if (DEBUG_APP_DIR_OBSERVER)
7098                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7099
7100                if (!isPackageFilename(path)) {
7101                    if (DEBUG_APP_DIR_OBSERVER)
7102                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7103                    return;
7104                }
7105
7106                // Ignore packages that are being installed or
7107                // have just been installed.
7108                if (ignoreCodePath(fullPathStr)) {
7109                    return;
7110                }
7111                PackageParser.Package p = null;
7112                PackageSetting ps = null;
7113                // reader
7114                synchronized (mPackages) {
7115                    p = mAppDirs.get(fullPathStr);
7116                    if (p != null) {
7117                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7118                        if (ps != null) {
7119                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7120                        } else {
7121                            removedUsers = sUserManager.getUserIds();
7122                        }
7123                    }
7124                    addedUsers = sUserManager.getUserIds();
7125                }
7126                if ((event&REMOVE_EVENTS) != 0) {
7127                    if (ps != null) {
7128                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7129                        removePackageLI(ps, true);
7130                        removedPackage = ps.name;
7131                        removedAppId = ps.appId;
7132                    }
7133                }
7134
7135                if ((event&ADD_EVENTS) != 0) {
7136                    if (p == null) {
7137                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7138                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7139                        if (mIsRom) {
7140                            flags |= PackageParser.PARSE_IS_SYSTEM
7141                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7142                            if (mIsPrivileged) {
7143                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7144                            }
7145                        }
7146                        p = scanPackageLI(fullPath, flags,
7147                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7148                                System.currentTimeMillis(), UserHandle.ALL);
7149                        if (p != null) {
7150                            /*
7151                             * TODO this seems dangerous as the package may have
7152                             * changed since we last acquired the mPackages
7153                             * lock.
7154                             */
7155                            // writer
7156                            synchronized (mPackages) {
7157                                updatePermissionsLPw(p.packageName, p,
7158                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7159                            }
7160                            addedPackage = p.applicationInfo.packageName;
7161                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7162                        }
7163                    }
7164                }
7165
7166                // reader
7167                synchronized (mPackages) {
7168                    mSettings.writeLPr();
7169                }
7170            }
7171
7172            if (removedPackage != null) {
7173                Bundle extras = new Bundle(1);
7174                extras.putInt(Intent.EXTRA_UID, removedAppId);
7175                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7176                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7177                        extras, null, null, removedUsers);
7178            }
7179            if (addedPackage != null) {
7180                Bundle extras = new Bundle(1);
7181                extras.putInt(Intent.EXTRA_UID, addedAppId);
7182                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7183                        extras, null, null, addedUsers);
7184            }
7185        }
7186
7187        private final String mRootDir;
7188        private final boolean mIsRom;
7189        private final boolean mIsPrivileged;
7190    }
7191
7192    /* Called when a downloaded package installation has been confirmed by the user */
7193    public void installPackage(
7194            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7195        installPackage(packageURI, observer, flags, null);
7196    }
7197
7198    /* Called when a downloaded package installation has been confirmed by the user */
7199    @Override
7200    public void installPackage(
7201            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7202            final String installerPackageName) {
7203        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
7204                null, null);
7205    }
7206
7207    @Override
7208    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7209            int flags, String installerPackageName, Uri verificationURI,
7210            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7211        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7212                VerificationParams.NO_UID, manifestDigest);
7213        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
7214                installerPackageName, verificationParams, encryptionParams);
7215    }
7216
7217    @Override
7218    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7219            IPackageInstallObserver observer, int flags, String installerPackageName,
7220            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7221        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7222                null);
7223
7224        final int uid = Binder.getCallingUid();
7225        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7226            try {
7227                observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7228            } catch (RemoteException re) {
7229            }
7230            return;
7231        }
7232
7233        UserHandle user;
7234        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7235            user = UserHandle.ALL;
7236        } else {
7237            user = new UserHandle(UserHandle.getUserId(uid));
7238        }
7239
7240        final int filteredFlags;
7241
7242        if (uid == Process.SHELL_UID || uid == 0) {
7243            if (DEBUG_INSTALL) {
7244                Slog.v(TAG, "Install from ADB");
7245            }
7246            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7247        } else {
7248            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7249        }
7250
7251        verificationParams.setInstallerUid(uid);
7252
7253        final Message msg = mHandler.obtainMessage(INIT_COPY);
7254        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
7255                verificationParams, encryptionParams, user);
7256        mHandler.sendMessage(msg);
7257    }
7258
7259    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7260        Bundle extras = new Bundle(1);
7261        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7262
7263        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7264                packageName, extras, null, null, new int[] {userId});
7265        try {
7266            IActivityManager am = ActivityManagerNative.getDefault();
7267            final boolean isSystem =
7268                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7269            if (isSystem && am.isUserRunning(userId, false)) {
7270                // The just-installed/enabled app is bundled on the system, so presumed
7271                // to be able to run automatically without needing an explicit launch.
7272                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7273                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7274                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7275                        .setPackage(packageName);
7276                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7277                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7278            }
7279        } catch (RemoteException e) {
7280            // shouldn't happen
7281            Slog.w(TAG, "Unable to bootstrap installed package", e);
7282        }
7283    }
7284
7285    @Override
7286    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7287            int userId) {
7288        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7289        PackageSetting pkgSetting;
7290        final int uid = Binder.getCallingUid();
7291        if (UserHandle.getUserId(uid) != userId) {
7292            mContext.enforceCallingOrSelfPermission(
7293                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7294                    "setApplicationBlockedSetting for user " + userId);
7295        }
7296
7297        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7298            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7299            return false;
7300        }
7301
7302        long callingId = Binder.clearCallingIdentity();
7303        try {
7304            boolean sendAdded = false;
7305            boolean sendRemoved = false;
7306            // writer
7307            synchronized (mPackages) {
7308                pkgSetting = mSettings.mPackages.get(packageName);
7309                if (pkgSetting == null) {
7310                    return false;
7311                }
7312                if (pkgSetting.getBlocked(userId) != blocked) {
7313                    pkgSetting.setBlocked(blocked, userId);
7314                    mSettings.writePackageRestrictionsLPr(userId);
7315                    if (blocked) {
7316                        sendRemoved = true;
7317                    } else {
7318                        sendAdded = true;
7319                    }
7320                }
7321            }
7322            if (sendAdded) {
7323                sendPackageAddedForUser(packageName, pkgSetting, userId);
7324                return true;
7325            }
7326            if (sendRemoved) {
7327                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7328                        "blocking pkg");
7329                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7330            }
7331        } finally {
7332            Binder.restoreCallingIdentity(callingId);
7333        }
7334        return false;
7335    }
7336
7337    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7338            int userId) {
7339        final PackageRemovedInfo info = new PackageRemovedInfo();
7340        info.removedPackage = packageName;
7341        info.removedUsers = new int[] {userId};
7342        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7343        info.sendBroadcast(false, false, false);
7344    }
7345
7346    /**
7347     * Returns true if application is not found or there was an error. Otherwise it returns
7348     * the blocked state of the package for the given user.
7349     */
7350    @Override
7351    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7352        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7353        PackageSetting pkgSetting;
7354        final int uid = Binder.getCallingUid();
7355        if (UserHandle.getUserId(uid) != userId) {
7356            mContext.enforceCallingPermission(
7357                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7358                    "getApplicationBlocked for user " + userId);
7359        }
7360        long callingId = Binder.clearCallingIdentity();
7361        try {
7362            // writer
7363            synchronized (mPackages) {
7364                pkgSetting = mSettings.mPackages.get(packageName);
7365                if (pkgSetting == null) {
7366                    return true;
7367                }
7368                return pkgSetting.getBlocked(userId);
7369            }
7370        } finally {
7371            Binder.restoreCallingIdentity(callingId);
7372        }
7373    }
7374
7375    /**
7376     * @hide
7377     */
7378    @Override
7379    public int installExistingPackageAsUser(String packageName, int userId) {
7380        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7381                null);
7382        PackageSetting pkgSetting;
7383        final int uid = Binder.getCallingUid();
7384        if (UserHandle.getUserId(uid) != userId) {
7385            mContext.enforceCallingPermission(
7386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7387                    "installExistingPackage for user " + userId);
7388        }
7389        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7390            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7391        }
7392
7393        long callingId = Binder.clearCallingIdentity();
7394        try {
7395            boolean sendAdded = false;
7396            Bundle extras = new Bundle(1);
7397
7398            // writer
7399            synchronized (mPackages) {
7400                pkgSetting = mSettings.mPackages.get(packageName);
7401                if (pkgSetting == null) {
7402                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7403                }
7404                if (!pkgSetting.getInstalled(userId)) {
7405                    pkgSetting.setInstalled(true, userId);
7406                    pkgSetting.setBlocked(false, userId);
7407                    mSettings.writePackageRestrictionsLPr(userId);
7408                    sendAdded = true;
7409                }
7410            }
7411
7412            if (sendAdded) {
7413                sendPackageAddedForUser(packageName, pkgSetting, userId);
7414            }
7415        } finally {
7416            Binder.restoreCallingIdentity(callingId);
7417        }
7418
7419        return PackageManager.INSTALL_SUCCEEDED;
7420    }
7421
7422    private boolean isUserRestricted(int userId, String restrictionKey) {
7423        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7424        if (restrictions.getBoolean(restrictionKey, false)) {
7425            Log.w(TAG, "User is restricted: " + restrictionKey);
7426            return true;
7427        }
7428        return false;
7429    }
7430
7431    @Override
7432    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7433        mContext.enforceCallingOrSelfPermission(
7434                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7435                "Only package verification agents can verify applications");
7436
7437        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7438        final PackageVerificationResponse response = new PackageVerificationResponse(
7439                verificationCode, Binder.getCallingUid());
7440        msg.arg1 = id;
7441        msg.obj = response;
7442        mHandler.sendMessage(msg);
7443    }
7444
7445    @Override
7446    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7447            long millisecondsToDelay) {
7448        mContext.enforceCallingOrSelfPermission(
7449                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7450                "Only package verification agents can extend verification timeouts");
7451
7452        final PackageVerificationState state = mPendingVerification.get(id);
7453        final PackageVerificationResponse response = new PackageVerificationResponse(
7454                verificationCodeAtTimeout, Binder.getCallingUid());
7455
7456        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7457            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7458        }
7459        if (millisecondsToDelay < 0) {
7460            millisecondsToDelay = 0;
7461        }
7462        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7463                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7464            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7465        }
7466
7467        if ((state != null) && !state.timeoutExtended()) {
7468            state.extendTimeout();
7469
7470            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7471            msg.arg1 = id;
7472            msg.obj = response;
7473            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7474        }
7475    }
7476
7477    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7478            int verificationCode, UserHandle user) {
7479        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7480        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7481        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7482        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7483        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7484
7485        mContext.sendBroadcastAsUser(intent, user,
7486                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7487    }
7488
7489    private ComponentName matchComponentForVerifier(String packageName,
7490            List<ResolveInfo> receivers) {
7491        ActivityInfo targetReceiver = null;
7492
7493        final int NR = receivers.size();
7494        for (int i = 0; i < NR; i++) {
7495            final ResolveInfo info = receivers.get(i);
7496            if (info.activityInfo == null) {
7497                continue;
7498            }
7499
7500            if (packageName.equals(info.activityInfo.packageName)) {
7501                targetReceiver = info.activityInfo;
7502                break;
7503            }
7504        }
7505
7506        if (targetReceiver == null) {
7507            return null;
7508        }
7509
7510        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7511    }
7512
7513    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7514            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7515        if (pkgInfo.verifiers.length == 0) {
7516            return null;
7517        }
7518
7519        final int N = pkgInfo.verifiers.length;
7520        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7521        for (int i = 0; i < N; i++) {
7522            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7523
7524            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7525                    receivers);
7526            if (comp == null) {
7527                continue;
7528            }
7529
7530            final int verifierUid = getUidForVerifier(verifierInfo);
7531            if (verifierUid == -1) {
7532                continue;
7533            }
7534
7535            if (DEBUG_VERIFY) {
7536                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7537                        + " with the correct signature");
7538            }
7539            sufficientVerifiers.add(comp);
7540            verificationState.addSufficientVerifier(verifierUid);
7541        }
7542
7543        return sufficientVerifiers;
7544    }
7545
7546    private int getUidForVerifier(VerifierInfo verifierInfo) {
7547        synchronized (mPackages) {
7548            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7549            if (pkg == null) {
7550                return -1;
7551            } else if (pkg.mSignatures.length != 1) {
7552                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7553                        + " has more than one signature; ignoring");
7554                return -1;
7555            }
7556
7557            /*
7558             * If the public key of the package's signature does not match
7559             * our expected public key, then this is a different package and
7560             * we should skip.
7561             */
7562
7563            final byte[] expectedPublicKey;
7564            try {
7565                final Signature verifierSig = pkg.mSignatures[0];
7566                final PublicKey publicKey = verifierSig.getPublicKey();
7567                expectedPublicKey = publicKey.getEncoded();
7568            } catch (CertificateException e) {
7569                return -1;
7570            }
7571
7572            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7573
7574            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7575                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7576                        + " does not have the expected public key; ignoring");
7577                return -1;
7578            }
7579
7580            return pkg.applicationInfo.uid;
7581        }
7582    }
7583
7584    @Override
7585    public void finishPackageInstall(int token) {
7586        enforceSystemOrRoot("Only the system is allowed to finish installs");
7587
7588        if (DEBUG_INSTALL) {
7589            Slog.v(TAG, "BM finishing package install for " + token);
7590        }
7591
7592        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7593        mHandler.sendMessage(msg);
7594    }
7595
7596    /**
7597     * Get the verification agent timeout.
7598     *
7599     * @return verification timeout in milliseconds
7600     */
7601    private long getVerificationTimeout() {
7602        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7603                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7604                DEFAULT_VERIFICATION_TIMEOUT);
7605    }
7606
7607    /**
7608     * Get the default verification agent response code.
7609     *
7610     * @return default verification response code
7611     */
7612    private int getDefaultVerificationResponse() {
7613        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7614                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7615                DEFAULT_VERIFICATION_RESPONSE);
7616    }
7617
7618    /**
7619     * Check whether or not package verification has been enabled.
7620     *
7621     * @return true if verification should be performed
7622     */
7623    private boolean isVerificationEnabled(int flags) {
7624        if (!DEFAULT_VERIFY_ENABLE) {
7625            return false;
7626        }
7627
7628        // Check if installing from ADB
7629        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7630            // Do not run verification in a test harness environment
7631            if (ActivityManager.isRunningInTestHarness()) {
7632                return false;
7633            }
7634            // Check if the developer does not want package verification for ADB installs
7635            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7636                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7637                return false;
7638            }
7639        }
7640
7641        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7642                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7643    }
7644
7645    /**
7646     * Get the "allow unknown sources" setting.
7647     *
7648     * @return the current "allow unknown sources" setting
7649     */
7650    private int getUnknownSourcesSettings() {
7651        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7652                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7653                -1);
7654    }
7655
7656    @Override
7657    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7658        final int uid = Binder.getCallingUid();
7659        // writer
7660        synchronized (mPackages) {
7661            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7662            if (targetPackageSetting == null) {
7663                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7664            }
7665
7666            PackageSetting installerPackageSetting;
7667            if (installerPackageName != null) {
7668                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7669                if (installerPackageSetting == null) {
7670                    throw new IllegalArgumentException("Unknown installer package: "
7671                            + installerPackageName);
7672                }
7673            } else {
7674                installerPackageSetting = null;
7675            }
7676
7677            Signature[] callerSignature;
7678            Object obj = mSettings.getUserIdLPr(uid);
7679            if (obj != null) {
7680                if (obj instanceof SharedUserSetting) {
7681                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7682                } else if (obj instanceof PackageSetting) {
7683                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7684                } else {
7685                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7686                }
7687            } else {
7688                throw new SecurityException("Unknown calling uid " + uid);
7689            }
7690
7691            // Verify: can't set installerPackageName to a package that is
7692            // not signed with the same cert as the caller.
7693            if (installerPackageSetting != null) {
7694                if (compareSignatures(callerSignature,
7695                        installerPackageSetting.signatures.mSignatures)
7696                        != PackageManager.SIGNATURE_MATCH) {
7697                    throw new SecurityException(
7698                            "Caller does not have same cert as new installer package "
7699                            + installerPackageName);
7700                }
7701            }
7702
7703            // Verify: if target already has an installer package, it must
7704            // be signed with the same cert as the caller.
7705            if (targetPackageSetting.installerPackageName != null) {
7706                PackageSetting setting = mSettings.mPackages.get(
7707                        targetPackageSetting.installerPackageName);
7708                // If the currently set package isn't valid, then it's always
7709                // okay to change it.
7710                if (setting != null) {
7711                    if (compareSignatures(callerSignature,
7712                            setting.signatures.mSignatures)
7713                            != PackageManager.SIGNATURE_MATCH) {
7714                        throw new SecurityException(
7715                                "Caller does not have same cert as old installer package "
7716                                + targetPackageSetting.installerPackageName);
7717                    }
7718                }
7719            }
7720
7721            // Okay!
7722            targetPackageSetting.installerPackageName = installerPackageName;
7723            scheduleWriteSettingsLocked();
7724        }
7725    }
7726
7727    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7728        // Queue up an async operation since the package installation may take a little while.
7729        mHandler.post(new Runnable() {
7730            public void run() {
7731                mHandler.removeCallbacks(this);
7732                 // Result object to be returned
7733                PackageInstalledInfo res = new PackageInstalledInfo();
7734                res.returnCode = currentStatus;
7735                res.uid = -1;
7736                res.pkg = null;
7737                res.removedInfo = new PackageRemovedInfo();
7738                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7739                    args.doPreInstall(res.returnCode);
7740                    synchronized (mInstallLock) {
7741                        installPackageLI(args, true, res);
7742                    }
7743                    args.doPostInstall(res.returnCode, res.uid);
7744                }
7745
7746                // A restore should be performed at this point if (a) the install
7747                // succeeded, (b) the operation is not an update, and (c) the new
7748                // package has a backupAgent defined.
7749                final boolean update = res.removedInfo.removedPackage != null;
7750                boolean doRestore = (!update
7751                        && res.pkg != null
7752                        && res.pkg.applicationInfo.backupAgentName != null);
7753
7754                // Set up the post-install work request bookkeeping.  This will be used
7755                // and cleaned up by the post-install event handling regardless of whether
7756                // there's a restore pass performed.  Token values are >= 1.
7757                int token;
7758                if (mNextInstallToken < 0) mNextInstallToken = 1;
7759                token = mNextInstallToken++;
7760
7761                PostInstallData data = new PostInstallData(args, res);
7762                mRunningInstalls.put(token, data);
7763                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7764
7765                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7766                    // Pass responsibility to the Backup Manager.  It will perform a
7767                    // restore if appropriate, then pass responsibility back to the
7768                    // Package Manager to run the post-install observer callbacks
7769                    // and broadcasts.
7770                    IBackupManager bm = IBackupManager.Stub.asInterface(
7771                            ServiceManager.getService(Context.BACKUP_SERVICE));
7772                    if (bm != null) {
7773                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7774                                + " to BM for possible restore");
7775                        try {
7776                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7777                        } catch (RemoteException e) {
7778                            // can't happen; the backup manager is local
7779                        } catch (Exception e) {
7780                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7781                            doRestore = false;
7782                        }
7783                    } else {
7784                        Slog.e(TAG, "Backup Manager not found!");
7785                        doRestore = false;
7786                    }
7787                }
7788
7789                if (!doRestore) {
7790                    // No restore possible, or the Backup Manager was mysteriously not
7791                    // available -- just fire the post-install work request directly.
7792                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7793                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7794                    mHandler.sendMessage(msg);
7795                }
7796            }
7797        });
7798    }
7799
7800    private abstract class HandlerParams {
7801        private static final int MAX_RETRIES = 4;
7802
7803        /**
7804         * Number of times startCopy() has been attempted and had a non-fatal
7805         * error.
7806         */
7807        private int mRetries = 0;
7808
7809        /** User handle for the user requesting the information or installation. */
7810        private final UserHandle mUser;
7811
7812        HandlerParams(UserHandle user) {
7813            mUser = user;
7814        }
7815
7816        UserHandle getUser() {
7817            return mUser;
7818        }
7819
7820        final boolean startCopy() {
7821            boolean res;
7822            try {
7823                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7824
7825                if (++mRetries > MAX_RETRIES) {
7826                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7827                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7828                    handleServiceError();
7829                    return false;
7830                } else {
7831                    handleStartCopy();
7832                    res = true;
7833                }
7834            } catch (RemoteException e) {
7835                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7836                mHandler.sendEmptyMessage(MCS_RECONNECT);
7837                res = false;
7838            }
7839            handleReturnCode();
7840            return res;
7841        }
7842
7843        final void serviceError() {
7844            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7845            handleServiceError();
7846            handleReturnCode();
7847        }
7848
7849        abstract void handleStartCopy() throws RemoteException;
7850        abstract void handleServiceError();
7851        abstract void handleReturnCode();
7852    }
7853
7854    class MeasureParams extends HandlerParams {
7855        private final PackageStats mStats;
7856        private boolean mSuccess;
7857
7858        private final IPackageStatsObserver mObserver;
7859
7860        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7861            super(new UserHandle(stats.userHandle));
7862            mObserver = observer;
7863            mStats = stats;
7864        }
7865
7866        @Override
7867        public String toString() {
7868            return "MeasureParams{"
7869                + Integer.toHexString(System.identityHashCode(this))
7870                + " " + mStats.packageName + "}";
7871        }
7872
7873        @Override
7874        void handleStartCopy() throws RemoteException {
7875            synchronized (mInstallLock) {
7876                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7877            }
7878
7879            final boolean mounted;
7880            if (Environment.isExternalStorageEmulated()) {
7881                mounted = true;
7882            } else {
7883                final String status = Environment.getExternalStorageState();
7884                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7885                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7886            }
7887
7888            if (mounted) {
7889                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7890
7891                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7892                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7893
7894                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7895                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7896
7897                // Always subtract cache size, since it's a subdirectory
7898                mStats.externalDataSize -= mStats.externalCacheSize;
7899
7900                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7901                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7902
7903                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7904                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7905            }
7906        }
7907
7908        @Override
7909        void handleReturnCode() {
7910            if (mObserver != null) {
7911                try {
7912                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7913                } catch (RemoteException e) {
7914                    Slog.i(TAG, "Observer no longer exists.");
7915                }
7916            }
7917        }
7918
7919        @Override
7920        void handleServiceError() {
7921            Slog.e(TAG, "Could not measure application " + mStats.packageName
7922                            + " external storage");
7923        }
7924    }
7925
7926    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7927            throws RemoteException {
7928        long result = 0;
7929        for (File path : paths) {
7930            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7931        }
7932        return result;
7933    }
7934
7935    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7936        for (File path : paths) {
7937            try {
7938                mcs.clearDirectory(path.getAbsolutePath());
7939            } catch (RemoteException e) {
7940            }
7941        }
7942    }
7943
7944    class InstallParams extends HandlerParams {
7945        final IPackageInstallObserver observer;
7946        int flags;
7947
7948        private final Uri mPackageURI;
7949        final String installerPackageName;
7950        final VerificationParams verificationParams;
7951        private InstallArgs mArgs;
7952        private int mRet;
7953        private File mTempPackage;
7954        final ContainerEncryptionParams encryptionParams;
7955
7956        InstallParams(Uri packageURI,
7957                IPackageInstallObserver observer, int flags,
7958                String installerPackageName, VerificationParams verificationParams,
7959                ContainerEncryptionParams encryptionParams, UserHandle user) {
7960            super(user);
7961            this.mPackageURI = packageURI;
7962            this.flags = flags;
7963            this.observer = observer;
7964            this.installerPackageName = installerPackageName;
7965            this.verificationParams = verificationParams;
7966            this.encryptionParams = encryptionParams;
7967        }
7968
7969        @Override
7970        public String toString() {
7971            return "InstallParams{"
7972                + Integer.toHexString(System.identityHashCode(this))
7973                + " " + mPackageURI + "}";
7974        }
7975
7976        public ManifestDigest getManifestDigest() {
7977            if (verificationParams == null) {
7978                return null;
7979            }
7980            return verificationParams.getManifestDigest();
7981        }
7982
7983        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7984            String packageName = pkgLite.packageName;
7985            int installLocation = pkgLite.installLocation;
7986            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7987            // reader
7988            synchronized (mPackages) {
7989                PackageParser.Package pkg = mPackages.get(packageName);
7990                if (pkg != null) {
7991                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7992                        // Check for downgrading.
7993                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7994                            if (pkgLite.versionCode < pkg.mVersionCode) {
7995                                Slog.w(TAG, "Can't install update of " + packageName
7996                                        + " update version " + pkgLite.versionCode
7997                                        + " is older than installed version "
7998                                        + pkg.mVersionCode);
7999                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8000                            }
8001                        }
8002                        // Check for updated system application.
8003                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8004                            if (onSd) {
8005                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8006                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8007                            }
8008                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8009                        } else {
8010                            if (onSd) {
8011                                // Install flag overrides everything.
8012                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8013                            }
8014                            // If current upgrade specifies particular preference
8015                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8016                                // Application explicitly specified internal.
8017                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8018                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8019                                // App explictly prefers external. Let policy decide
8020                            } else {
8021                                // Prefer previous location
8022                                if (isExternal(pkg)) {
8023                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8024                                }
8025                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8026                            }
8027                        }
8028                    } else {
8029                        // Invalid install. Return error code
8030                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8031                    }
8032                }
8033            }
8034            // All the special cases have been taken care of.
8035            // Return result based on recommended install location.
8036            if (onSd) {
8037                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8038            }
8039            return pkgLite.recommendedInstallLocation;
8040        }
8041
8042        private long getMemoryLowThreshold() {
8043            final DeviceStorageMonitorInternal
8044                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8045            if (dsm == null) {
8046                return 0L;
8047            }
8048            return dsm.getMemoryLowThreshold();
8049        }
8050
8051        /*
8052         * Invoke remote method to get package information and install
8053         * location values. Override install location based on default
8054         * policy if needed and then create install arguments based
8055         * on the install location.
8056         */
8057        public void handleStartCopy() throws RemoteException {
8058            int ret = PackageManager.INSTALL_SUCCEEDED;
8059            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8060            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8061            PackageInfoLite pkgLite = null;
8062
8063            if (onInt && onSd) {
8064                // Check if both bits are set.
8065                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8066                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8067            } else {
8068                final long lowThreshold = getMemoryLowThreshold();
8069                if (lowThreshold == 0L) {
8070                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8071                }
8072
8073                try {
8074                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8075                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8076
8077                    final File packageFile;
8078                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8079                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8080                        if (mTempPackage != null) {
8081                            ParcelFileDescriptor out;
8082                            try {
8083                                out = ParcelFileDescriptor.open(mTempPackage,
8084                                        ParcelFileDescriptor.MODE_READ_WRITE);
8085                            } catch (FileNotFoundException e) {
8086                                out = null;
8087                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8088                            }
8089
8090                            // Make a temporary file for decryption.
8091                            ret = mContainerService
8092                                    .copyResource(mPackageURI, encryptionParams, out);
8093                            IoUtils.closeQuietly(out);
8094
8095                            packageFile = mTempPackage;
8096
8097                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8098                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8099                                            | FileUtils.S_IROTH,
8100                                    -1, -1);
8101                        } else {
8102                            packageFile = null;
8103                        }
8104                    } else {
8105                        packageFile = new File(mPackageURI.getPath());
8106                    }
8107
8108                    if (packageFile != null) {
8109                        // Remote call to find out default install location
8110                        final String packageFilePath = packageFile.getAbsolutePath();
8111                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8112                                lowThreshold);
8113
8114                        /*
8115                         * If we have too little free space, try to free cache
8116                         * before giving up.
8117                         */
8118                        if (pkgLite.recommendedInstallLocation
8119                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8120                            final long size = mContainerService.calculateInstalledSize(
8121                                    packageFilePath, isForwardLocked());
8122                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8123                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8124                                        flags, lowThreshold);
8125                            }
8126                            /*
8127                             * The cache free must have deleted the file we
8128                             * downloaded to install.
8129                             *
8130                             * TODO: fix the "freeCache" call to not delete
8131                             *       the file we care about.
8132                             */
8133                            if (pkgLite.recommendedInstallLocation
8134                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8135                                pkgLite.recommendedInstallLocation
8136                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8137                            }
8138                        }
8139                    }
8140                } finally {
8141                    mContext.revokeUriPermission(mPackageURI,
8142                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8143                }
8144            }
8145
8146            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8147                int loc = pkgLite.recommendedInstallLocation;
8148                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8149                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8150                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8151                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8152                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8153                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8154                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8155                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8156                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8157                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8158                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8159                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8160                } else {
8161                    // Override with defaults if needed.
8162                    loc = installLocationPolicy(pkgLite, flags);
8163                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8164                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8165                    } else if (!onSd && !onInt) {
8166                        // Override install location with flags
8167                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8168                            // Set the flag to install on external media.
8169                            flags |= PackageManager.INSTALL_EXTERNAL;
8170                            flags &= ~PackageManager.INSTALL_INTERNAL;
8171                        } else {
8172                            // Make sure the flag for installing on external
8173                            // media is unset
8174                            flags |= PackageManager.INSTALL_INTERNAL;
8175                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8176                        }
8177                    }
8178                }
8179            }
8180
8181            final InstallArgs args = createInstallArgs(this);
8182            mArgs = args;
8183
8184            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8185                 /*
8186                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8187                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8188                 */
8189                int userIdentifier = getUser().getIdentifier();
8190                if (userIdentifier == UserHandle.USER_ALL
8191                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8192                    userIdentifier = UserHandle.USER_OWNER;
8193                }
8194
8195                /*
8196                 * Determine if we have any installed package verifiers. If we
8197                 * do, then we'll defer to them to verify the packages.
8198                 */
8199                final int requiredUid = mRequiredVerifierPackage == null ? -1
8200                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8201                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8202                    final Intent verification = new Intent(
8203                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8204                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8205                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8206
8207                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8208                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8209                            0 /* TODO: Which userId? */);
8210
8211                    if (DEBUG_VERIFY) {
8212                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8213                                + verification.toString() + " with " + pkgLite.verifiers.length
8214                                + " optional verifiers");
8215                    }
8216
8217                    final int verificationId = mPendingVerificationToken++;
8218
8219                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8220
8221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8222                            installerPackageName);
8223
8224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8225
8226                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8227                            pkgLite.packageName);
8228
8229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8230                            pkgLite.versionCode);
8231
8232                    if (verificationParams != null) {
8233                        if (verificationParams.getVerificationURI() != null) {
8234                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8235                                 verificationParams.getVerificationURI());
8236                        }
8237                        if (verificationParams.getOriginatingURI() != null) {
8238                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8239                                  verificationParams.getOriginatingURI());
8240                        }
8241                        if (verificationParams.getReferrer() != null) {
8242                            verification.putExtra(Intent.EXTRA_REFERRER,
8243                                  verificationParams.getReferrer());
8244                        }
8245                        if (verificationParams.getOriginatingUid() >= 0) {
8246                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8247                                  verificationParams.getOriginatingUid());
8248                        }
8249                        if (verificationParams.getInstallerUid() >= 0) {
8250                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8251                                  verificationParams.getInstallerUid());
8252                        }
8253                    }
8254
8255                    final PackageVerificationState verificationState = new PackageVerificationState(
8256                            requiredUid, args);
8257
8258                    mPendingVerification.append(verificationId, verificationState);
8259
8260                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8261                            receivers, verificationState);
8262
8263                    /*
8264                     * If any sufficient verifiers were listed in the package
8265                     * manifest, attempt to ask them.
8266                     */
8267                    if (sufficientVerifiers != null) {
8268                        final int N = sufficientVerifiers.size();
8269                        if (N == 0) {
8270                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8271                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8272                        } else {
8273                            for (int i = 0; i < N; i++) {
8274                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8275
8276                                final Intent sufficientIntent = new Intent(verification);
8277                                sufficientIntent.setComponent(verifierComponent);
8278
8279                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8280                            }
8281                        }
8282                    }
8283
8284                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8285                            mRequiredVerifierPackage, receivers);
8286                    if (ret == PackageManager.INSTALL_SUCCEEDED
8287                            && mRequiredVerifierPackage != null) {
8288                        /*
8289                         * Send the intent to the required verification agent,
8290                         * but only start the verification timeout after the
8291                         * target BroadcastReceivers have run.
8292                         */
8293                        verification.setComponent(requiredVerifierComponent);
8294                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8295                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8296                                new BroadcastReceiver() {
8297                                    @Override
8298                                    public void onReceive(Context context, Intent intent) {
8299                                        final Message msg = mHandler
8300                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8301                                        msg.arg1 = verificationId;
8302                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8303                                    }
8304                                }, null, 0, null, null);
8305
8306                        /*
8307                         * We don't want the copy to proceed until verification
8308                         * succeeds, so null out this field.
8309                         */
8310                        mArgs = null;
8311                    }
8312                } else {
8313                    /*
8314                     * No package verification is enabled, so immediately start
8315                     * the remote call to initiate copy using temporary file.
8316                     */
8317                    ret = args.copyApk(mContainerService, true);
8318                }
8319            }
8320
8321            mRet = ret;
8322        }
8323
8324        @Override
8325        void handleReturnCode() {
8326            // If mArgs is null, then MCS couldn't be reached. When it
8327            // reconnects, it will try again to install. At that point, this
8328            // will succeed.
8329            if (mArgs != null) {
8330                processPendingInstall(mArgs, mRet);
8331
8332                if (mTempPackage != null) {
8333                    if (!mTempPackage.delete()) {
8334                        Slog.w(TAG, "Couldn't delete temporary file: " +
8335                                mTempPackage.getAbsolutePath());
8336                    }
8337                }
8338            }
8339        }
8340
8341        @Override
8342        void handleServiceError() {
8343            mArgs = createInstallArgs(this);
8344            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8345        }
8346
8347        public boolean isForwardLocked() {
8348            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8349        }
8350
8351        public Uri getPackageUri() {
8352            if (mTempPackage != null) {
8353                return Uri.fromFile(mTempPackage);
8354            } else {
8355                return mPackageURI;
8356            }
8357        }
8358    }
8359
8360    /*
8361     * Utility class used in movePackage api.
8362     * srcArgs and targetArgs are not set for invalid flags and make
8363     * sure to do null checks when invoking methods on them.
8364     * We probably want to return ErrorPrams for both failed installs
8365     * and moves.
8366     */
8367    class MoveParams extends HandlerParams {
8368        final IPackageMoveObserver observer;
8369        final int flags;
8370        final String packageName;
8371        final InstallArgs srcArgs;
8372        final InstallArgs targetArgs;
8373        int uid;
8374        int mRet;
8375
8376        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8377                String packageName, String dataDir, String instructionSet,
8378                int uid, UserHandle user) {
8379            super(user);
8380            this.srcArgs = srcArgs;
8381            this.observer = observer;
8382            this.flags = flags;
8383            this.packageName = packageName;
8384            this.uid = uid;
8385            if (srcArgs != null) {
8386                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8387                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8388            } else {
8389                targetArgs = null;
8390            }
8391        }
8392
8393        @Override
8394        public String toString() {
8395            return "MoveParams{"
8396                + Integer.toHexString(System.identityHashCode(this))
8397                + " " + packageName + "}";
8398        }
8399
8400        public void handleStartCopy() throws RemoteException {
8401            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8402            // Check for storage space on target medium
8403            if (!targetArgs.checkFreeStorage(mContainerService)) {
8404                Log.w(TAG, "Insufficient storage to install");
8405                return;
8406            }
8407
8408            mRet = srcArgs.doPreCopy();
8409            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8410                return;
8411            }
8412
8413            mRet = targetArgs.copyApk(mContainerService, false);
8414            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8415                srcArgs.doPostCopy(uid);
8416                return;
8417            }
8418
8419            mRet = srcArgs.doPostCopy(uid);
8420            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8421                return;
8422            }
8423
8424            mRet = targetArgs.doPreInstall(mRet);
8425            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8426                return;
8427            }
8428
8429            if (DEBUG_SD_INSTALL) {
8430                StringBuilder builder = new StringBuilder();
8431                if (srcArgs != null) {
8432                    builder.append("src: ");
8433                    builder.append(srcArgs.getCodePath());
8434                }
8435                if (targetArgs != null) {
8436                    builder.append(" target : ");
8437                    builder.append(targetArgs.getCodePath());
8438                }
8439                Log.i(TAG, builder.toString());
8440            }
8441        }
8442
8443        @Override
8444        void handleReturnCode() {
8445            targetArgs.doPostInstall(mRet, uid);
8446            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8447            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8448                currentStatus = PackageManager.MOVE_SUCCEEDED;
8449            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8450                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8451            }
8452            processPendingMove(this, currentStatus);
8453        }
8454
8455        @Override
8456        void handleServiceError() {
8457            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8458        }
8459    }
8460
8461    /**
8462     * Used during creation of InstallArgs
8463     *
8464     * @param flags package installation flags
8465     * @return true if should be installed on external storage
8466     */
8467    private static boolean installOnSd(int flags) {
8468        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8469            return false;
8470        }
8471        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8472            return true;
8473        }
8474        return false;
8475    }
8476
8477    /**
8478     * Used during creation of InstallArgs
8479     *
8480     * @param flags package installation flags
8481     * @return true if should be installed as forward locked
8482     */
8483    private static boolean installForwardLocked(int flags) {
8484        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8485    }
8486
8487    private InstallArgs createInstallArgs(InstallParams params) {
8488        if (installOnSd(params.flags) || params.isForwardLocked()) {
8489            return new AsecInstallArgs(params);
8490        } else {
8491            return new FileInstallArgs(params);
8492        }
8493    }
8494
8495    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8496            String nativeLibraryPath, String instructionSet) {
8497        final boolean isInAsec;
8498        if (installOnSd(flags)) {
8499            /* Apps on SD card are always in ASEC containers. */
8500            isInAsec = true;
8501        } else if (installForwardLocked(flags)
8502                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8503            /*
8504             * Forward-locked apps are only in ASEC containers if they're the
8505             * new style
8506             */
8507            isInAsec = true;
8508        } else {
8509            isInAsec = false;
8510        }
8511
8512        if (isInAsec) {
8513            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8514                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8515        } else {
8516            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8517                    instructionSet);
8518        }
8519    }
8520
8521    // Used by package mover
8522    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8523            String instructionSet) {
8524        if (installOnSd(flags) || installForwardLocked(flags)) {
8525            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8526                    + AsecInstallArgs.RES_FILE_NAME);
8527            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8528                    installForwardLocked(flags));
8529        } else {
8530            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8531        }
8532    }
8533
8534    static abstract class InstallArgs {
8535        final IPackageInstallObserver observer;
8536        // Always refers to PackageManager flags only
8537        final int flags;
8538        final Uri packageURI;
8539        final String installerPackageName;
8540        final ManifestDigest manifestDigest;
8541        final UserHandle user;
8542        final String instructionSet;
8543
8544        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
8545                String installerPackageName, ManifestDigest manifestDigest,
8546                UserHandle user, String instructionSet) {
8547            this.packageURI = packageURI;
8548            this.flags = flags;
8549            this.observer = observer;
8550            this.installerPackageName = installerPackageName;
8551            this.manifestDigest = manifestDigest;
8552            this.user = user;
8553            this.instructionSet = instructionSet;
8554        }
8555
8556        abstract void createCopyFile();
8557        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8558        abstract int doPreInstall(int status);
8559        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8560
8561        abstract int doPostInstall(int status, int uid);
8562        abstract String getCodePath();
8563        abstract String getResourcePath();
8564        abstract String getNativeLibraryPath();
8565        // Need installer lock especially for dex file removal.
8566        abstract void cleanUpResourcesLI();
8567        abstract boolean doPostDeleteLI(boolean delete);
8568        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8569
8570        /**
8571         * Called before the source arguments are copied. This is used mostly
8572         * for MoveParams when it needs to read the source file to put it in the
8573         * destination.
8574         */
8575        int doPreCopy() {
8576            return PackageManager.INSTALL_SUCCEEDED;
8577        }
8578
8579        /**
8580         * Called after the source arguments are copied. This is used mostly for
8581         * MoveParams when it needs to read the source file to put it in the
8582         * destination.
8583         *
8584         * @return
8585         */
8586        int doPostCopy(int uid) {
8587            return PackageManager.INSTALL_SUCCEEDED;
8588        }
8589
8590        protected boolean isFwdLocked() {
8591            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8592        }
8593
8594        UserHandle getUser() {
8595            return user;
8596        }
8597    }
8598
8599    class FileInstallArgs extends InstallArgs {
8600        File installDir;
8601        String codeFileName;
8602        String resourceFileName;
8603        String libraryPath;
8604        boolean created = false;
8605
8606        FileInstallArgs(InstallParams params) {
8607            super(params.getPackageUri(), params.observer, params.flags,
8608                    params.installerPackageName, params.getManifestDigest(),
8609                    params.getUser(), null /* instruction set */);
8610        }
8611
8612        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8613                String instructionSet) {
8614            super(null, null, 0, null, null, null, instructionSet);
8615            File codeFile = new File(fullCodePath);
8616            installDir = codeFile.getParentFile();
8617            codeFileName = fullCodePath;
8618            resourceFileName = fullResourcePath;
8619            libraryPath = nativeLibraryPath;
8620        }
8621
8622        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8623            super(packageURI, null, 0, null, null, null, instructionSet);
8624            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8625            String apkName = getNextCodePath(null, pkgName, ".apk");
8626            codeFileName = new File(installDir, apkName + ".apk").getPath();
8627            resourceFileName = getResourcePathFromCodePath();
8628            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8629        }
8630
8631        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8632            final long lowThreshold;
8633
8634            final DeviceStorageMonitorInternal
8635                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8636            if (dsm == null) {
8637                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8638                lowThreshold = 0L;
8639            } else {
8640                if (dsm.isMemoryLow()) {
8641                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8642                    return false;
8643                }
8644
8645                lowThreshold = dsm.getMemoryLowThreshold();
8646            }
8647
8648            try {
8649                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8650                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8651                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8652            } finally {
8653                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8654            }
8655        }
8656
8657        String getCodePath() {
8658            return codeFileName;
8659        }
8660
8661        void createCopyFile() {
8662            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8663            codeFileName = createTempPackageFile(installDir).getPath();
8664            resourceFileName = getResourcePathFromCodePath();
8665            libraryPath = getLibraryPathFromCodePath();
8666            created = true;
8667        }
8668
8669        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8670            if (temp) {
8671                // Generate temp file name
8672                createCopyFile();
8673            }
8674            // Get a ParcelFileDescriptor to write to the output file
8675            File codeFile = new File(codeFileName);
8676            if (!created) {
8677                try {
8678                    codeFile.createNewFile();
8679                    // Set permissions
8680                    if (!setPermissions()) {
8681                        // Failed setting permissions.
8682                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8683                    }
8684                } catch (IOException e) {
8685                   Slog.w(TAG, "Failed to create file " + codeFile);
8686                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8687                }
8688            }
8689            ParcelFileDescriptor out = null;
8690            try {
8691                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8692            } catch (FileNotFoundException e) {
8693                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8694                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8695            }
8696            // Copy the resource now
8697            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8698            try {
8699                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8700                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8701                ret = imcs.copyResource(packageURI, null, out);
8702            } finally {
8703                IoUtils.closeQuietly(out);
8704                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8705            }
8706
8707            if (isFwdLocked()) {
8708                final File destResourceFile = new File(getResourcePath());
8709
8710                // Copy the public files
8711                try {
8712                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8713                } catch (IOException e) {
8714                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8715                            + " forward-locked app.");
8716                    destResourceFile.delete();
8717                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8718                }
8719            }
8720
8721            final File nativeLibraryFile = new File(getNativeLibraryPath());
8722            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8723            if (nativeLibraryFile.exists()) {
8724                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8725                nativeLibraryFile.delete();
8726            }
8727            try {
8728                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8729                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8730                    return copyRet;
8731                }
8732            } catch (IOException e) {
8733                Slog.e(TAG, "Copying native libraries failed", e);
8734                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8735            }
8736
8737            return ret;
8738        }
8739
8740        int doPreInstall(int status) {
8741            if (status != PackageManager.INSTALL_SUCCEEDED) {
8742                cleanUp();
8743            }
8744            return status;
8745        }
8746
8747        boolean doRename(int status, final String pkgName, String oldCodePath) {
8748            if (status != PackageManager.INSTALL_SUCCEEDED) {
8749                cleanUp();
8750                return false;
8751            } else {
8752                final File oldCodeFile = new File(getCodePath());
8753                final File oldResourceFile = new File(getResourcePath());
8754                final File oldLibraryFile = new File(getNativeLibraryPath());
8755
8756                // Rename APK file based on packageName
8757                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8758                final File newCodeFile = new File(installDir, apkName + ".apk");
8759                if (!oldCodeFile.renameTo(newCodeFile)) {
8760                    return false;
8761                }
8762                codeFileName = newCodeFile.getPath();
8763
8764                // Rename public resource file if it's forward-locked.
8765                final File newResFile = new File(getResourcePathFromCodePath());
8766                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8767                    return false;
8768                }
8769                resourceFileName = newResFile.getPath();
8770
8771                // Rename library path
8772                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8773                if (newLibraryFile.exists()) {
8774                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8775                    newLibraryFile.delete();
8776                }
8777                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8778                    Slog.e(TAG, "Cannot rename native library directory "
8779                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8780                    return false;
8781                }
8782                libraryPath = newLibraryFile.getPath();
8783
8784                // Attempt to set permissions
8785                if (!setPermissions()) {
8786                    return false;
8787                }
8788
8789                if (!SELinux.restorecon(newCodeFile)) {
8790                    return false;
8791                }
8792
8793                return true;
8794            }
8795        }
8796
8797        int doPostInstall(int status, int uid) {
8798            if (status != PackageManager.INSTALL_SUCCEEDED) {
8799                cleanUp();
8800            }
8801            return status;
8802        }
8803
8804        String getResourcePath() {
8805            return resourceFileName;
8806        }
8807
8808        private String getResourcePathFromCodePath() {
8809            final String codePath = getCodePath();
8810            if (isFwdLocked()) {
8811                final StringBuilder sb = new StringBuilder();
8812
8813                sb.append(mAppInstallDir.getPath());
8814                sb.append('/');
8815                sb.append(getApkName(codePath));
8816                sb.append(".zip");
8817
8818                /*
8819                 * If our APK is a temporary file, mark the resource as a
8820                 * temporary file as well so it can be cleaned up after
8821                 * catastrophic failure.
8822                 */
8823                if (codePath.endsWith(".tmp")) {
8824                    sb.append(".tmp");
8825                }
8826
8827                return sb.toString();
8828            } else {
8829                return codePath;
8830            }
8831        }
8832
8833        private String getLibraryPathFromCodePath() {
8834            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8835        }
8836
8837        @Override
8838        String getNativeLibraryPath() {
8839            if (libraryPath == null) {
8840                libraryPath = getLibraryPathFromCodePath();
8841            }
8842            return libraryPath;
8843        }
8844
8845        private boolean cleanUp() {
8846            boolean ret = true;
8847            String sourceDir = getCodePath();
8848            String publicSourceDir = getResourcePath();
8849            if (sourceDir != null) {
8850                File sourceFile = new File(sourceDir);
8851                if (!sourceFile.exists()) {
8852                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8853                    ret = false;
8854                }
8855                // Delete application's code and resources
8856                sourceFile.delete();
8857            }
8858            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8859                final File publicSourceFile = new File(publicSourceDir);
8860                if (!publicSourceFile.exists()) {
8861                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8862                }
8863                if (publicSourceFile.exists()) {
8864                    publicSourceFile.delete();
8865                }
8866            }
8867
8868            if (libraryPath != null) {
8869                File nativeLibraryFile = new File(libraryPath);
8870                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8871                if (!nativeLibraryFile.delete()) {
8872                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8873                }
8874            }
8875
8876            return ret;
8877        }
8878
8879        void cleanUpResourcesLI() {
8880            String sourceDir = getCodePath();
8881            if (cleanUp()) {
8882                if (instructionSet == null) {
8883                    throw new IllegalStateException("instructionSet == null");
8884                }
8885                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
8886                if (retCode < 0) {
8887                    Slog.w(TAG, "Couldn't remove dex file for package: "
8888                            +  " at location "
8889                            + sourceDir + ", retcode=" + retCode);
8890                    // we don't consider this to be a failure of the core package deletion
8891                }
8892            }
8893        }
8894
8895        private boolean setPermissions() {
8896            // TODO Do this in a more elegant way later on. for now just a hack
8897            if (!isFwdLocked()) {
8898                final int filePermissions =
8899                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8900                    |FileUtils.S_IROTH;
8901                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8902                if (retCode != 0) {
8903                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8904                            getCodePath()
8905                            + ". The return code was: " + retCode);
8906                    // TODO Define new internal error
8907                    return false;
8908                }
8909                return true;
8910            }
8911            return true;
8912        }
8913
8914        boolean doPostDeleteLI(boolean delete) {
8915            // XXX err, shouldn't we respect the delete flag?
8916            cleanUpResourcesLI();
8917            return true;
8918        }
8919    }
8920
8921    private boolean isAsecExternal(String cid) {
8922        final String asecPath = PackageHelper.getSdFilesystem(cid);
8923        return !asecPath.startsWith(mAsecInternalPath);
8924    }
8925
8926    /**
8927     * Extract the MountService "container ID" from the full code path of an
8928     * .apk.
8929     */
8930    static String cidFromCodePath(String fullCodePath) {
8931        int eidx = fullCodePath.lastIndexOf("/");
8932        String subStr1 = fullCodePath.substring(0, eidx);
8933        int sidx = subStr1.lastIndexOf("/");
8934        return subStr1.substring(sidx+1, eidx);
8935    }
8936
8937    class AsecInstallArgs extends InstallArgs {
8938        static final String RES_FILE_NAME = "pkg.apk";
8939        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8940
8941        String cid;
8942        String packagePath;
8943        String resourcePath;
8944        String libraryPath;
8945
8946        AsecInstallArgs(InstallParams params) {
8947            super(params.getPackageUri(), params.observer, params.flags,
8948                    params.installerPackageName, params.getManifestDigest(),
8949                    params.getUser(), null /* instruction set */);
8950        }
8951
8952        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8953                String instructionSet, boolean isExternal, boolean isForwardLocked) {
8954            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8955                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8956                    null, null, null, instructionSet);
8957            // Extract cid from fullCodePath
8958            int eidx = fullCodePath.lastIndexOf("/");
8959            String subStr1 = fullCodePath.substring(0, eidx);
8960            int sidx = subStr1.lastIndexOf("/");
8961            cid = subStr1.substring(sidx+1, eidx);
8962            setCachePath(subStr1);
8963        }
8964
8965        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
8966            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8967                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8968                    null, null, null, instructionSet);
8969            this.cid = cid;
8970            setCachePath(PackageHelper.getSdDir(cid));
8971        }
8972
8973        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
8974                boolean isExternal, boolean isForwardLocked) {
8975            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8976                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8977                    null, null, null, instructionSet);
8978            this.cid = cid;
8979        }
8980
8981        void createCopyFile() {
8982            cid = getTempContainerId();
8983        }
8984
8985        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8986            try {
8987                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8988                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8989                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8990            } finally {
8991                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8992            }
8993        }
8994
8995        private final boolean isExternal() {
8996            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8997        }
8998
8999        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9000            if (temp) {
9001                createCopyFile();
9002            } else {
9003                /*
9004                 * Pre-emptively destroy the container since it's destroyed if
9005                 * copying fails due to it existing anyway.
9006                 */
9007                PackageHelper.destroySdDir(cid);
9008            }
9009
9010            final String newCachePath;
9011            try {
9012                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9013                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9014                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9015                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9016            } finally {
9017                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9018            }
9019
9020            if (newCachePath != null) {
9021                setCachePath(newCachePath);
9022                return PackageManager.INSTALL_SUCCEEDED;
9023            } else {
9024                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9025            }
9026        }
9027
9028        @Override
9029        String getCodePath() {
9030            return packagePath;
9031        }
9032
9033        @Override
9034        String getResourcePath() {
9035            return resourcePath;
9036        }
9037
9038        @Override
9039        String getNativeLibraryPath() {
9040            return libraryPath;
9041        }
9042
9043        int doPreInstall(int status) {
9044            if (status != PackageManager.INSTALL_SUCCEEDED) {
9045                // Destroy container
9046                PackageHelper.destroySdDir(cid);
9047            } else {
9048                boolean mounted = PackageHelper.isContainerMounted(cid);
9049                if (!mounted) {
9050                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9051                            Process.SYSTEM_UID);
9052                    if (newCachePath != null) {
9053                        setCachePath(newCachePath);
9054                    } else {
9055                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9056                    }
9057                }
9058            }
9059            return status;
9060        }
9061
9062        boolean doRename(int status, final String pkgName,
9063                String oldCodePath) {
9064            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9065            String newCachePath = null;
9066            if (PackageHelper.isContainerMounted(cid)) {
9067                // Unmount the container
9068                if (!PackageHelper.unMountSdDir(cid)) {
9069                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9070                    return false;
9071                }
9072            }
9073            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9074                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9075                        " which might be stale. Will try to clean up.");
9076                // Clean up the stale container and proceed to recreate.
9077                if (!PackageHelper.destroySdDir(newCacheId)) {
9078                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9079                    return false;
9080                }
9081                // Successfully cleaned up stale container. Try to rename again.
9082                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9083                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9084                            + " inspite of cleaning it up.");
9085                    return false;
9086                }
9087            }
9088            if (!PackageHelper.isContainerMounted(newCacheId)) {
9089                Slog.w(TAG, "Mounting container " + newCacheId);
9090                newCachePath = PackageHelper.mountSdDir(newCacheId,
9091                        getEncryptKey(), Process.SYSTEM_UID);
9092            } else {
9093                newCachePath = PackageHelper.getSdDir(newCacheId);
9094            }
9095            if (newCachePath == null) {
9096                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9097                return false;
9098            }
9099            Log.i(TAG, "Succesfully renamed " + cid +
9100                    " to " + newCacheId +
9101                    " at new path: " + newCachePath);
9102            cid = newCacheId;
9103            setCachePath(newCachePath);
9104            return true;
9105        }
9106
9107        private void setCachePath(String newCachePath) {
9108            File cachePath = new File(newCachePath);
9109            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9110            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9111
9112            if (isFwdLocked()) {
9113                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9114            } else {
9115                resourcePath = packagePath;
9116            }
9117        }
9118
9119        int doPostInstall(int status, int uid) {
9120            if (status != PackageManager.INSTALL_SUCCEEDED) {
9121                cleanUp();
9122            } else {
9123                final int groupOwner;
9124                final String protectedFile;
9125                if (isFwdLocked()) {
9126                    groupOwner = UserHandle.getSharedAppGid(uid);
9127                    protectedFile = RES_FILE_NAME;
9128                } else {
9129                    groupOwner = -1;
9130                    protectedFile = null;
9131                }
9132
9133                if (uid < Process.FIRST_APPLICATION_UID
9134                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9135                    Slog.e(TAG, "Failed to finalize " + cid);
9136                    PackageHelper.destroySdDir(cid);
9137                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9138                }
9139
9140                boolean mounted = PackageHelper.isContainerMounted(cid);
9141                if (!mounted) {
9142                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9143                }
9144            }
9145            return status;
9146        }
9147
9148        private void cleanUp() {
9149            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9150
9151            // Destroy secure container
9152            PackageHelper.destroySdDir(cid);
9153        }
9154
9155        void cleanUpResourcesLI() {
9156            String sourceFile = getCodePath();
9157            // Remove dex file
9158            if (instructionSet == null) {
9159                throw new IllegalStateException("instructionSet == null");
9160            }
9161            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9162            if (retCode < 0) {
9163                Slog.w(TAG, "Couldn't remove dex file for package: "
9164                        + " at location "
9165                        + sourceFile.toString() + ", retcode=" + retCode);
9166                // we don't consider this to be a failure of the core package deletion
9167            }
9168            cleanUp();
9169        }
9170
9171        boolean matchContainer(String app) {
9172            if (cid.startsWith(app)) {
9173                return true;
9174            }
9175            return false;
9176        }
9177
9178        String getPackageName() {
9179            return getAsecPackageName(cid);
9180        }
9181
9182        boolean doPostDeleteLI(boolean delete) {
9183            boolean ret = false;
9184            boolean mounted = PackageHelper.isContainerMounted(cid);
9185            if (mounted) {
9186                // Unmount first
9187                ret = PackageHelper.unMountSdDir(cid);
9188            }
9189            if (ret && delete) {
9190                cleanUpResourcesLI();
9191            }
9192            return ret;
9193        }
9194
9195        @Override
9196        int doPreCopy() {
9197            if (isFwdLocked()) {
9198                if (!PackageHelper.fixSdPermissions(cid,
9199                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9200                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9201                }
9202            }
9203
9204            return PackageManager.INSTALL_SUCCEEDED;
9205        }
9206
9207        @Override
9208        int doPostCopy(int uid) {
9209            if (isFwdLocked()) {
9210                if (uid < Process.FIRST_APPLICATION_UID
9211                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9212                                RES_FILE_NAME)) {
9213                    Slog.e(TAG, "Failed to finalize " + cid);
9214                    PackageHelper.destroySdDir(cid);
9215                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9216                }
9217            }
9218
9219            return PackageManager.INSTALL_SUCCEEDED;
9220        }
9221    };
9222
9223    static String getAsecPackageName(String packageCid) {
9224        int idx = packageCid.lastIndexOf("-");
9225        if (idx == -1) {
9226            return packageCid;
9227        }
9228        return packageCid.substring(0, idx);
9229    }
9230
9231    // Utility method used to create code paths based on package name and available index.
9232    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9233        String idxStr = "";
9234        int idx = 1;
9235        // Fall back to default value of idx=1 if prefix is not
9236        // part of oldCodePath
9237        if (oldCodePath != null) {
9238            String subStr = oldCodePath;
9239            // Drop the suffix right away
9240            if (subStr.endsWith(suffix)) {
9241                subStr = subStr.substring(0, subStr.length() - suffix.length());
9242            }
9243            // If oldCodePath already contains prefix find out the
9244            // ending index to either increment or decrement.
9245            int sidx = subStr.lastIndexOf(prefix);
9246            if (sidx != -1) {
9247                subStr = subStr.substring(sidx + prefix.length());
9248                if (subStr != null) {
9249                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9250                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9251                    }
9252                    try {
9253                        idx = Integer.parseInt(subStr);
9254                        if (idx <= 1) {
9255                            idx++;
9256                        } else {
9257                            idx--;
9258                        }
9259                    } catch(NumberFormatException e) {
9260                    }
9261                }
9262            }
9263        }
9264        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9265        return prefix + idxStr;
9266    }
9267
9268    // Utility method used to ignore ADD/REMOVE events
9269    // by directory observer.
9270    private static boolean ignoreCodePath(String fullPathStr) {
9271        String apkName = getApkName(fullPathStr);
9272        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9273        if (idx != -1 && ((idx+1) < apkName.length())) {
9274            // Make sure the package ends with a numeral
9275            String version = apkName.substring(idx+1);
9276            try {
9277                Integer.parseInt(version);
9278                return true;
9279            } catch (NumberFormatException e) {}
9280        }
9281        return false;
9282    }
9283
9284    // Utility method that returns the relative package path with respect
9285    // to the installation directory. Like say for /data/data/com.test-1.apk
9286    // string com.test-1 is returned.
9287    static String getApkName(String codePath) {
9288        if (codePath == null) {
9289            return null;
9290        }
9291        int sidx = codePath.lastIndexOf("/");
9292        int eidx = codePath.lastIndexOf(".");
9293        if (eidx == -1) {
9294            eidx = codePath.length();
9295        } else if (eidx == 0) {
9296            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9297            return null;
9298        }
9299        return codePath.substring(sidx+1, eidx);
9300    }
9301
9302    class PackageInstalledInfo {
9303        String name;
9304        int uid;
9305        // The set of users that originally had this package installed.
9306        int[] origUsers;
9307        // The set of users that now have this package installed.
9308        int[] newUsers;
9309        PackageParser.Package pkg;
9310        int returnCode;
9311        PackageRemovedInfo removedInfo;
9312    }
9313
9314    /*
9315     * Install a non-existing package.
9316     */
9317    private void installNewPackageLI(PackageParser.Package pkg,
9318            int parseFlags, int scanMode, UserHandle user,
9319            String installerPackageName, PackageInstalledInfo res) {
9320        // Remember this for later, in case we need to rollback this install
9321        String pkgName = pkg.packageName;
9322
9323        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9324        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9325        synchronized(mPackages) {
9326            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9327                // A package with the same name is already installed, though
9328                // it has been renamed to an older name.  The package we
9329                // are trying to install should be installed as an update to
9330                // the existing one, but that has not been requested, so bail.
9331                Slog.w(TAG, "Attempt to re-install " + pkgName
9332                        + " without first uninstalling package running as "
9333                        + mSettings.mRenamedPackages.get(pkgName));
9334                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9335                return;
9336            }
9337            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9338                // Don't allow installation over an existing package with the same name.
9339                Slog.w(TAG, "Attempt to re-install " + pkgName
9340                        + " without first uninstalling.");
9341                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9342                return;
9343            }
9344        }
9345        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9346        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9347                System.currentTimeMillis(), user);
9348        if (newPackage == null) {
9349            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9350            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9351                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9352            }
9353        } else {
9354            updateSettingsLI(newPackage,
9355                    installerPackageName,
9356                    null, null,
9357                    res);
9358            // delete the partially installed application. the data directory will have to be
9359            // restored if it was already existing
9360            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9361                // remove package from internal structures.  Note that we want deletePackageX to
9362                // delete the package data and cache directories that it created in
9363                // scanPackageLocked, unless those directories existed before we even tried to
9364                // install.
9365                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9366                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9367                                res.removedInfo, true);
9368            }
9369        }
9370    }
9371
9372    private void replacePackageLI(PackageParser.Package pkg,
9373            int parseFlags, int scanMode, UserHandle user,
9374            String installerPackageName, PackageInstalledInfo res) {
9375
9376        PackageParser.Package oldPackage;
9377        String pkgName = pkg.packageName;
9378        int[] allUsers;
9379        boolean[] perUserInstalled;
9380
9381        // First find the old package info and check signatures
9382        synchronized(mPackages) {
9383            oldPackage = mPackages.get(pkgName);
9384            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9385            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9386                    != PackageManager.SIGNATURE_MATCH) {
9387                Slog.w(TAG, "New package has a different signature: " + pkgName);
9388                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9389                return;
9390            }
9391
9392            // In case of rollback, remember per-user/profile install state
9393            PackageSetting ps = mSettings.mPackages.get(pkgName);
9394            allUsers = sUserManager.getUserIds();
9395            perUserInstalled = new boolean[allUsers.length];
9396            for (int i = 0; i < allUsers.length; i++) {
9397                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9398            }
9399        }
9400        boolean sysPkg = (isSystemApp(oldPackage));
9401        if (sysPkg) {
9402            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9403                    user, allUsers, perUserInstalled, installerPackageName, res);
9404        } else {
9405            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9406                    user, allUsers, perUserInstalled, installerPackageName, res);
9407        }
9408    }
9409
9410    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9411            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9412            int[] allUsers, boolean[] perUserInstalled,
9413            String installerPackageName, PackageInstalledInfo res) {
9414        PackageParser.Package newPackage = null;
9415        String pkgName = deletedPackage.packageName;
9416        boolean deletedPkg = true;
9417        boolean updatedSettings = false;
9418
9419        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9420                + deletedPackage);
9421        long origUpdateTime;
9422        if (pkg.mExtras != null) {
9423            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9424        } else {
9425            origUpdateTime = 0;
9426        }
9427
9428        // First delete the existing package while retaining the data directory
9429        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9430                res.removedInfo, true)) {
9431            // If the existing package wasn't successfully deleted
9432            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9433            deletedPkg = false;
9434        } else {
9435            // Successfully deleted the old package. Now proceed with re-installation
9436            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9437            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9438                    System.currentTimeMillis(), user);
9439            if (newPackage == null) {
9440                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9441                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9442                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9443                }
9444            } else {
9445                updateSettingsLI(newPackage,
9446                        installerPackageName,
9447                        allUsers, perUserInstalled,
9448                        res);
9449                updatedSettings = true;
9450            }
9451        }
9452
9453        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9454            // remove package from internal structures.  Note that we want deletePackageX to
9455            // delete the package data and cache directories that it created in
9456            // scanPackageLocked, unless those directories existed before we even tried to
9457            // install.
9458            if(updatedSettings) {
9459                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9460                deletePackageLI(
9461                        pkgName, null, true, allUsers, perUserInstalled,
9462                        PackageManager.DELETE_KEEP_DATA,
9463                                res.removedInfo, true);
9464            }
9465            // Since we failed to install the new package we need to restore the old
9466            // package that we deleted.
9467            if(deletedPkg) {
9468                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9469                File restoreFile = new File(deletedPackage.mPath);
9470                // Parse old package
9471                boolean oldOnSd = isExternal(deletedPackage);
9472                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9473                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9474                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9475                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9476                        | SCAN_UPDATE_TIME;
9477                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9478                        origUpdateTime, null) == null) {
9479                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9480                    return;
9481                }
9482                // Restore of old package succeeded. Update permissions.
9483                // writer
9484                synchronized (mPackages) {
9485                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9486                            UPDATE_PERMISSIONS_ALL);
9487                    // can downgrade to reader
9488                    mSettings.writeLPr();
9489                }
9490                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9491            }
9492        }
9493    }
9494
9495    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9496            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9497            int[] allUsers, boolean[] perUserInstalled,
9498            String installerPackageName, PackageInstalledInfo res) {
9499        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9500                + ", old=" + deletedPackage);
9501        PackageParser.Package newPackage = null;
9502        boolean updatedSettings = false;
9503        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9504                PackageParser.PARSE_IS_SYSTEM;
9505        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9506            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9507        }
9508        String packageName = deletedPackage.packageName;
9509        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9510        if (packageName == null) {
9511            Slog.w(TAG, "Attempt to delete null packageName.");
9512            return;
9513        }
9514        PackageParser.Package oldPkg;
9515        PackageSetting oldPkgSetting;
9516        // reader
9517        synchronized (mPackages) {
9518            oldPkg = mPackages.get(packageName);
9519            oldPkgSetting = mSettings.mPackages.get(packageName);
9520            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9521                    (oldPkgSetting == null)) {
9522                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9523                return;
9524            }
9525        }
9526
9527        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9528
9529        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9530        res.removedInfo.removedPackage = packageName;
9531        // Remove existing system package
9532        removePackageLI(oldPkgSetting, true);
9533        // writer
9534        synchronized (mPackages) {
9535            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9536                // We didn't need to disable the .apk as a current system package,
9537                // which means we are replacing another update that is already
9538                // installed.  We need to make sure to delete the older one's .apk.
9539                res.removedInfo.args = createInstallArgs(0,
9540                        deletedPackage.applicationInfo.sourceDir,
9541                        deletedPackage.applicationInfo.publicSourceDir,
9542                        deletedPackage.applicationInfo.nativeLibraryDir,
9543                        getAppInstructionSet(deletedPackage.applicationInfo));
9544            } else {
9545                res.removedInfo.args = null;
9546            }
9547        }
9548
9549        // Successfully disabled the old package. Now proceed with re-installation
9550        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9551        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9552        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9553        if (newPackage == null) {
9554            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9555            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9556                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9557            }
9558        } else {
9559            if (newPackage.mExtras != null) {
9560                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9561                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9562                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9563            }
9564            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9565            updatedSettings = true;
9566        }
9567
9568        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9569            // Re installation failed. Restore old information
9570            // Remove new pkg information
9571            if (newPackage != null) {
9572                removeInstalledPackageLI(newPackage, true);
9573            }
9574            // Add back the old system package
9575            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9576            // Restore the old system information in Settings
9577            synchronized(mPackages) {
9578                if (updatedSettings) {
9579                    mSettings.enableSystemPackageLPw(packageName);
9580                    mSettings.setInstallerPackageName(packageName,
9581                            oldPkgSetting.installerPackageName);
9582                }
9583                mSettings.writeLPr();
9584            }
9585        }
9586    }
9587
9588    // Utility method used to move dex files during install.
9589    private int moveDexFilesLI(PackageParser.Package newPackage) {
9590        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9591            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9592            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9593                                             instructionSet);
9594            if (retCode != 0) {
9595                /*
9596                 * Programs may be lazily run through dexopt, so the
9597                 * source may not exist. However, something seems to
9598                 * have gone wrong, so note that dexopt needs to be
9599                 * run again and remove the source file. In addition,
9600                 * remove the target to make sure there isn't a stale
9601                 * file from a previous version of the package.
9602                 */
9603                newPackage.mDexOptNeeded = true;
9604                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
9605                mInstaller.rmdex(newPackage.mPath, instructionSet);
9606            }
9607        }
9608        return PackageManager.INSTALL_SUCCEEDED;
9609    }
9610
9611    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9612            int[] allUsers, boolean[] perUserInstalled,
9613            PackageInstalledInfo res) {
9614        String pkgName = newPackage.packageName;
9615        synchronized (mPackages) {
9616            //write settings. the installStatus will be incomplete at this stage.
9617            //note that the new package setting would have already been
9618            //added to mPackages. It hasn't been persisted yet.
9619            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9620            mSettings.writeLPr();
9621        }
9622
9623        if ((res.returnCode = moveDexFilesLI(newPackage))
9624                != PackageManager.INSTALL_SUCCEEDED) {
9625            // Discontinue if moving dex files failed.
9626            return;
9627        }
9628
9629        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9630
9631        synchronized (mPackages) {
9632            updatePermissionsLPw(newPackage.packageName, newPackage,
9633                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9634                            ? UPDATE_PERMISSIONS_ALL : 0));
9635            // For system-bundled packages, we assume that installing an upgraded version
9636            // of the package implies that the user actually wants to run that new code,
9637            // so we enable the package.
9638            if (isSystemApp(newPackage)) {
9639                // NB: implicit assumption that system package upgrades apply to all users
9640                if (DEBUG_INSTALL) {
9641                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9642                }
9643                PackageSetting ps = mSettings.mPackages.get(pkgName);
9644                if (ps != null) {
9645                    if (res.origUsers != null) {
9646                        for (int userHandle : res.origUsers) {
9647                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9648                                    userHandle, installerPackageName);
9649                        }
9650                    }
9651                    // Also convey the prior install/uninstall state
9652                    if (allUsers != null && perUserInstalled != null) {
9653                        for (int i = 0; i < allUsers.length; i++) {
9654                            if (DEBUG_INSTALL) {
9655                                Slog.d(TAG, "    user " + allUsers[i]
9656                                        + " => " + perUserInstalled[i]);
9657                            }
9658                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9659                        }
9660                        // these install state changes will be persisted in the
9661                        // upcoming call to mSettings.writeLPr().
9662                    }
9663                }
9664            }
9665            res.name = pkgName;
9666            res.uid = newPackage.applicationInfo.uid;
9667            res.pkg = newPackage;
9668            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9669            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9670            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9671            //to update install status
9672            mSettings.writeLPr();
9673        }
9674    }
9675
9676    private void installPackageLI(InstallArgs args,
9677            boolean newInstall, PackageInstalledInfo res) {
9678        int pFlags = args.flags;
9679        String installerPackageName = args.installerPackageName;
9680        File tmpPackageFile = new File(args.getCodePath());
9681        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9682        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9683        boolean replace = false;
9684        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9685                | (newInstall ? SCAN_NEW_INSTALL : 0);
9686        // Result object to be returned
9687        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9688
9689        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9690        // Retrieve PackageSettings and parse package
9691        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9692                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9693                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9694        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9695        pp.setSeparateProcesses(mSeparateProcesses);
9696        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9697                null, mMetrics, parseFlags);
9698        if (pkg == null) {
9699            res.returnCode = pp.getParseError();
9700            return;
9701        }
9702        String pkgName = res.name = pkg.packageName;
9703        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9704            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9705                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9706                return;
9707            }
9708        }
9709        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9710            res.returnCode = pp.getParseError();
9711            return;
9712        }
9713
9714        /* If the installer passed in a manifest digest, compare it now. */
9715        if (args.manifestDigest != null) {
9716            if (DEBUG_INSTALL) {
9717                final String parsedManifest = pkg.manifestDigest == null ? "null"
9718                        : pkg.manifestDigest.toString();
9719                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9720                        + parsedManifest);
9721            }
9722
9723            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9724                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9725                return;
9726            }
9727        } else if (DEBUG_INSTALL) {
9728            final String parsedManifest = pkg.manifestDigest == null
9729                    ? "null" : pkg.manifestDigest.toString();
9730            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9731        }
9732
9733        // Get rid of all references to package scan path via parser.
9734        pp = null;
9735        String oldCodePath = null;
9736        boolean systemApp = false;
9737        synchronized (mPackages) {
9738            // Check if installing already existing package
9739            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9740                String oldName = mSettings.mRenamedPackages.get(pkgName);
9741                if (pkg.mOriginalPackages != null
9742                        && pkg.mOriginalPackages.contains(oldName)
9743                        && mPackages.containsKey(oldName)) {
9744                    // This package is derived from an original package,
9745                    // and this device has been updating from that original
9746                    // name.  We must continue using the original name, so
9747                    // rename the new package here.
9748                    pkg.setPackageName(oldName);
9749                    pkgName = pkg.packageName;
9750                    replace = true;
9751                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9752                            + oldName + " pkgName=" + pkgName);
9753                } else if (mPackages.containsKey(pkgName)) {
9754                    // This package, under its official name, already exists
9755                    // on the device; we should replace it.
9756                    replace = true;
9757                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9758                }
9759            }
9760            PackageSetting ps = mSettings.mPackages.get(pkgName);
9761            if (ps != null) {
9762                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9763                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9764                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9765                    systemApp = (ps.pkg.applicationInfo.flags &
9766                            ApplicationInfo.FLAG_SYSTEM) != 0;
9767                }
9768                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9769            }
9770        }
9771
9772        if (systemApp && onSd) {
9773            // Disable updates to system apps on sdcard
9774            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9775            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9776            return;
9777        }
9778
9779        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9780            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9781            return;
9782        }
9783        // Set application objects path explicitly after the rename
9784        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9785        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9786        if (replace) {
9787            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9788                    installerPackageName, res);
9789        } else {
9790            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9791                    installerPackageName, res);
9792        }
9793        synchronized (mPackages) {
9794            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9795            if (ps != null) {
9796                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9797            }
9798        }
9799    }
9800
9801    private static boolean isForwardLocked(PackageParser.Package pkg) {
9802        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9803    }
9804
9805
9806    private boolean isForwardLocked(PackageSetting ps) {
9807        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9808    }
9809
9810    private static boolean isExternal(PackageParser.Package pkg) {
9811        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9812    }
9813
9814    private static boolean isExternal(PackageSetting ps) {
9815        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9816    }
9817
9818    private static boolean isSystemApp(PackageParser.Package pkg) {
9819        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9820    }
9821
9822    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9823        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9824    }
9825
9826    private static boolean isSystemApp(ApplicationInfo info) {
9827        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9828    }
9829
9830    private static boolean isSystemApp(PackageSetting ps) {
9831        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9832    }
9833
9834    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9835        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9836    }
9837
9838    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9839        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9840    }
9841
9842    private int packageFlagsToInstallFlags(PackageSetting ps) {
9843        int installFlags = 0;
9844        if (isExternal(ps)) {
9845            installFlags |= PackageManager.INSTALL_EXTERNAL;
9846        }
9847        if (isForwardLocked(ps)) {
9848            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9849        }
9850        return installFlags;
9851    }
9852
9853    private void deleteTempPackageFiles() {
9854        final FilenameFilter filter = new FilenameFilter() {
9855            public boolean accept(File dir, String name) {
9856                return name.startsWith("vmdl") && name.endsWith(".tmp");
9857            }
9858        };
9859        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9860        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9861    }
9862
9863    private static final void deleteTempPackageFilesInDirectory(File directory,
9864            FilenameFilter filter) {
9865        final String[] tmpFilesList = directory.list(filter);
9866        if (tmpFilesList == null) {
9867            return;
9868        }
9869        for (int i = 0; i < tmpFilesList.length; i++) {
9870            final File tmpFile = new File(directory, tmpFilesList[i]);
9871            tmpFile.delete();
9872        }
9873    }
9874
9875    private File createTempPackageFile(File installDir) {
9876        File tmpPackageFile;
9877        try {
9878            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9879        } catch (IOException e) {
9880            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9881            return null;
9882        }
9883        try {
9884            FileUtils.setPermissions(
9885                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9886                    -1, -1);
9887            if (!SELinux.restorecon(tmpPackageFile)) {
9888                return null;
9889            }
9890        } catch (IOException e) {
9891            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9892            return null;
9893        }
9894        return tmpPackageFile;
9895    }
9896
9897    @Override
9898    public void deletePackageAsUser(final String packageName,
9899                                    final IPackageDeleteObserver observer,
9900                                    final int userId, final int flags) {
9901        mContext.enforceCallingOrSelfPermission(
9902                android.Manifest.permission.DELETE_PACKAGES, null);
9903        final int uid = Binder.getCallingUid();
9904        if (UserHandle.getUserId(uid) != userId) {
9905            mContext.enforceCallingPermission(
9906                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9907                    "deletePackage for user " + userId);
9908        }
9909        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9910            try {
9911                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9912            } catch (RemoteException re) {
9913            }
9914            return;
9915        }
9916
9917        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9918        // Queue up an async operation since the package deletion may take a little while.
9919        mHandler.post(new Runnable() {
9920            public void run() {
9921                mHandler.removeCallbacks(this);
9922                final int returnCode = deletePackageX(packageName, userId, flags);
9923                if (observer != null) {
9924                    try {
9925                        observer.packageDeleted(packageName, returnCode);
9926                    } catch (RemoteException e) {
9927                        Log.i(TAG, "Observer no longer exists.");
9928                    } //end catch
9929                } //end if
9930            } //end run
9931        });
9932    }
9933
9934    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9935        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9936                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9937        try {
9938            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9939                    || dpm.isDeviceOwner(packageName))) {
9940                return true;
9941            }
9942        } catch (RemoteException e) {
9943        }
9944        return false;
9945    }
9946
9947    /**
9948     *  This method is an internal method that could be get invoked either
9949     *  to delete an installed package or to clean up a failed installation.
9950     *  After deleting an installed package, a broadcast is sent to notify any
9951     *  listeners that the package has been installed. For cleaning up a failed
9952     *  installation, the broadcast is not necessary since the package's
9953     *  installation wouldn't have sent the initial broadcast either
9954     *  The key steps in deleting a package are
9955     *  deleting the package information in internal structures like mPackages,
9956     *  deleting the packages base directories through installd
9957     *  updating mSettings to reflect current status
9958     *  persisting settings for later use
9959     *  sending a broadcast if necessary
9960     */
9961    private int deletePackageX(String packageName, int userId, int flags) {
9962        final PackageRemovedInfo info = new PackageRemovedInfo();
9963        final boolean res;
9964
9965        if (isPackageDeviceAdmin(packageName, userId)) {
9966            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9967            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9968        }
9969
9970        boolean removedForAllUsers = false;
9971        boolean systemUpdate = false;
9972
9973        // for the uninstall-updates case and restricted profiles, remember the per-
9974        // userhandle installed state
9975        int[] allUsers;
9976        boolean[] perUserInstalled;
9977        synchronized (mPackages) {
9978            PackageSetting ps = mSettings.mPackages.get(packageName);
9979            allUsers = sUserManager.getUserIds();
9980            perUserInstalled = new boolean[allUsers.length];
9981            for (int i = 0; i < allUsers.length; i++) {
9982                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9983            }
9984        }
9985
9986        synchronized (mInstallLock) {
9987            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9988            res = deletePackageLI(packageName,
9989                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9990                            ? UserHandle.ALL : new UserHandle(userId),
9991                    true, allUsers, perUserInstalled,
9992                    flags | REMOVE_CHATTY, info, true);
9993            systemUpdate = info.isRemovedPackageSystemUpdate;
9994            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9995                removedForAllUsers = true;
9996            }
9997            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9998                    + " removedForAllUsers=" + removedForAllUsers);
9999        }
10000
10001        if (res) {
10002            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10003
10004            // If the removed package was a system update, the old system package
10005            // was re-enabled; we need to broadcast this information
10006            if (systemUpdate) {
10007                Bundle extras = new Bundle(1);
10008                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10009                        ? info.removedAppId : info.uid);
10010                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10011
10012                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10013                        extras, null, null, null);
10014                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10015                        extras, null, null, null);
10016                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10017                        null, packageName, null, null);
10018            }
10019        }
10020        // Force a gc here.
10021        Runtime.getRuntime().gc();
10022        // Delete the resources here after sending the broadcast to let
10023        // other processes clean up before deleting resources.
10024        if (info.args != null) {
10025            synchronized (mInstallLock) {
10026                info.args.doPostDeleteLI(true);
10027            }
10028        }
10029
10030        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10031    }
10032
10033    static class PackageRemovedInfo {
10034        String removedPackage;
10035        int uid = -1;
10036        int removedAppId = -1;
10037        int[] removedUsers = null;
10038        boolean isRemovedPackageSystemUpdate = false;
10039        // Clean up resources deleted packages.
10040        InstallArgs args = null;
10041
10042        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10043            Bundle extras = new Bundle(1);
10044            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10045            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10046            if (replacing) {
10047                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10048            }
10049            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10050            if (removedPackage != null) {
10051                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10052                        extras, null, null, removedUsers);
10053                if (fullRemove && !replacing) {
10054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10055                            extras, null, null, removedUsers);
10056                }
10057            }
10058            if (removedAppId >= 0) {
10059                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10060                        removedUsers);
10061            }
10062        }
10063    }
10064
10065    /*
10066     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10067     * flag is not set, the data directory is removed as well.
10068     * make sure this flag is set for partially installed apps. If not its meaningless to
10069     * delete a partially installed application.
10070     */
10071    private void removePackageDataLI(PackageSetting ps,
10072            int[] allUserHandles, boolean[] perUserInstalled,
10073            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10074        String packageName = ps.name;
10075        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10076        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10077        // Retrieve object to delete permissions for shared user later on
10078        final PackageSetting deletedPs;
10079        // reader
10080        synchronized (mPackages) {
10081            deletedPs = mSettings.mPackages.get(packageName);
10082            if (outInfo != null) {
10083                outInfo.removedPackage = packageName;
10084                outInfo.removedUsers = deletedPs != null
10085                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10086                        : null;
10087            }
10088        }
10089        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10090            removeDataDirsLI(packageName);
10091            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10092        }
10093        // writer
10094        synchronized (mPackages) {
10095            if (deletedPs != null) {
10096                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10097                    if (outInfo != null) {
10098                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10099                    }
10100                    if (deletedPs != null) {
10101                        updatePermissionsLPw(deletedPs.name, null, 0);
10102                        if (deletedPs.sharedUser != null) {
10103                            // remove permissions associated with package
10104                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10105                        }
10106                    }
10107                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10108                }
10109                // make sure to preserve per-user disabled state if this removal was just
10110                // a downgrade of a system app to the factory package
10111                if (allUserHandles != null && perUserInstalled != null) {
10112                    if (DEBUG_REMOVE) {
10113                        Slog.d(TAG, "Propagating install state across downgrade");
10114                    }
10115                    for (int i = 0; i < allUserHandles.length; i++) {
10116                        if (DEBUG_REMOVE) {
10117                            Slog.d(TAG, "    user " + allUserHandles[i]
10118                                    + " => " + perUserInstalled[i]);
10119                        }
10120                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10121                    }
10122                }
10123            }
10124            // can downgrade to reader
10125            if (writeSettings) {
10126                // Save settings now
10127                mSettings.writeLPr();
10128            }
10129        }
10130        if (outInfo != null) {
10131            // A user ID was deleted here. Go through all users and remove it
10132            // from KeyStore.
10133            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10134        }
10135    }
10136
10137    static boolean locationIsPrivileged(File path) {
10138        try {
10139            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10140                    .getCanonicalPath();
10141            return path.getCanonicalPath().startsWith(privilegedAppDir);
10142        } catch (IOException e) {
10143            Slog.e(TAG, "Unable to access code path " + path);
10144        }
10145        return false;
10146    }
10147
10148    /*
10149     * Tries to delete system package.
10150     */
10151    private boolean deleteSystemPackageLI(PackageSetting newPs,
10152            int[] allUserHandles, boolean[] perUserInstalled,
10153            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10154        final boolean applyUserRestrictions
10155                = (allUserHandles != null) && (perUserInstalled != null);
10156        PackageSetting disabledPs = null;
10157        // Confirm if the system package has been updated
10158        // An updated system app can be deleted. This will also have to restore
10159        // the system pkg from system partition
10160        // reader
10161        synchronized (mPackages) {
10162            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10163        }
10164        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10165                + " disabledPs=" + disabledPs);
10166        if (disabledPs == null) {
10167            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10168            return false;
10169        } else if (DEBUG_REMOVE) {
10170            Slog.d(TAG, "Deleting system pkg from data partition");
10171        }
10172        if (DEBUG_REMOVE) {
10173            if (applyUserRestrictions) {
10174                Slog.d(TAG, "Remembering install states:");
10175                for (int i = 0; i < allUserHandles.length; i++) {
10176                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10177                }
10178            }
10179        }
10180        // Delete the updated package
10181        outInfo.isRemovedPackageSystemUpdate = true;
10182        if (disabledPs.versionCode < newPs.versionCode) {
10183            // Delete data for downgrades
10184            flags &= ~PackageManager.DELETE_KEEP_DATA;
10185        } else {
10186            // Preserve data by setting flag
10187            flags |= PackageManager.DELETE_KEEP_DATA;
10188        }
10189        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10190                allUserHandles, perUserInstalled, outInfo, writeSettings);
10191        if (!ret) {
10192            return false;
10193        }
10194        // writer
10195        synchronized (mPackages) {
10196            // Reinstate the old system package
10197            mSettings.enableSystemPackageLPw(newPs.name);
10198            // Remove any native libraries from the upgraded package.
10199            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10200        }
10201        // Install the system package
10202        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10203        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10204        if (locationIsPrivileged(disabledPs.codePath)) {
10205            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10206        }
10207        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10208                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10209
10210        if (newPkg == null) {
10211            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10212                    + " with error:" + mLastScanError);
10213            return false;
10214        }
10215        // writer
10216        synchronized (mPackages) {
10217            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10218            setInternalAppNativeLibraryPath(newPkg, ps);
10219            updatePermissionsLPw(newPkg.packageName, newPkg,
10220                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10221            if (applyUserRestrictions) {
10222                if (DEBUG_REMOVE) {
10223                    Slog.d(TAG, "Propagating install state across reinstall");
10224                }
10225                for (int i = 0; i < allUserHandles.length; i++) {
10226                    if (DEBUG_REMOVE) {
10227                        Slog.d(TAG, "    user " + allUserHandles[i]
10228                                + " => " + perUserInstalled[i]);
10229                    }
10230                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10231                }
10232                // Regardless of writeSettings we need to ensure that this restriction
10233                // state propagation is persisted
10234                mSettings.writeAllUsersPackageRestrictionsLPr();
10235            }
10236            // can downgrade to reader here
10237            if (writeSettings) {
10238                mSettings.writeLPr();
10239            }
10240        }
10241        return true;
10242    }
10243
10244    private boolean deleteInstalledPackageLI(PackageSetting ps,
10245            boolean deleteCodeAndResources, int flags,
10246            int[] allUserHandles, boolean[] perUserInstalled,
10247            PackageRemovedInfo outInfo, boolean writeSettings) {
10248        if (outInfo != null) {
10249            outInfo.uid = ps.appId;
10250        }
10251
10252        // Delete package data from internal structures and also remove data if flag is set
10253        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10254
10255        // Delete application code and resources
10256        if (deleteCodeAndResources && (outInfo != null)) {
10257            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10258                    ps.resourcePathString, ps.nativeLibraryPathString,
10259                    getAppInstructionSetFromSettings(ps));
10260        }
10261        return true;
10262    }
10263
10264    /*
10265     * This method handles package deletion in general
10266     */
10267    private boolean deletePackageLI(String packageName, UserHandle user,
10268            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10269            int flags, PackageRemovedInfo outInfo,
10270            boolean writeSettings) {
10271        if (packageName == null) {
10272            Slog.w(TAG, "Attempt to delete null packageName.");
10273            return false;
10274        }
10275        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10276        PackageSetting ps;
10277        boolean dataOnly = false;
10278        int removeUser = -1;
10279        int appId = -1;
10280        synchronized (mPackages) {
10281            ps = mSettings.mPackages.get(packageName);
10282            if (ps == null) {
10283                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10284                return false;
10285            }
10286            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10287                    && user.getIdentifier() != UserHandle.USER_ALL) {
10288                // The caller is asking that the package only be deleted for a single
10289                // user.  To do this, we just mark its uninstalled state and delete
10290                // its data.  If this is a system app, we only allow this to happen if
10291                // they have set the special DELETE_SYSTEM_APP which requests different
10292                // semantics than normal for uninstalling system apps.
10293                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10294                ps.setUserState(user.getIdentifier(),
10295                        COMPONENT_ENABLED_STATE_DEFAULT,
10296                        false, //installed
10297                        true,  //stopped
10298                        true,  //notLaunched
10299                        false, //blocked
10300                        null, null, null);
10301                if (!isSystemApp(ps)) {
10302                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10303                        // Other user still have this package installed, so all
10304                        // we need to do is clear this user's data and save that
10305                        // it is uninstalled.
10306                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10307                        removeUser = user.getIdentifier();
10308                        appId = ps.appId;
10309                        mSettings.writePackageRestrictionsLPr(removeUser);
10310                    } else {
10311                        // We need to set it back to 'installed' so the uninstall
10312                        // broadcasts will be sent correctly.
10313                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10314                        ps.setInstalled(true, user.getIdentifier());
10315                    }
10316                } else {
10317                    // This is a system app, so we assume that the
10318                    // other users still have this package installed, so all
10319                    // we need to do is clear this user's data and save that
10320                    // it is uninstalled.
10321                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10322                    removeUser = user.getIdentifier();
10323                    appId = ps.appId;
10324                    mSettings.writePackageRestrictionsLPr(removeUser);
10325                }
10326            }
10327        }
10328
10329        if (removeUser >= 0) {
10330            // From above, we determined that we are deleting this only
10331            // for a single user.  Continue the work here.
10332            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10333            if (outInfo != null) {
10334                outInfo.removedPackage = packageName;
10335                outInfo.removedAppId = appId;
10336                outInfo.removedUsers = new int[] {removeUser};
10337            }
10338            mInstaller.clearUserData(packageName, removeUser);
10339            removeKeystoreDataIfNeeded(removeUser, appId);
10340            schedulePackageCleaning(packageName, removeUser, false);
10341            return true;
10342        }
10343
10344        if (dataOnly) {
10345            // Delete application data first
10346            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10347            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10348            return true;
10349        }
10350
10351        boolean ret = false;
10352        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10353        if (isSystemApp(ps)) {
10354            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10355            // When an updated system application is deleted we delete the existing resources as well and
10356            // fall back to existing code in system partition
10357            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10358                    flags, outInfo, writeSettings);
10359        } else {
10360            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10361            // Kill application pre-emptively especially for apps on sd.
10362            killApplication(packageName, ps.appId, "uninstall pkg");
10363            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10364                    allUserHandles, perUserInstalled,
10365                    outInfo, writeSettings);
10366        }
10367
10368        return ret;
10369    }
10370
10371    private final class ClearStorageConnection implements ServiceConnection {
10372        IMediaContainerService mContainerService;
10373
10374        @Override
10375        public void onServiceConnected(ComponentName name, IBinder service) {
10376            synchronized (this) {
10377                mContainerService = IMediaContainerService.Stub.asInterface(service);
10378                notifyAll();
10379            }
10380        }
10381
10382        @Override
10383        public void onServiceDisconnected(ComponentName name) {
10384        }
10385    }
10386
10387    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10388        final boolean mounted;
10389        if (Environment.isExternalStorageEmulated()) {
10390            mounted = true;
10391        } else {
10392            final String status = Environment.getExternalStorageState();
10393
10394            mounted = status.equals(Environment.MEDIA_MOUNTED)
10395                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10396        }
10397
10398        if (!mounted) {
10399            return;
10400        }
10401
10402        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10403        int[] users;
10404        if (userId == UserHandle.USER_ALL) {
10405            users = sUserManager.getUserIds();
10406        } else {
10407            users = new int[] { userId };
10408        }
10409        final ClearStorageConnection conn = new ClearStorageConnection();
10410        if (mContext.bindServiceAsUser(
10411                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10412            try {
10413                for (int curUser : users) {
10414                    long timeout = SystemClock.uptimeMillis() + 5000;
10415                    synchronized (conn) {
10416                        long now = SystemClock.uptimeMillis();
10417                        while (conn.mContainerService == null && now < timeout) {
10418                            try {
10419                                conn.wait(timeout - now);
10420                            } catch (InterruptedException e) {
10421                            }
10422                        }
10423                    }
10424                    if (conn.mContainerService == null) {
10425                        return;
10426                    }
10427
10428                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10429                    clearDirectory(conn.mContainerService,
10430                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10431                    if (allData) {
10432                        clearDirectory(conn.mContainerService,
10433                                userEnv.buildExternalStorageAppDataDirs(packageName));
10434                        clearDirectory(conn.mContainerService,
10435                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10436                    }
10437                }
10438            } finally {
10439                mContext.unbindService(conn);
10440            }
10441        }
10442    }
10443
10444    @Override
10445    public void clearApplicationUserData(final String packageName,
10446            final IPackageDataObserver observer, final int userId) {
10447        mContext.enforceCallingOrSelfPermission(
10448                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10449        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10450        // Queue up an async operation since the package deletion may take a little while.
10451        mHandler.post(new Runnable() {
10452            public void run() {
10453                mHandler.removeCallbacks(this);
10454                final boolean succeeded;
10455                synchronized (mInstallLock) {
10456                    succeeded = clearApplicationUserDataLI(packageName, userId);
10457                }
10458                clearExternalStorageDataSync(packageName, userId, true);
10459                if (succeeded) {
10460                    // invoke DeviceStorageMonitor's update method to clear any notifications
10461                    DeviceStorageMonitorInternal
10462                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10463                    if (dsm != null) {
10464                        dsm.checkMemory();
10465                    }
10466                }
10467                if(observer != null) {
10468                    try {
10469                        observer.onRemoveCompleted(packageName, succeeded);
10470                    } catch (RemoteException e) {
10471                        Log.i(TAG, "Observer no longer exists.");
10472                    }
10473                } //end if observer
10474            } //end run
10475        });
10476    }
10477
10478    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10479        if (packageName == null) {
10480            Slog.w(TAG, "Attempt to delete null packageName.");
10481            return false;
10482        }
10483        PackageParser.Package p;
10484        boolean dataOnly = false;
10485        final int appId;
10486        synchronized (mPackages) {
10487            p = mPackages.get(packageName);
10488            if (p == null) {
10489                dataOnly = true;
10490                PackageSetting ps = mSettings.mPackages.get(packageName);
10491                if ((ps == null) || (ps.pkg == null)) {
10492                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10493                    return false;
10494                }
10495                p = ps.pkg;
10496            }
10497            if (!dataOnly) {
10498                // need to check this only for fully installed applications
10499                if (p == null) {
10500                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10501                    return false;
10502                }
10503                final ApplicationInfo applicationInfo = p.applicationInfo;
10504                if (applicationInfo == null) {
10505                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10506                    return false;
10507                }
10508            }
10509            if (p != null && p.applicationInfo != null) {
10510                appId = p.applicationInfo.uid;
10511            } else {
10512                appId = -1;
10513            }
10514        }
10515        int retCode = mInstaller.clearUserData(packageName, userId);
10516        if (retCode < 0) {
10517            Slog.w(TAG, "Couldn't remove cache files for package: "
10518                    + packageName);
10519            return false;
10520        }
10521        removeKeystoreDataIfNeeded(userId, appId);
10522        return true;
10523    }
10524
10525    /**
10526     * Remove entries from the keystore daemon. Will only remove it if the
10527     * {@code appId} is valid.
10528     */
10529    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10530        if (appId < 0) {
10531            return;
10532        }
10533
10534        final KeyStore keyStore = KeyStore.getInstance();
10535        if (keyStore != null) {
10536            if (userId == UserHandle.USER_ALL) {
10537                for (final int individual : sUserManager.getUserIds()) {
10538                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10539                }
10540            } else {
10541                keyStore.clearUid(UserHandle.getUid(userId, appId));
10542            }
10543        } else {
10544            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10545        }
10546    }
10547
10548    @Override
10549    public void deleteApplicationCacheFiles(final String packageName,
10550            final IPackageDataObserver observer) {
10551        mContext.enforceCallingOrSelfPermission(
10552                android.Manifest.permission.DELETE_CACHE_FILES, null);
10553        // Queue up an async operation since the package deletion may take a little while.
10554        final int userId = UserHandle.getCallingUserId();
10555        mHandler.post(new Runnable() {
10556            public void run() {
10557                mHandler.removeCallbacks(this);
10558                final boolean succeded;
10559                synchronized (mInstallLock) {
10560                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10561                }
10562                clearExternalStorageDataSync(packageName, userId, false);
10563                if(observer != null) {
10564                    try {
10565                        observer.onRemoveCompleted(packageName, succeded);
10566                    } catch (RemoteException e) {
10567                        Log.i(TAG, "Observer no longer exists.");
10568                    }
10569                } //end if observer
10570            } //end run
10571        });
10572    }
10573
10574    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10575        if (packageName == null) {
10576            Slog.w(TAG, "Attempt to delete null packageName.");
10577            return false;
10578        }
10579        PackageParser.Package p;
10580        synchronized (mPackages) {
10581            p = mPackages.get(packageName);
10582        }
10583        if (p == null) {
10584            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10585            return false;
10586        }
10587        final ApplicationInfo applicationInfo = p.applicationInfo;
10588        if (applicationInfo == null) {
10589            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10590            return false;
10591        }
10592        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10593        if (retCode < 0) {
10594            Slog.w(TAG, "Couldn't remove cache files for package: "
10595                       + packageName + " u" + userId);
10596            return false;
10597        }
10598        return true;
10599    }
10600
10601    @Override
10602    public void getPackageSizeInfo(final String packageName, int userHandle,
10603            final IPackageStatsObserver observer) {
10604        mContext.enforceCallingOrSelfPermission(
10605                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10606
10607        PackageStats stats = new PackageStats(packageName, userHandle);
10608
10609        /*
10610         * Queue up an async operation since the package measurement may take a
10611         * little while.
10612         */
10613        Message msg = mHandler.obtainMessage(INIT_COPY);
10614        msg.obj = new MeasureParams(stats, observer);
10615        mHandler.sendMessage(msg);
10616    }
10617
10618    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10619            PackageStats pStats) {
10620        if (packageName == null) {
10621            Slog.w(TAG, "Attempt to get size of null packageName.");
10622            return false;
10623        }
10624        PackageParser.Package p;
10625        boolean dataOnly = false;
10626        String libDirPath = null;
10627        String asecPath = null;
10628        PackageSetting ps = null;
10629        synchronized (mPackages) {
10630            p = mPackages.get(packageName);
10631            ps = mSettings.mPackages.get(packageName);
10632            if(p == null) {
10633                dataOnly = true;
10634                if((ps == null) || (ps.pkg == null)) {
10635                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10636                    return false;
10637                }
10638                p = ps.pkg;
10639            }
10640            if (ps != null) {
10641                libDirPath = ps.nativeLibraryPathString;
10642            }
10643            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10644                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10645                if (secureContainerId != null) {
10646                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10647                }
10648            }
10649        }
10650        String publicSrcDir = null;
10651        if(!dataOnly) {
10652            final ApplicationInfo applicationInfo = p.applicationInfo;
10653            if (applicationInfo == null) {
10654                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10655                return false;
10656            }
10657            if (isForwardLocked(p)) {
10658                publicSrcDir = applicationInfo.publicSourceDir;
10659            }
10660        }
10661        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10662                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10663                pStats);
10664        if (res < 0) {
10665            return false;
10666        }
10667
10668        // Fix-up for forward-locked applications in ASEC containers.
10669        if (!isExternal(p)) {
10670            pStats.codeSize += pStats.externalCodeSize;
10671            pStats.externalCodeSize = 0L;
10672        }
10673
10674        return true;
10675    }
10676
10677
10678    @Override
10679    public void addPackageToPreferred(String packageName) {
10680        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10681    }
10682
10683    @Override
10684    public void removePackageFromPreferred(String packageName) {
10685        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10686    }
10687
10688    @Override
10689    public List<PackageInfo> getPreferredPackages(int flags) {
10690        return new ArrayList<PackageInfo>();
10691    }
10692
10693    private int getUidTargetSdkVersionLockedLPr(int uid) {
10694        Object obj = mSettings.getUserIdLPr(uid);
10695        if (obj instanceof SharedUserSetting) {
10696            final SharedUserSetting sus = (SharedUserSetting) obj;
10697            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10698            final Iterator<PackageSetting> it = sus.packages.iterator();
10699            while (it.hasNext()) {
10700                final PackageSetting ps = it.next();
10701                if (ps.pkg != null) {
10702                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10703                    if (v < vers) vers = v;
10704                }
10705            }
10706            return vers;
10707        } else if (obj instanceof PackageSetting) {
10708            final PackageSetting ps = (PackageSetting) obj;
10709            if (ps.pkg != null) {
10710                return ps.pkg.applicationInfo.targetSdkVersion;
10711            }
10712        }
10713        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10714    }
10715
10716    @Override
10717    public void addPreferredActivity(IntentFilter filter, int match,
10718            ComponentName[] set, ComponentName activity, int userId) {
10719        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10720    }
10721
10722    private void addPreferredActivityInternal(IntentFilter filter, int match,
10723            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10724        // writer
10725        int callingUid = Binder.getCallingUid();
10726        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10727        if (filter.countActions() == 0) {
10728            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10729            return;
10730        }
10731        synchronized (mPackages) {
10732            if (mContext.checkCallingOrSelfPermission(
10733                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10734                    != PackageManager.PERMISSION_GRANTED) {
10735                if (getUidTargetSdkVersionLockedLPr(callingUid)
10736                        < Build.VERSION_CODES.FROYO) {
10737                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10738                            + callingUid);
10739                    return;
10740                }
10741                mContext.enforceCallingOrSelfPermission(
10742                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10743            }
10744
10745            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10746            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10747            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10748                    new PreferredActivity(filter, match, set, activity, always));
10749            mSettings.writePackageRestrictionsLPr(userId);
10750        }
10751    }
10752
10753    @Override
10754    public void replacePreferredActivity(IntentFilter filter, int match,
10755            ComponentName[] set, ComponentName activity) {
10756        if (filter.countActions() != 1) {
10757            throw new IllegalArgumentException(
10758                    "replacePreferredActivity expects filter to have only 1 action.");
10759        }
10760        if (filter.countDataAuthorities() != 0
10761                || filter.countDataPaths() != 0
10762                || filter.countDataSchemes() > 1
10763                || filter.countDataTypes() != 0) {
10764            throw new IllegalArgumentException(
10765                    "replacePreferredActivity expects filter to have no data authorities, " +
10766                    "paths, or types; and at most one scheme.");
10767        }
10768        synchronized (mPackages) {
10769            if (mContext.checkCallingOrSelfPermission(
10770                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10771                    != PackageManager.PERMISSION_GRANTED) {
10772                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10773                        < Build.VERSION_CODES.FROYO) {
10774                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10775                            + Binder.getCallingUid());
10776                    return;
10777                }
10778                mContext.enforceCallingOrSelfPermission(
10779                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10780            }
10781
10782            final int callingUserId = UserHandle.getCallingUserId();
10783            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10784            if (pir != null) {
10785                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10786                if (filter.countDataSchemes() == 1) {
10787                    Uri.Builder builder = new Uri.Builder();
10788                    builder.scheme(filter.getDataScheme(0));
10789                    intent.setData(builder.build());
10790                }
10791                List<PreferredActivity> matches = pir.queryIntent(
10792                        intent, null, true, callingUserId);
10793                if (DEBUG_PREFERRED) {
10794                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10795                }
10796                for (int i = 0; i < matches.size(); i++) {
10797                    PreferredActivity pa = matches.get(i);
10798                    if (DEBUG_PREFERRED) {
10799                        Slog.i(TAG, "Removing preferred activity "
10800                                + pa.mPref.mComponent + ":");
10801                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10802                    }
10803                    pir.removeFilter(pa);
10804                }
10805            }
10806            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10807        }
10808    }
10809
10810    @Override
10811    public void clearPackagePreferredActivities(String packageName) {
10812        final int uid = Binder.getCallingUid();
10813        // writer
10814        synchronized (mPackages) {
10815            PackageParser.Package pkg = mPackages.get(packageName);
10816            if (pkg == null || pkg.applicationInfo.uid != uid) {
10817                if (mContext.checkCallingOrSelfPermission(
10818                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10819                        != PackageManager.PERMISSION_GRANTED) {
10820                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10821                            < Build.VERSION_CODES.FROYO) {
10822                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10823                                + Binder.getCallingUid());
10824                        return;
10825                    }
10826                    mContext.enforceCallingOrSelfPermission(
10827                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10828                }
10829            }
10830
10831            int user = UserHandle.getCallingUserId();
10832            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10833                mSettings.writePackageRestrictionsLPr(user);
10834                scheduleWriteSettingsLocked();
10835            }
10836        }
10837    }
10838
10839    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10840    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10841        ArrayList<PreferredActivity> removed = null;
10842        boolean changed = false;
10843        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10844            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10845            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10846            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10847                continue;
10848            }
10849            Iterator<PreferredActivity> it = pir.filterIterator();
10850            while (it.hasNext()) {
10851                PreferredActivity pa = it.next();
10852                // Mark entry for removal only if it matches the package name
10853                // and the entry is of type "always".
10854                if (packageName == null ||
10855                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10856                                && pa.mPref.mAlways)) {
10857                    if (removed == null) {
10858                        removed = new ArrayList<PreferredActivity>();
10859                    }
10860                    removed.add(pa);
10861                }
10862            }
10863            if (removed != null) {
10864                for (int j=0; j<removed.size(); j++) {
10865                    PreferredActivity pa = removed.get(j);
10866                    pir.removeFilter(pa);
10867                }
10868                changed = true;
10869            }
10870        }
10871        return changed;
10872    }
10873
10874    @Override
10875    public void resetPreferredActivities(int userId) {
10876        mContext.enforceCallingOrSelfPermission(
10877                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10878        // writer
10879        synchronized (mPackages) {
10880            int user = UserHandle.getCallingUserId();
10881            clearPackagePreferredActivitiesLPw(null, user);
10882            mSettings.readDefaultPreferredAppsLPw(this, user);
10883            mSettings.writePackageRestrictionsLPr(user);
10884            scheduleWriteSettingsLocked();
10885        }
10886    }
10887
10888    @Override
10889    public int getPreferredActivities(List<IntentFilter> outFilters,
10890            List<ComponentName> outActivities, String packageName) {
10891
10892        int num = 0;
10893        final int userId = UserHandle.getCallingUserId();
10894        // reader
10895        synchronized (mPackages) {
10896            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10897            if (pir != null) {
10898                final Iterator<PreferredActivity> it = pir.filterIterator();
10899                while (it.hasNext()) {
10900                    final PreferredActivity pa = it.next();
10901                    if (packageName == null
10902                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10903                                    && pa.mPref.mAlways)) {
10904                        if (outFilters != null) {
10905                            outFilters.add(new IntentFilter(pa));
10906                        }
10907                        if (outActivities != null) {
10908                            outActivities.add(pa.mPref.mComponent);
10909                        }
10910                    }
10911                }
10912            }
10913        }
10914
10915        return num;
10916    }
10917
10918    @Override
10919    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10920        Intent intent = new Intent(Intent.ACTION_MAIN);
10921        intent.addCategory(Intent.CATEGORY_HOME);
10922
10923        final int callingUserId = UserHandle.getCallingUserId();
10924        List<ResolveInfo> list = queryIntentActivities(intent, null,
10925                PackageManager.GET_META_DATA, callingUserId);
10926        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10927                true, false, false, callingUserId);
10928
10929        allHomeCandidates.clear();
10930        if (list != null) {
10931            for (ResolveInfo ri : list) {
10932                allHomeCandidates.add(ri);
10933            }
10934        }
10935        return (preferred == null || preferred.activityInfo == null)
10936                ? null
10937                : new ComponentName(preferred.activityInfo.packageName,
10938                        preferred.activityInfo.name);
10939    }
10940
10941    @Override
10942    public void setApplicationEnabledSetting(String appPackageName,
10943            int newState, int flags, int userId, String callingPackage) {
10944        if (!sUserManager.exists(userId)) return;
10945        if (callingPackage == null) {
10946            callingPackage = Integer.toString(Binder.getCallingUid());
10947        }
10948        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10949    }
10950
10951    @Override
10952    public void setComponentEnabledSetting(ComponentName componentName,
10953            int newState, int flags, int userId) {
10954        if (!sUserManager.exists(userId)) return;
10955        setEnabledSetting(componentName.getPackageName(),
10956                componentName.getClassName(), newState, flags, userId, null);
10957    }
10958
10959    private void setEnabledSetting(final String packageName, String className, int newState,
10960            final int flags, int userId, String callingPackage) {
10961        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10962              || newState == COMPONENT_ENABLED_STATE_ENABLED
10963              || newState == COMPONENT_ENABLED_STATE_DISABLED
10964              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10965              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10966            throw new IllegalArgumentException("Invalid new component state: "
10967                    + newState);
10968        }
10969        PackageSetting pkgSetting;
10970        final int uid = Binder.getCallingUid();
10971        final int permission = mContext.checkCallingOrSelfPermission(
10972                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10973        enforceCrossUserPermission(uid, userId, false, "set enabled");
10974        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10975        boolean sendNow = false;
10976        boolean isApp = (className == null);
10977        String componentName = isApp ? packageName : className;
10978        int packageUid = -1;
10979        ArrayList<String> components;
10980
10981        // writer
10982        synchronized (mPackages) {
10983            pkgSetting = mSettings.mPackages.get(packageName);
10984            if (pkgSetting == null) {
10985                if (className == null) {
10986                    throw new IllegalArgumentException(
10987                            "Unknown package: " + packageName);
10988                }
10989                throw new IllegalArgumentException(
10990                        "Unknown component: " + packageName
10991                        + "/" + className);
10992            }
10993            // Allow root and verify that userId is not being specified by a different user
10994            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10995                throw new SecurityException(
10996                        "Permission Denial: attempt to change component state from pid="
10997                        + Binder.getCallingPid()
10998                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10999            }
11000            if (className == null) {
11001                // We're dealing with an application/package level state change
11002                if (pkgSetting.getEnabled(userId) == newState) {
11003                    // Nothing to do
11004                    return;
11005                }
11006                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11007                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11008                    // Don't care about who enables an app.
11009                    callingPackage = null;
11010                }
11011                pkgSetting.setEnabled(newState, userId, callingPackage);
11012                // pkgSetting.pkg.mSetEnabled = newState;
11013            } else {
11014                // We're dealing with a component level state change
11015                // First, verify that this is a valid class name.
11016                PackageParser.Package pkg = pkgSetting.pkg;
11017                if (pkg == null || !pkg.hasComponentClassName(className)) {
11018                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11019                        throw new IllegalArgumentException("Component class " + className
11020                                + " does not exist in " + packageName);
11021                    } else {
11022                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11023                                + className + " does not exist in " + packageName);
11024                    }
11025                }
11026                switch (newState) {
11027                case COMPONENT_ENABLED_STATE_ENABLED:
11028                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11029                        return;
11030                    }
11031                    break;
11032                case COMPONENT_ENABLED_STATE_DISABLED:
11033                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11034                        return;
11035                    }
11036                    break;
11037                case COMPONENT_ENABLED_STATE_DEFAULT:
11038                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11039                        return;
11040                    }
11041                    break;
11042                default:
11043                    Slog.e(TAG, "Invalid new component state: " + newState);
11044                    return;
11045                }
11046            }
11047            mSettings.writePackageRestrictionsLPr(userId);
11048            components = mPendingBroadcasts.get(userId, packageName);
11049            final boolean newPackage = components == null;
11050            if (newPackage) {
11051                components = new ArrayList<String>();
11052            }
11053            if (!components.contains(componentName)) {
11054                components.add(componentName);
11055            }
11056            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11057                sendNow = true;
11058                // Purge entry from pending broadcast list if another one exists already
11059                // since we are sending one right away.
11060                mPendingBroadcasts.remove(userId, packageName);
11061            } else {
11062                if (newPackage) {
11063                    mPendingBroadcasts.put(userId, packageName, components);
11064                }
11065                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11066                    // Schedule a message
11067                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11068                }
11069            }
11070        }
11071
11072        long callingId = Binder.clearCallingIdentity();
11073        try {
11074            if (sendNow) {
11075                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11076                sendPackageChangedBroadcast(packageName,
11077                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11078            }
11079        } finally {
11080            Binder.restoreCallingIdentity(callingId);
11081        }
11082    }
11083
11084    private void sendPackageChangedBroadcast(String packageName,
11085            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11086        if (DEBUG_INSTALL)
11087            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11088                    + componentNames);
11089        Bundle extras = new Bundle(4);
11090        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11091        String nameList[] = new String[componentNames.size()];
11092        componentNames.toArray(nameList);
11093        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11094        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11095        extras.putInt(Intent.EXTRA_UID, packageUid);
11096        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11097                new int[] {UserHandle.getUserId(packageUid)});
11098    }
11099
11100    @Override
11101    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11102        if (!sUserManager.exists(userId)) return;
11103        final int uid = Binder.getCallingUid();
11104        final int permission = mContext.checkCallingOrSelfPermission(
11105                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11106        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11107        enforceCrossUserPermission(uid, userId, true, "stop package");
11108        // writer
11109        synchronized (mPackages) {
11110            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11111                    uid, userId)) {
11112                scheduleWritePackageRestrictionsLocked(userId);
11113            }
11114        }
11115    }
11116
11117    @Override
11118    public String getInstallerPackageName(String packageName) {
11119        // reader
11120        synchronized (mPackages) {
11121            return mSettings.getInstallerPackageNameLPr(packageName);
11122        }
11123    }
11124
11125    @Override
11126    public int getApplicationEnabledSetting(String packageName, int userId) {
11127        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11128        int uid = Binder.getCallingUid();
11129        enforceCrossUserPermission(uid, userId, false, "get enabled");
11130        // reader
11131        synchronized (mPackages) {
11132            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11133        }
11134    }
11135
11136    @Override
11137    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11138        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11139        int uid = Binder.getCallingUid();
11140        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11141        // reader
11142        synchronized (mPackages) {
11143            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11144        }
11145    }
11146
11147    @Override
11148    public void enterSafeMode() {
11149        enforceSystemOrRoot("Only the system can request entering safe mode");
11150
11151        if (!mSystemReady) {
11152            mSafeMode = true;
11153        }
11154    }
11155
11156    @Override
11157    public void systemReady() {
11158        mSystemReady = true;
11159
11160        // Read the compatibilty setting when the system is ready.
11161        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11162                mContext.getContentResolver(),
11163                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11164        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11165        if (DEBUG_SETTINGS) {
11166            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11167        }
11168
11169        synchronized (mPackages) {
11170            // Verify that all of the preferred activity components actually
11171            // exist.  It is possible for applications to be updated and at
11172            // that point remove a previously declared activity component that
11173            // had been set as a preferred activity.  We try to clean this up
11174            // the next time we encounter that preferred activity, but it is
11175            // possible for the user flow to never be able to return to that
11176            // situation so here we do a sanity check to make sure we haven't
11177            // left any junk around.
11178            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11179            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11180                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11181                removed.clear();
11182                for (PreferredActivity pa : pir.filterSet()) {
11183                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11184                        removed.add(pa);
11185                    }
11186                }
11187                if (removed.size() > 0) {
11188                    for (int j=0; j<removed.size(); j++) {
11189                        PreferredActivity pa = removed.get(i);
11190                        Slog.w(TAG, "Removing dangling preferred activity: "
11191                                + pa.mPref.mComponent);
11192                        pir.removeFilter(pa);
11193                    }
11194                    mSettings.writePackageRestrictionsLPr(
11195                            mSettings.mPreferredActivities.keyAt(i));
11196                }
11197            }
11198        }
11199        sUserManager.systemReady();
11200    }
11201
11202    @Override
11203    public boolean isSafeMode() {
11204        return mSafeMode;
11205    }
11206
11207    @Override
11208    public boolean hasSystemUidErrors() {
11209        return mHasSystemUidErrors;
11210    }
11211
11212    static String arrayToString(int[] array) {
11213        StringBuffer buf = new StringBuffer(128);
11214        buf.append('[');
11215        if (array != null) {
11216            for (int i=0; i<array.length; i++) {
11217                if (i > 0) buf.append(", ");
11218                buf.append(array[i]);
11219            }
11220        }
11221        buf.append(']');
11222        return buf.toString();
11223    }
11224
11225    static class DumpState {
11226        public static final int DUMP_LIBS = 1 << 0;
11227
11228        public static final int DUMP_FEATURES = 1 << 1;
11229
11230        public static final int DUMP_RESOLVERS = 1 << 2;
11231
11232        public static final int DUMP_PERMISSIONS = 1 << 3;
11233
11234        public static final int DUMP_PACKAGES = 1 << 4;
11235
11236        public static final int DUMP_SHARED_USERS = 1 << 5;
11237
11238        public static final int DUMP_MESSAGES = 1 << 6;
11239
11240        public static final int DUMP_PROVIDERS = 1 << 7;
11241
11242        public static final int DUMP_VERIFIERS = 1 << 8;
11243
11244        public static final int DUMP_PREFERRED = 1 << 9;
11245
11246        public static final int DUMP_PREFERRED_XML = 1 << 10;
11247
11248        public static final int DUMP_KEYSETS = 1 << 11;
11249
11250        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11251
11252        private int mTypes;
11253
11254        private int mOptions;
11255
11256        private boolean mTitlePrinted;
11257
11258        private SharedUserSetting mSharedUser;
11259
11260        public boolean isDumping(int type) {
11261            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11262                return true;
11263            }
11264
11265            return (mTypes & type) != 0;
11266        }
11267
11268        public void setDump(int type) {
11269            mTypes |= type;
11270        }
11271
11272        public boolean isOptionEnabled(int option) {
11273            return (mOptions & option) != 0;
11274        }
11275
11276        public void setOptionEnabled(int option) {
11277            mOptions |= option;
11278        }
11279
11280        public boolean onTitlePrinted() {
11281            final boolean printed = mTitlePrinted;
11282            mTitlePrinted = true;
11283            return printed;
11284        }
11285
11286        public boolean getTitlePrinted() {
11287            return mTitlePrinted;
11288        }
11289
11290        public void setTitlePrinted(boolean enabled) {
11291            mTitlePrinted = enabled;
11292        }
11293
11294        public SharedUserSetting getSharedUser() {
11295            return mSharedUser;
11296        }
11297
11298        public void setSharedUser(SharedUserSetting user) {
11299            mSharedUser = user;
11300        }
11301    }
11302
11303    @Override
11304    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11305        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11306                != PackageManager.PERMISSION_GRANTED) {
11307            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11308                    + Binder.getCallingPid()
11309                    + ", uid=" + Binder.getCallingUid()
11310                    + " without permission "
11311                    + android.Manifest.permission.DUMP);
11312            return;
11313        }
11314
11315        DumpState dumpState = new DumpState();
11316        boolean fullPreferred = false;
11317        boolean checkin = false;
11318
11319        String packageName = null;
11320
11321        int opti = 0;
11322        while (opti < args.length) {
11323            String opt = args[opti];
11324            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11325                break;
11326            }
11327            opti++;
11328            if ("-a".equals(opt)) {
11329                // Right now we only know how to print all.
11330            } else if ("-h".equals(opt)) {
11331                pw.println("Package manager dump options:");
11332                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11333                pw.println("    --checkin: dump for a checkin");
11334                pw.println("    -f: print details of intent filters");
11335                pw.println("    -h: print this help");
11336                pw.println("  cmd may be one of:");
11337                pw.println("    l[ibraries]: list known shared libraries");
11338                pw.println("    f[ibraries]: list device features");
11339                pw.println("    r[esolvers]: dump intent resolvers");
11340                pw.println("    perm[issions]: dump permissions");
11341                pw.println("    pref[erred]: print preferred package settings");
11342                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11343                pw.println("    prov[iders]: dump content providers");
11344                pw.println("    p[ackages]: dump installed packages");
11345                pw.println("    s[hared-users]: dump shared user IDs");
11346                pw.println("    m[essages]: print collected runtime messages");
11347                pw.println("    v[erifiers]: print package verifier info");
11348                pw.println("    <package.name>: info about given package");
11349                pw.println("    k[eysets]: print known keysets");
11350                return;
11351            } else if ("--checkin".equals(opt)) {
11352                checkin = true;
11353            } else if ("-f".equals(opt)) {
11354                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11355            } else {
11356                pw.println("Unknown argument: " + opt + "; use -h for help");
11357            }
11358        }
11359
11360        // Is the caller requesting to dump a particular piece of data?
11361        if (opti < args.length) {
11362            String cmd = args[opti];
11363            opti++;
11364            // Is this a package name?
11365            if ("android".equals(cmd) || cmd.contains(".")) {
11366                packageName = cmd;
11367                // When dumping a single package, we always dump all of its
11368                // filter information since the amount of data will be reasonable.
11369                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11370            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11371                dumpState.setDump(DumpState.DUMP_LIBS);
11372            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11373                dumpState.setDump(DumpState.DUMP_FEATURES);
11374            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11375                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11376            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11377                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11378            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11379                dumpState.setDump(DumpState.DUMP_PREFERRED);
11380            } else if ("preferred-xml".equals(cmd)) {
11381                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11382                if (opti < args.length && "--full".equals(args[opti])) {
11383                    fullPreferred = true;
11384                    opti++;
11385                }
11386            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11387                dumpState.setDump(DumpState.DUMP_PACKAGES);
11388            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11389                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11390            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11391                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11392            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11393                dumpState.setDump(DumpState.DUMP_MESSAGES);
11394            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11395                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11396            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11397                dumpState.setDump(DumpState.DUMP_KEYSETS);
11398            }
11399        }
11400
11401        if (checkin) {
11402            pw.println("vers,1");
11403        }
11404
11405        // reader
11406        synchronized (mPackages) {
11407            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11408                if (!checkin) {
11409                    if (dumpState.onTitlePrinted())
11410                        pw.println();
11411                    pw.println("Verifiers:");
11412                    pw.print("  Required: ");
11413                    pw.print(mRequiredVerifierPackage);
11414                    pw.print(" (uid=");
11415                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11416                    pw.println(")");
11417                } else if (mRequiredVerifierPackage != null) {
11418                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11419                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11420                }
11421            }
11422
11423            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11424                boolean printedHeader = false;
11425                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11426                while (it.hasNext()) {
11427                    String name = it.next();
11428                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11429                    if (!checkin) {
11430                        if (!printedHeader) {
11431                            if (dumpState.onTitlePrinted())
11432                                pw.println();
11433                            pw.println("Libraries:");
11434                            printedHeader = true;
11435                        }
11436                        pw.print("  ");
11437                    } else {
11438                        pw.print("lib,");
11439                    }
11440                    pw.print(name);
11441                    if (!checkin) {
11442                        pw.print(" -> ");
11443                    }
11444                    if (ent.path != null) {
11445                        if (!checkin) {
11446                            pw.print("(jar) ");
11447                            pw.print(ent.path);
11448                        } else {
11449                            pw.print(",jar,");
11450                            pw.print(ent.path);
11451                        }
11452                    } else {
11453                        if (!checkin) {
11454                            pw.print("(apk) ");
11455                            pw.print(ent.apk);
11456                        } else {
11457                            pw.print(",apk,");
11458                            pw.print(ent.apk);
11459                        }
11460                    }
11461                    pw.println();
11462                }
11463            }
11464
11465            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11466                if (dumpState.onTitlePrinted())
11467                    pw.println();
11468                if (!checkin) {
11469                    pw.println("Features:");
11470                }
11471                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11472                while (it.hasNext()) {
11473                    String name = it.next();
11474                    if (!checkin) {
11475                        pw.print("  ");
11476                    } else {
11477                        pw.print("feat,");
11478                    }
11479                    pw.println(name);
11480                }
11481            }
11482
11483            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11484                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11485                        : "Activity Resolver Table:", "  ", packageName,
11486                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11487                    dumpState.setTitlePrinted(true);
11488                }
11489                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11490                        : "Receiver Resolver Table:", "  ", packageName,
11491                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11492                    dumpState.setTitlePrinted(true);
11493                }
11494                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11495                        : "Service Resolver Table:", "  ", packageName,
11496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11497                    dumpState.setTitlePrinted(true);
11498                }
11499                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11500                        : "Provider Resolver Table:", "  ", packageName,
11501                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11502                    dumpState.setTitlePrinted(true);
11503                }
11504            }
11505
11506            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11507                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11508                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11509                    int user = mSettings.mPreferredActivities.keyAt(i);
11510                    if (pir.dump(pw,
11511                            dumpState.getTitlePrinted()
11512                                ? "\nPreferred Activities User " + user + ":"
11513                                : "Preferred Activities User " + user + ":", "  ",
11514                            packageName, true)) {
11515                        dumpState.setTitlePrinted(true);
11516                    }
11517                }
11518            }
11519
11520            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11521                pw.flush();
11522                FileOutputStream fout = new FileOutputStream(fd);
11523                BufferedOutputStream str = new BufferedOutputStream(fout);
11524                XmlSerializer serializer = new FastXmlSerializer();
11525                try {
11526                    serializer.setOutput(str, "utf-8");
11527                    serializer.startDocument(null, true);
11528                    serializer.setFeature(
11529                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11530                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11531                    serializer.endDocument();
11532                    serializer.flush();
11533                } catch (IllegalArgumentException e) {
11534                    pw.println("Failed writing: " + e);
11535                } catch (IllegalStateException e) {
11536                    pw.println("Failed writing: " + e);
11537                } catch (IOException e) {
11538                    pw.println("Failed writing: " + e);
11539                }
11540            }
11541
11542            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11543                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11544            }
11545
11546            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11547                boolean printedSomething = false;
11548                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11549                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11550                        continue;
11551                    }
11552                    if (!printedSomething) {
11553                        if (dumpState.onTitlePrinted())
11554                            pw.println();
11555                        pw.println("Registered ContentProviders:");
11556                        printedSomething = true;
11557                    }
11558                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11559                    pw.print("    "); pw.println(p.toString());
11560                }
11561                printedSomething = false;
11562                for (Map.Entry<String, PackageParser.Provider> entry :
11563                        mProvidersByAuthority.entrySet()) {
11564                    PackageParser.Provider p = entry.getValue();
11565                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11566                        continue;
11567                    }
11568                    if (!printedSomething) {
11569                        if (dumpState.onTitlePrinted())
11570                            pw.println();
11571                        pw.println("ContentProvider Authorities:");
11572                        printedSomething = true;
11573                    }
11574                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11575                    pw.print("    "); pw.println(p.toString());
11576                    if (p.info != null && p.info.applicationInfo != null) {
11577                        final String appInfo = p.info.applicationInfo.toString();
11578                        pw.print("      applicationInfo="); pw.println(appInfo);
11579                    }
11580                }
11581            }
11582
11583            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11584                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11585            }
11586
11587            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11588                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11589            }
11590
11591            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11592                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11593            }
11594
11595            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11596                if (dumpState.onTitlePrinted())
11597                    pw.println();
11598                mSettings.dumpReadMessagesLPr(pw, dumpState);
11599
11600                pw.println();
11601                pw.println("Package warning messages:");
11602                final File fname = getSettingsProblemFile();
11603                FileInputStream in = null;
11604                try {
11605                    in = new FileInputStream(fname);
11606                    final int avail = in.available();
11607                    final byte[] data = new byte[avail];
11608                    in.read(data);
11609                    pw.print(new String(data));
11610                } catch (FileNotFoundException e) {
11611                } catch (IOException e) {
11612                } finally {
11613                    if (in != null) {
11614                        try {
11615                            in.close();
11616                        } catch (IOException e) {
11617                        }
11618                    }
11619                }
11620            }
11621        }
11622    }
11623
11624    // ------- apps on sdcard specific code -------
11625    static final boolean DEBUG_SD_INSTALL = false;
11626
11627    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11628
11629    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11630
11631    private boolean mMediaMounted = false;
11632
11633    private String getEncryptKey() {
11634        try {
11635            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11636                    SD_ENCRYPTION_KEYSTORE_NAME);
11637            if (sdEncKey == null) {
11638                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11639                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11640                if (sdEncKey == null) {
11641                    Slog.e(TAG, "Failed to create encryption keys");
11642                    return null;
11643                }
11644            }
11645            return sdEncKey;
11646        } catch (NoSuchAlgorithmException nsae) {
11647            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11648            return null;
11649        } catch (IOException ioe) {
11650            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11651            return null;
11652        }
11653
11654    }
11655
11656    /* package */static String getTempContainerId() {
11657        int tmpIdx = 1;
11658        String list[] = PackageHelper.getSecureContainerList();
11659        if (list != null) {
11660            for (final String name : list) {
11661                // Ignore null and non-temporary container entries
11662                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11663                    continue;
11664                }
11665
11666                String subStr = name.substring(mTempContainerPrefix.length());
11667                try {
11668                    int cid = Integer.parseInt(subStr);
11669                    if (cid >= tmpIdx) {
11670                        tmpIdx = cid + 1;
11671                    }
11672                } catch (NumberFormatException e) {
11673                }
11674            }
11675        }
11676        return mTempContainerPrefix + tmpIdx;
11677    }
11678
11679    /*
11680     * Update media status on PackageManager.
11681     */
11682    @Override
11683    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11684        int callingUid = Binder.getCallingUid();
11685        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11686            throw new SecurityException("Media status can only be updated by the system");
11687        }
11688        // reader; this apparently protects mMediaMounted, but should probably
11689        // be a different lock in that case.
11690        synchronized (mPackages) {
11691            Log.i(TAG, "Updating external media status from "
11692                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11693                    + (mediaStatus ? "mounted" : "unmounted"));
11694            if (DEBUG_SD_INSTALL)
11695                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11696                        + ", mMediaMounted=" + mMediaMounted);
11697            if (mediaStatus == mMediaMounted) {
11698                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11699                        : 0, -1);
11700                mHandler.sendMessage(msg);
11701                return;
11702            }
11703            mMediaMounted = mediaStatus;
11704        }
11705        // Queue up an async operation since the package installation may take a
11706        // little while.
11707        mHandler.post(new Runnable() {
11708            public void run() {
11709                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11710            }
11711        });
11712    }
11713
11714    /**
11715     * Called by MountService when the initial ASECs to scan are available.
11716     * Should block until all the ASEC containers are finished being scanned.
11717     */
11718    public void scanAvailableAsecs() {
11719        updateExternalMediaStatusInner(true, false, false);
11720        if (mShouldRestoreconData) {
11721            SELinuxMMAC.setRestoreconDone();
11722            mShouldRestoreconData = false;
11723        }
11724    }
11725
11726    /*
11727     * Collect information of applications on external media, map them against
11728     * existing containers and update information based on current mount status.
11729     * Please note that we always have to report status if reportStatus has been
11730     * set to true especially when unloading packages.
11731     */
11732    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11733            boolean externalStorage) {
11734        // Collection of uids
11735        int uidArr[] = null;
11736        // Collection of stale containers
11737        HashSet<String> removeCids = new HashSet<String>();
11738        // Collection of packages on external media with valid containers.
11739        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11740        // Get list of secure containers.
11741        final String list[] = PackageHelper.getSecureContainerList();
11742        if (list == null || list.length == 0) {
11743            Log.i(TAG, "No secure containers on sdcard");
11744        } else {
11745            // Process list of secure containers and categorize them
11746            // as active or stale based on their package internal state.
11747            int uidList[] = new int[list.length];
11748            int num = 0;
11749            // reader
11750            synchronized (mPackages) {
11751                for (String cid : list) {
11752                    if (DEBUG_SD_INSTALL)
11753                        Log.i(TAG, "Processing container " + cid);
11754                    String pkgName = getAsecPackageName(cid);
11755                    if (pkgName == null) {
11756                        if (DEBUG_SD_INSTALL)
11757                            Log.i(TAG, "Container : " + cid + " stale");
11758                        removeCids.add(cid);
11759                        continue;
11760                    }
11761                    if (DEBUG_SD_INSTALL)
11762                        Log.i(TAG, "Looking for pkg : " + pkgName);
11763
11764                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11765                    if (ps == null) {
11766                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11767                        removeCids.add(cid);
11768                        continue;
11769                    }
11770
11771                    /*
11772                     * Skip packages that are not external if we're unmounting
11773                     * external storage.
11774                     */
11775                    if (externalStorage && !isMounted && !isExternal(ps)) {
11776                        continue;
11777                    }
11778
11779                    final AsecInstallArgs args = new AsecInstallArgs(cid,
11780                            getAppInstructionSetFromSettings(ps),
11781                            isForwardLocked(ps));
11782                    // The package status is changed only if the code path
11783                    // matches between settings and the container id.
11784                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11785                        if (DEBUG_SD_INSTALL) {
11786                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11787                                    + " at code path: " + ps.codePathString);
11788                        }
11789
11790                        // We do have a valid package installed on sdcard
11791                        processCids.put(args, ps.codePathString);
11792                        final int uid = ps.appId;
11793                        if (uid != -1) {
11794                            uidList[num++] = uid;
11795                        }
11796                    } else {
11797                        Log.i(TAG, "Deleting stale container for " + cid);
11798                        removeCids.add(cid);
11799                    }
11800                }
11801            }
11802
11803            if (num > 0) {
11804                // Sort uid list
11805                Arrays.sort(uidList, 0, num);
11806                // Throw away duplicates
11807                uidArr = new int[num];
11808                uidArr[0] = uidList[0];
11809                int di = 0;
11810                for (int i = 1; i < num; i++) {
11811                    if (uidList[i - 1] != uidList[i]) {
11812                        uidArr[di++] = uidList[i];
11813                    }
11814                }
11815            }
11816        }
11817        // Process packages with valid entries.
11818        if (isMounted) {
11819            if (DEBUG_SD_INSTALL)
11820                Log.i(TAG, "Loading packages");
11821            loadMediaPackages(processCids, uidArr, removeCids);
11822            startCleaningPackages();
11823        } else {
11824            if (DEBUG_SD_INSTALL)
11825                Log.i(TAG, "Unloading packages");
11826            unloadMediaPackages(processCids, uidArr, reportStatus);
11827        }
11828    }
11829
11830   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11831           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11832        int size = pkgList.size();
11833        if (size > 0) {
11834            // Send broadcasts here
11835            Bundle extras = new Bundle();
11836            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11837                    .toArray(new String[size]));
11838            if (uidArr != null) {
11839                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11840            }
11841            if (replacing) {
11842                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11843            }
11844            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11845                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11846            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11847        }
11848    }
11849
11850   /*
11851     * Look at potentially valid container ids from processCids If package
11852     * information doesn't match the one on record or package scanning fails,
11853     * the cid is added to list of removeCids. We currently don't delete stale
11854     * containers.
11855     */
11856   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11857            HashSet<String> removeCids) {
11858        ArrayList<String> pkgList = new ArrayList<String>();
11859        Set<AsecInstallArgs> keys = processCids.keySet();
11860        boolean doGc = false;
11861        for (AsecInstallArgs args : keys) {
11862            String codePath = processCids.get(args);
11863            if (DEBUG_SD_INSTALL)
11864                Log.i(TAG, "Loading container : " + args.cid);
11865            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11866            try {
11867                // Make sure there are no container errors first.
11868                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11869                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11870                            + " when installing from sdcard");
11871                    continue;
11872                }
11873                // Check code path here.
11874                if (codePath == null || !codePath.equals(args.getCodePath())) {
11875                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11876                            + " does not match one in settings " + codePath);
11877                    continue;
11878                }
11879                // Parse package
11880                int parseFlags = mDefParseFlags;
11881                if (args.isExternal()) {
11882                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11883                }
11884                if (args.isFwdLocked()) {
11885                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11886                }
11887
11888                doGc = true;
11889                synchronized (mInstallLock) {
11890                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11891                            0, 0, null);
11892                    // Scan the package
11893                    if (pkg != null) {
11894                        /*
11895                         * TODO why is the lock being held? doPostInstall is
11896                         * called in other places without the lock. This needs
11897                         * to be straightened out.
11898                         */
11899                        // writer
11900                        synchronized (mPackages) {
11901                            retCode = PackageManager.INSTALL_SUCCEEDED;
11902                            pkgList.add(pkg.packageName);
11903                            // Post process args
11904                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11905                                    pkg.applicationInfo.uid);
11906                        }
11907                    } else {
11908                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11909                    }
11910                }
11911
11912            } finally {
11913                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11914                    // Don't destroy container here. Wait till gc clears things
11915                    // up.
11916                    removeCids.add(args.cid);
11917                }
11918            }
11919        }
11920        // writer
11921        synchronized (mPackages) {
11922            // If the platform SDK has changed since the last time we booted,
11923            // we need to re-grant app permission to catch any new ones that
11924            // appear. This is really a hack, and means that apps can in some
11925            // cases get permissions that the user didn't initially explicitly
11926            // allow... it would be nice to have some better way to handle
11927            // this situation.
11928            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11929            if (regrantPermissions)
11930                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11931                        + mSdkVersion + "; regranting permissions for external storage");
11932            mSettings.mExternalSdkPlatform = mSdkVersion;
11933
11934            // Make sure group IDs have been assigned, and any permission
11935            // changes in other apps are accounted for
11936            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11937                    | (regrantPermissions
11938                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11939                            : 0));
11940            // can downgrade to reader
11941            // Persist settings
11942            mSettings.writeLPr();
11943        }
11944        // Send a broadcast to let everyone know we are done processing
11945        if (pkgList.size() > 0) {
11946            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11947        }
11948        // Force gc to avoid any stale parser references that we might have.
11949        if (doGc) {
11950            Runtime.getRuntime().gc();
11951        }
11952        // List stale containers and destroy stale temporary containers.
11953        if (removeCids != null) {
11954            for (String cid : removeCids) {
11955                if (cid.startsWith(mTempContainerPrefix)) {
11956                    Log.i(TAG, "Destroying stale temporary container " + cid);
11957                    PackageHelper.destroySdDir(cid);
11958                } else {
11959                    Log.w(TAG, "Container " + cid + " is stale");
11960               }
11961           }
11962        }
11963    }
11964
11965   /*
11966     * Utility method to unload a list of specified containers
11967     */
11968    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11969        // Just unmount all valid containers.
11970        for (AsecInstallArgs arg : cidArgs) {
11971            synchronized (mInstallLock) {
11972                arg.doPostDeleteLI(false);
11973           }
11974       }
11975   }
11976
11977    /*
11978     * Unload packages mounted on external media. This involves deleting package
11979     * data from internal structures, sending broadcasts about diabled packages,
11980     * gc'ing to free up references, unmounting all secure containers
11981     * corresponding to packages on external media, and posting a
11982     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11983     * that we always have to post this message if status has been requested no
11984     * matter what.
11985     */
11986    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11987            final boolean reportStatus) {
11988        if (DEBUG_SD_INSTALL)
11989            Log.i(TAG, "unloading media packages");
11990        ArrayList<String> pkgList = new ArrayList<String>();
11991        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11992        final Set<AsecInstallArgs> keys = processCids.keySet();
11993        for (AsecInstallArgs args : keys) {
11994            String pkgName = args.getPackageName();
11995            if (DEBUG_SD_INSTALL)
11996                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11997            // Delete package internally
11998            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11999            synchronized (mInstallLock) {
12000                boolean res = deletePackageLI(pkgName, null, false, null, null,
12001                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12002                if (res) {
12003                    pkgList.add(pkgName);
12004                } else {
12005                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12006                    failedList.add(args);
12007                }
12008            }
12009        }
12010
12011        // reader
12012        synchronized (mPackages) {
12013            // We didn't update the settings after removing each package;
12014            // write them now for all packages.
12015            mSettings.writeLPr();
12016        }
12017
12018        // We have to absolutely send UPDATED_MEDIA_STATUS only
12019        // after confirming that all the receivers processed the ordered
12020        // broadcast when packages get disabled, force a gc to clean things up.
12021        // and unload all the containers.
12022        if (pkgList.size() > 0) {
12023            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12024                    new IIntentReceiver.Stub() {
12025                public void performReceive(Intent intent, int resultCode, String data,
12026                        Bundle extras, boolean ordered, boolean sticky,
12027                        int sendingUser) throws RemoteException {
12028                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12029                            reportStatus ? 1 : 0, 1, keys);
12030                    mHandler.sendMessage(msg);
12031                }
12032            });
12033        } else {
12034            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12035                    keys);
12036            mHandler.sendMessage(msg);
12037        }
12038    }
12039
12040    /** Binder call */
12041    @Override
12042    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12043            final int flags) {
12044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12045        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12046        int returnCode = PackageManager.MOVE_SUCCEEDED;
12047        int currFlags = 0;
12048        int newFlags = 0;
12049        // reader
12050        synchronized (mPackages) {
12051            PackageParser.Package pkg = mPackages.get(packageName);
12052            if (pkg == null) {
12053                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12054            } else {
12055                // Disable moving fwd locked apps and system packages
12056                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12057                    Slog.w(TAG, "Cannot move system application");
12058                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12059                } else if (pkg.mOperationPending) {
12060                    Slog.w(TAG, "Attempt to move package which has pending operations");
12061                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12062                } else {
12063                    // Find install location first
12064                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12065                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12066                        Slog.w(TAG, "Ambigous flags specified for move location.");
12067                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12068                    } else {
12069                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12070                                : PackageManager.INSTALL_INTERNAL;
12071                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12072                                : PackageManager.INSTALL_INTERNAL;
12073
12074                        if (newFlags == currFlags) {
12075                            Slog.w(TAG, "No move required. Trying to move to same location");
12076                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12077                        } else {
12078                            if (isForwardLocked(pkg)) {
12079                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12080                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12081                            }
12082                        }
12083                    }
12084                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12085                        pkg.mOperationPending = true;
12086                    }
12087                }
12088            }
12089
12090            /*
12091             * TODO this next block probably shouldn't be inside the lock. We
12092             * can't guarantee these won't change after this is fired off
12093             * anyway.
12094             */
12095            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12096                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12097                        null, -1, user),
12098                        returnCode);
12099            } else {
12100                Message msg = mHandler.obtainMessage(INIT_COPY);
12101                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12102                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12103                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12104                        instructionSet);
12105                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12106                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12107                msg.obj = mp;
12108                mHandler.sendMessage(msg);
12109            }
12110        }
12111    }
12112
12113    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12114        // Queue up an async operation since the package deletion may take a
12115        // little while.
12116        mHandler.post(new Runnable() {
12117            public void run() {
12118                // TODO fix this; this does nothing.
12119                mHandler.removeCallbacks(this);
12120                int returnCode = currentStatus;
12121                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12122                    int uidArr[] = null;
12123                    ArrayList<String> pkgList = null;
12124                    synchronized (mPackages) {
12125                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12126                        if (pkg == null) {
12127                            Slog.w(TAG, " Package " + mp.packageName
12128                                    + " doesn't exist. Aborting move");
12129                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12130                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12131                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12132                                    + mp.srcArgs.getCodePath() + " to "
12133                                    + pkg.applicationInfo.sourceDir
12134                                    + " Aborting move and returning error");
12135                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12136                        } else {
12137                            uidArr = new int[] {
12138                                pkg.applicationInfo.uid
12139                            };
12140                            pkgList = new ArrayList<String>();
12141                            pkgList.add(mp.packageName);
12142                        }
12143                    }
12144                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12145                        // Send resources unavailable broadcast
12146                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12147                        // Update package code and resource paths
12148                        synchronized (mInstallLock) {
12149                            synchronized (mPackages) {
12150                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12151                                // Recheck for package again.
12152                                if (pkg == null) {
12153                                    Slog.w(TAG, " Package " + mp.packageName
12154                                            + " doesn't exist. Aborting move");
12155                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12156                                } else if (!mp.srcArgs.getCodePath().equals(
12157                                        pkg.applicationInfo.sourceDir)) {
12158                                    Slog.w(TAG, "Package " + mp.packageName
12159                                            + " code path changed from " + mp.srcArgs.getCodePath()
12160                                            + " to " + pkg.applicationInfo.sourceDir
12161                                            + " Aborting move and returning error");
12162                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12163                                } else {
12164                                    final String oldCodePath = pkg.mPath;
12165                                    final String newCodePath = mp.targetArgs.getCodePath();
12166                                    final String newResPath = mp.targetArgs.getResourcePath();
12167                                    final String newNativePath = mp.targetArgs
12168                                            .getNativeLibraryPath();
12169
12170                                    final File newNativeDir = new File(newNativePath);
12171
12172                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12173                                        // NOTE: We do not report any errors from the APK scan and library
12174                                        // copy at this point.
12175                                        NativeLibraryHelper.ApkHandle handle =
12176                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12177                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12178                                                handle, Build.SUPPORTED_ABIS);
12179                                        if (abi >= 0) {
12180                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12181                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12182                                        }
12183                                        handle.close();
12184                                    }
12185                                    final int[] users = sUserManager.getUserIds();
12186                                    for (int user : users) {
12187                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12188                                                newNativePath, user) < 0) {
12189                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12190                                        }
12191                                    }
12192
12193                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12194                                        pkg.mPath = newCodePath;
12195                                        // Move dex files around
12196                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12197                                            // Moving of dex files failed. Set
12198                                            // error code and abort move.
12199                                            pkg.mPath = pkg.mScanPath;
12200                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12201                                        }
12202                                    }
12203
12204                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12205                                        pkg.mScanPath = newCodePath;
12206                                        pkg.applicationInfo.sourceDir = newCodePath;
12207                                        pkg.applicationInfo.publicSourceDir = newResPath;
12208                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12209                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12210                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12211                                        ps.codePathString = ps.codePath.getPath();
12212                                        ps.resourcePath = new File(
12213                                                pkg.applicationInfo.publicSourceDir);
12214                                        ps.resourcePathString = ps.resourcePath.getPath();
12215                                        ps.nativeLibraryPathString = newNativePath;
12216                                        // Set the application info flag
12217                                        // correctly.
12218                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12219                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12220                                        } else {
12221                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12222                                        }
12223                                        ps.setFlags(pkg.applicationInfo.flags);
12224                                        mAppDirs.remove(oldCodePath);
12225                                        mAppDirs.put(newCodePath, pkg);
12226                                        // Persist settings
12227                                        mSettings.writeLPr();
12228                                    }
12229                                }
12230                            }
12231                        }
12232                        // Send resources available broadcast
12233                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12234                    }
12235                }
12236                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12237                    // Clean up failed installation
12238                    if (mp.targetArgs != null) {
12239                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12240                                -1);
12241                    }
12242                } else {
12243                    // Force a gc to clear things up.
12244                    Runtime.getRuntime().gc();
12245                    // Delete older code
12246                    synchronized (mInstallLock) {
12247                        mp.srcArgs.doPostDeleteLI(true);
12248                    }
12249                }
12250
12251                // Allow more operations on this file if we didn't fail because
12252                // an operation was already pending for this package.
12253                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12254                    synchronized (mPackages) {
12255                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12256                        if (pkg != null) {
12257                            pkg.mOperationPending = false;
12258                       }
12259                   }
12260                }
12261
12262                IPackageMoveObserver observer = mp.observer;
12263                if (observer != null) {
12264                    try {
12265                        observer.packageMoved(mp.packageName, returnCode);
12266                    } catch (RemoteException e) {
12267                        Log.i(TAG, "Observer no longer exists.");
12268                    }
12269                }
12270            }
12271        });
12272    }
12273
12274    @Override
12275    public boolean setInstallLocation(int loc) {
12276        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12277                null);
12278        if (getInstallLocation() == loc) {
12279            return true;
12280        }
12281        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12282                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12283            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12284                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12285            return true;
12286        }
12287        return false;
12288   }
12289
12290    @Override
12291    public int getInstallLocation() {
12292        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12293                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12294                PackageHelper.APP_INSTALL_AUTO);
12295    }
12296
12297    /** Called by UserManagerService */
12298    void cleanUpUserLILPw(int userHandle) {
12299        mDirtyUsers.remove(userHandle);
12300        mSettings.removeUserLPr(userHandle);
12301        mPendingBroadcasts.remove(userHandle);
12302        if (mInstaller != null) {
12303            // Technically, we shouldn't be doing this with the package lock
12304            // held.  However, this is very rare, and there is already so much
12305            // other disk I/O going on, that we'll let it slide for now.
12306            mInstaller.removeUserDataDirs(userHandle);
12307        }
12308    }
12309
12310    /** Called by UserManagerService */
12311    void createNewUserLILPw(int userHandle, File path) {
12312        if (mInstaller != null) {
12313            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12314        }
12315    }
12316
12317    @Override
12318    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12319        mContext.enforceCallingOrSelfPermission(
12320                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12321                "Only package verification agents can read the verifier device identity");
12322
12323        synchronized (mPackages) {
12324            return mSettings.getVerifierDeviceIdentityLPw();
12325        }
12326    }
12327
12328    @Override
12329    public void setPermissionEnforced(String permission, boolean enforced) {
12330        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12331        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12332            synchronized (mPackages) {
12333                if (mSettings.mReadExternalStorageEnforced == null
12334                        || mSettings.mReadExternalStorageEnforced != enforced) {
12335                    mSettings.mReadExternalStorageEnforced = enforced;
12336                    mSettings.writeLPr();
12337                }
12338            }
12339            // kill any non-foreground processes so we restart them and
12340            // grant/revoke the GID.
12341            final IActivityManager am = ActivityManagerNative.getDefault();
12342            if (am != null) {
12343                final long token = Binder.clearCallingIdentity();
12344                try {
12345                    am.killProcessesBelowForeground("setPermissionEnforcement");
12346                } catch (RemoteException e) {
12347                } finally {
12348                    Binder.restoreCallingIdentity(token);
12349                }
12350            }
12351        } else {
12352            throw new IllegalArgumentException("No selective enforcement for " + permission);
12353        }
12354    }
12355
12356    @Override
12357    @Deprecated
12358    public boolean isPermissionEnforced(String permission) {
12359        return true;
12360    }
12361
12362    @Override
12363    public boolean isStorageLow() {
12364        final long token = Binder.clearCallingIdentity();
12365        try {
12366            final DeviceStorageMonitorInternal
12367                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12368            if (dsm != null) {
12369                return dsm.isMemoryLow();
12370            } else {
12371                return false;
12372            }
12373        } finally {
12374            Binder.restoreCallingIdentity(token);
12375        }
12376    }
12377}
12378