PackageManagerService.java revision 5406f59abd0cde826e8254fe628bea6d80769c8c
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.NativeLibraryHelper.ApkHandle;
41import com.android.internal.content.PackageHelper;
42import com.android.internal.util.FastPrintWriter;
43import com.android.internal.util.FastXmlSerializer;
44import com.android.internal.util.XmlUtils;
45import com.android.server.EventLogTags;
46import com.android.server.IntentResolver;
47import com.android.server.LocalServices;
48import com.android.server.ServiceThread;
49import com.android.server.Watchdog;
50import com.android.server.storage.DeviceStorageMonitorInternal;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
55
56import android.app.ActivityManager;
57import android.app.ActivityManagerNative;
58import android.app.IActivityManager;
59import android.app.admin.IDevicePolicyManager;
60import android.app.backup.IBackupManager;
61import android.content.BroadcastReceiver;
62import android.content.ComponentName;
63import android.content.Context;
64import android.content.IIntentReceiver;
65import android.content.Intent;
66import android.content.IntentFilter;
67import android.content.IntentSender;
68import android.content.IntentSender.SendIntentException;
69import android.content.ServiceConnection;
70import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ContainerEncryptionParams;
73import android.content.pm.FeatureInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageDeleteObserver;
76import android.content.pm.IPackageInstallObserver;
77import android.content.pm.IPackageManager;
78import android.content.pm.IPackageMoveObserver;
79import android.content.pm.IPackageStatsObserver;
80import android.content.pm.InstrumentationInfo;
81import android.content.pm.ManifestDigest;
82import android.content.pm.PackageCleanItem;
83import android.content.pm.PackageInfo;
84import android.content.pm.PackageInfoLite;
85import android.content.pm.PackageManager;
86import android.content.pm.PackageParser.ActivityIntentInfo;
87import android.content.pm.PackageParser;
88import android.content.pm.PackageStats;
89import android.content.pm.PackageUserState;
90import android.content.pm.ParceledListSlice;
91import android.content.pm.PermissionGroupInfo;
92import android.content.pm.PermissionInfo;
93import android.content.pm.ProviderInfo;
94import android.content.pm.ResolveInfo;
95import android.content.pm.ServiceInfo;
96import android.content.pm.Signature;
97import android.content.pm.VerificationParams;
98import android.content.pm.VerifierDeviceIdentity;
99import android.content.pm.VerifierInfo;
100import android.content.res.Resources;
101import android.hardware.display.DisplayManager;
102import android.net.Uri;
103import android.os.Binder;
104import android.os.Build;
105import android.os.Bundle;
106import android.os.Environment;
107import android.os.Environment.UserEnvironment;
108import android.os.FileObserver;
109import android.os.FileUtils;
110import android.os.Handler;
111import android.os.IBinder;
112import android.os.Looper;
113import android.os.Message;
114import android.os.Parcel;
115import android.os.ParcelFileDescriptor;
116import android.os.Process;
117import android.os.RemoteException;
118import android.os.SELinux;
119import android.os.ServiceManager;
120import android.os.SystemClock;
121import android.os.SystemProperties;
122import android.os.UserHandle;
123import android.os.UserManager;
124import android.security.KeyStore;
125import android.security.SystemKeyStore;
126import android.system.ErrnoException;
127import android.system.Os;
128import android.system.StructStat;
129import android.text.TextUtils;
130import android.util.AtomicFile;
131import android.util.DisplayMetrics;
132import android.util.EventLog;
133import android.util.Log;
134import android.util.LogPrinter;
135import android.util.PrintStreamPrinter;
136import android.util.Slog;
137import android.util.SparseArray;
138import android.util.Xml;
139import android.view.Display;
140
141import java.io.BufferedInputStream;
142import java.io.BufferedOutputStream;
143import java.io.File;
144import java.io.FileDescriptor;
145import java.io.FileInputStream;
146import java.io.FileNotFoundException;
147import java.io.FileOutputStream;
148import java.io.FileReader;
149import java.io.FilenameFilter;
150import java.io.IOException;
151import java.io.InputStream;
152import java.io.PrintWriter;
153import java.nio.charset.StandardCharsets;
154import java.security.NoSuchAlgorithmException;
155import java.security.PublicKey;
156import java.security.cert.CertificateException;
157import java.text.SimpleDateFormat;
158import java.util.ArrayList;
159import java.util.Arrays;
160import java.util.Collection;
161import java.util.Collections;
162import java.util.Comparator;
163import java.util.Date;
164import java.util.HashMap;
165import java.util.HashSet;
166import java.util.Iterator;
167import java.util.List;
168import java.util.Map;
169import java.util.Set;
170import java.util.concurrent.atomic.AtomicBoolean;
171import java.util.concurrent.atomic.AtomicLong;
172
173import dalvik.system.DexFile;
174import dalvik.system.StaleDexCacheError;
175import dalvik.system.VMRuntime;
176import libcore.io.IoUtils;
177
178/**
179 * Keep track of all those .apks everywhere.
180 *
181 * This is very central to the platform's security; please run the unit
182 * tests whenever making modifications here:
183 *
184mmm frameworks/base/tests/AndroidTests
185adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
186adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
187 *
188 * {@hide}
189 */
190public class PackageManagerService extends IPackageManager.Stub {
191    static final String TAG = "PackageManager";
192    static final boolean DEBUG_SETTINGS = false;
193    static final boolean DEBUG_PREFERRED = false;
194    static final boolean DEBUG_UPGRADE = false;
195    private static final boolean DEBUG_INSTALL = false;
196    private static final boolean DEBUG_REMOVE = false;
197    private static final boolean DEBUG_BROADCASTS = false;
198    private static final boolean DEBUG_SHOW_INFO = false;
199    private static final boolean DEBUG_PACKAGE_INFO = false;
200    private static final boolean DEBUG_INTENT_MATCHING = false;
201    private static final boolean DEBUG_PACKAGE_SCANNING = false;
202    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
203    private static final boolean DEBUG_VERIFY = false;
204    private static final boolean DEBUG_DEXOPT = false;
205
206    private static final int RADIO_UID = Process.PHONE_UID;
207    private static final int LOG_UID = Process.LOG_UID;
208    private static final int NFC_UID = Process.NFC_UID;
209    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
210    private static final int SHELL_UID = Process.SHELL_UID;
211
212    private static final boolean GET_CERTIFICATES = true;
213
214    private static final int REMOVE_EVENTS =
215        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
216    private static final int ADD_EVENTS =
217        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
218
219    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
220    // Suffix used during package installation when copying/moving
221    // package apks to install directory.
222    private static final String INSTALL_PACKAGE_SUFFIX = "-";
223
224    static final int SCAN_MONITOR = 1<<0;
225    static final int SCAN_NO_DEX = 1<<1;
226    static final int SCAN_FORCE_DEX = 1<<2;
227    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
228    static final int SCAN_NEW_INSTALL = 1<<4;
229    static final int SCAN_NO_PATHS = 1<<5;
230    static final int SCAN_UPDATE_TIME = 1<<6;
231    static final int SCAN_DEFER_DEX = 1<<7;
232    static final int SCAN_BOOTING = 1<<8;
233    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
234    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
235
236    static final int REMOVE_CHATTY = 1<<16;
237
238    /**
239     * Timeout (in milliseconds) after which the watchdog should declare that
240     * our handler thread is wedged.  The usual default for such things is one
241     * minute but we sometimes do very lengthy I/O operations on this thread,
242     * such as installing multi-gigabyte applications, so ours needs to be longer.
243     */
244    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
245
246    /**
247     * Whether verification is enabled by default.
248     */
249    private static final boolean DEFAULT_VERIFY_ENABLE = true;
250
251    /**
252     * The default maximum time to wait for the verification agent to return in
253     * milliseconds.
254     */
255    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
256
257    /**
258     * The default response for package verification timeout.
259     *
260     * This can be either PackageManager.VERIFICATION_ALLOW or
261     * PackageManager.VERIFICATION_REJECT.
262     */
263    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
264
265    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
266
267    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
268            DEFAULT_CONTAINER_PACKAGE,
269            "com.android.defcontainer.DefaultContainerService");
270
271    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
272
273    private static final String LIB_DIR_NAME = "lib";
274    private static final String LIB64_DIR_NAME = "lib64";
275
276    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
277
278    static final String mTempContainerPrefix = "smdl2tmp";
279
280    final ServiceThread mHandlerThread;
281
282    private static String sPreferredInstructionSet;
283
284    private static final String IDMAP_PREFIX = "/data/resource-cache/";
285    private static final String IDMAP_SUFFIX = "@idmap";
286
287    final PackageHandler mHandler;
288
289    final int mSdkVersion = Build.VERSION.SDK_INT;
290    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
291            ? null : Build.VERSION.CODENAME;
292
293    final Context mContext;
294    final boolean mFactoryTest;
295    final boolean mOnlyCore;
296    final DisplayMetrics mMetrics;
297    final int mDefParseFlags;
298    final String[] mSeparateProcesses;
299
300    // This is where all application persistent data goes.
301    final File mAppDataDir;
302
303    // This is where all application persistent data goes for secondary users.
304    final File mUserAppDataDir;
305
306    /** The location for ASEC container files on internal storage. */
307    final String mAsecInternalPath;
308
309    // This is the object monitoring the framework dir.
310    final FileObserver mFrameworkInstallObserver;
311
312    // This is the object monitoring the system app dir.
313    final FileObserver mSystemInstallObserver;
314
315    // This is the object monitoring the privileged system app dir.
316    final FileObserver mPrivilegedInstallObserver;
317
318    // This is the object monitoring the system app dir.
319    final FileObserver mVendorInstallObserver;
320
321    // This is the object monitoring the vendor overlay package dir.
322    final FileObserver mVendorOverlayInstallObserver;
323
324    // This is the object monitoring mAppInstallDir.
325    final FileObserver mAppInstallObserver;
326
327    // This is the object monitoring mDrmAppPrivateInstallDir.
328    final FileObserver mDrmAppInstallObserver;
329
330    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
331    // LOCK HELD.  Can be called with mInstallLock held.
332    final Installer mInstaller;
333
334    final File mAppInstallDir;
335
336    /**
337     * Directory to which applications installed internally have native
338     * libraries copied.
339     */
340    private File mAppLibInstallDir;
341
342    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
343    // apps.
344    final File mDrmAppPrivateInstallDir;
345
346    // ----------------------------------------------------------------
347
348    // Lock for state used when installing and doing other long running
349    // operations.  Methods that must be called with this lock held have
350    // the prefix "LI".
351    final Object mInstallLock = new Object();
352
353    // These are the directories in the 3rd party applications installed dir
354    // that we have currently loaded packages from.  Keys are the application's
355    // installed zip file (absolute codePath), and values are Package.
356    final HashMap<String, PackageParser.Package> mAppDirs =
357            new HashMap<String, PackageParser.Package>();
358
359    // Information for the parser to write more useful error messages.
360    int mLastScanError;
361
362    // ----------------------------------------------------------------
363
364    // Keys are String (package name), values are Package.  This also serves
365    // as the lock for the global state.  Methods that must be called with
366    // this lock held have the prefix "LP".
367    final HashMap<String, PackageParser.Package> mPackages =
368            new HashMap<String, PackageParser.Package>();
369
370    // Tracks available target package names -> overlay package paths.
371    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
372        new HashMap<String, HashMap<String, PackageParser.Package>>();
373
374    final Settings mSettings;
375    boolean mRestoredSettings;
376
377    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
378    int[] mGlobalGids;
379
380    // These are the built-in uid -> permission mappings that were read from the
381    // etc/permissions.xml file.
382    final SparseArray<HashSet<String>> mSystemPermissions =
383            new SparseArray<HashSet<String>>();
384
385    static final class SharedLibraryEntry {
386        final String path;
387        final String apk;
388
389        SharedLibraryEntry(String _path, String _apk) {
390            path = _path;
391            apk = _apk;
392        }
393    }
394
395    // These are the built-in shared libraries that were read from the
396    // etc/permissions.xml file.
397    final HashMap<String, SharedLibraryEntry> mSharedLibraries
398            = new HashMap<String, SharedLibraryEntry>();
399
400    // Temporary for building the final shared libraries for an .apk.
401    String[] mTmpSharedLibraries = null;
402
403    // These are the features this devices supports that were read from the
404    // etc/permissions.xml file.
405    final HashMap<String, FeatureInfo> mAvailableFeatures =
406            new HashMap<String, FeatureInfo>();
407
408    // If mac_permissions.xml was found for seinfo labeling.
409    boolean mFoundPolicyFile;
410
411    // If a recursive restorecon of /data/data/<pkg> is needed.
412    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
413
414    // All available activities, for your resolving pleasure.
415    final ActivityIntentResolver mActivities =
416            new ActivityIntentResolver();
417
418    // All available receivers, for your resolving pleasure.
419    final ActivityIntentResolver mReceivers =
420            new ActivityIntentResolver();
421
422    // All available services, for your resolving pleasure.
423    final ServiceIntentResolver mServices = new ServiceIntentResolver();
424
425    // All available providers, for your resolving pleasure.
426    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
427
428    // Mapping from provider base names (first directory in content URI codePath)
429    // to the provider information.
430    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
431            new HashMap<String, PackageParser.Provider>();
432
433    // Mapping from instrumentation class names to info about them.
434    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
435            new HashMap<ComponentName, PackageParser.Instrumentation>();
436
437    // Mapping from permission names to info about them.
438    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
439            new HashMap<String, PackageParser.PermissionGroup>();
440
441    // Packages whose data we have transfered into another package, thus
442    // should no longer exist.
443    final HashSet<String> mTransferedPackages = new HashSet<String>();
444
445    // Broadcast actions that are only available to the system.
446    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
447
448    /** List of packages waiting for verification. */
449    final SparseArray<PackageVerificationState> mPendingVerification
450            = new SparseArray<PackageVerificationState>();
451
452    HashSet<PackageParser.Package> mDeferredDexOpt = null;
453
454    /** Token for keys in mPendingVerification. */
455    private int mPendingVerificationToken = 0;
456
457    boolean mSystemReady;
458    boolean mSafeMode;
459    boolean mHasSystemUidErrors;
460
461    ApplicationInfo mAndroidApplication;
462    final ActivityInfo mResolveActivity = new ActivityInfo();
463    final ResolveInfo mResolveInfo = new ResolveInfo();
464    ComponentName mResolveComponentName;
465    PackageParser.Package mPlatformPackage;
466    ComponentName mCustomResolverComponentName;
467
468    boolean mResolverReplaced = false;
469
470    // Set of pending broadcasts for aggregating enable/disable of components.
471    static class PendingPackageBroadcasts {
472        // for each user id, a map of <package name -> components within that package>
473        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
474
475        public PendingPackageBroadcasts() {
476            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
477        }
478
479        public ArrayList<String> get(int userId, String packageName) {
480            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
481            return packages.get(packageName);
482        }
483
484        public void put(int userId, String packageName, ArrayList<String> components) {
485            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
486            packages.put(packageName, components);
487        }
488
489        public void remove(int userId, String packageName) {
490            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
491            if (packages != null) {
492                packages.remove(packageName);
493            }
494        }
495
496        public void remove(int userId) {
497            mUidMap.remove(userId);
498        }
499
500        public int userIdCount() {
501            return mUidMap.size();
502        }
503
504        public int userIdAt(int n) {
505            return mUidMap.keyAt(n);
506        }
507
508        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
509            return mUidMap.get(userId);
510        }
511
512        public int size() {
513            // total number of pending broadcast entries across all userIds
514            int num = 0;
515            for (int i = 0; i< mUidMap.size(); i++) {
516                num += mUidMap.valueAt(i).size();
517            }
518            return num;
519        }
520
521        public void clear() {
522            mUidMap.clear();
523        }
524
525        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
526            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
527            if (map == null) {
528                map = new HashMap<String, ArrayList<String>>();
529                mUidMap.put(userId, map);
530            }
531            return map;
532        }
533    }
534    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
535
536    // Service Connection to remote media container service to copy
537    // package uri's from external media onto secure containers
538    // or internal storage.
539    private IMediaContainerService mContainerService = null;
540
541    static final int SEND_PENDING_BROADCAST = 1;
542    static final int MCS_BOUND = 3;
543    static final int END_COPY = 4;
544    static final int INIT_COPY = 5;
545    static final int MCS_UNBIND = 6;
546    static final int START_CLEANING_PACKAGE = 7;
547    static final int FIND_INSTALL_LOC = 8;
548    static final int POST_INSTALL = 9;
549    static final int MCS_RECONNECT = 10;
550    static final int MCS_GIVE_UP = 11;
551    static final int UPDATED_MEDIA_STATUS = 12;
552    static final int WRITE_SETTINGS = 13;
553    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
554    static final int PACKAGE_VERIFIED = 15;
555    static final int CHECK_PENDING_VERIFICATION = 16;
556
557    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
558
559    // Delay time in millisecs
560    static final int BROADCAST_DELAY = 10 * 1000;
561
562    static UserManagerService sUserManager;
563
564    // Stores a list of users whose package restrictions file needs to be updated
565    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
566
567    final private DefaultContainerConnection mDefContainerConn =
568            new DefaultContainerConnection();
569    class DefaultContainerConnection implements ServiceConnection {
570        public void onServiceConnected(ComponentName name, IBinder service) {
571            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
572            IMediaContainerService imcs =
573                IMediaContainerService.Stub.asInterface(service);
574            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
575        }
576
577        public void onServiceDisconnected(ComponentName name) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
579        }
580    };
581
582    // Recordkeeping of restore-after-install operations that are currently in flight
583    // between the Package Manager and the Backup Manager
584    class PostInstallData {
585        public InstallArgs args;
586        public PackageInstalledInfo res;
587
588        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
589            args = _a;
590            res = _r;
591        }
592    };
593    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
594    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
595
596    private final String mRequiredVerifierPackage;
597
598    private final PackageUsage mPackageUsage = new PackageUsage();
599
600    private class PackageUsage {
601        private static final int WRITE_INTERVAL
602            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
603
604        private final Object mFileLock = new Object();
605        private final AtomicLong mLastWritten = new AtomicLong(0);
606        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
607
608        private boolean mIsFirstBoot = false;
609
610        boolean isFirstBoot() {
611            return mIsFirstBoot;
612        }
613
614        void write(boolean force) {
615            if (force) {
616                writeInternal();
617                return;
618            }
619            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
620                && !DEBUG_DEXOPT) {
621                return;
622            }
623            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
624                new Thread("PackageUsage_DiskWriter") {
625                    @Override
626                    public void run() {
627                        try {
628                            writeInternal();
629                        } finally {
630                            mBackgroundWriteRunning.set(false);
631                        }
632                    }
633                }.start();
634            }
635        }
636
637        private void writeInternal() {
638            synchronized (mPackages) {
639                synchronized (mFileLock) {
640                    AtomicFile file = getFile();
641                    FileOutputStream f = null;
642                    try {
643                        f = file.startWrite();
644                        BufferedOutputStream out = new BufferedOutputStream(f);
645                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
646                        StringBuilder sb = new StringBuilder();
647                        for (PackageParser.Package pkg : mPackages.values()) {
648                            if (pkg.mLastPackageUsageTimeInMills == 0) {
649                                continue;
650                            }
651                            sb.setLength(0);
652                            sb.append(pkg.packageName);
653                            sb.append(' ');
654                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
655                            sb.append('\n');
656                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
657                        }
658                        out.flush();
659                        file.finishWrite(f);
660                    } catch (IOException e) {
661                        if (f != null) {
662                            file.failWrite(f);
663                        }
664                        Log.e(TAG, "Failed to write package usage times", e);
665                    }
666                }
667            }
668            mLastWritten.set(SystemClock.elapsedRealtime());
669        }
670
671        void readLP() {
672            synchronized (mFileLock) {
673                AtomicFile file = getFile();
674                BufferedInputStream in = null;
675                try {
676                    in = new BufferedInputStream(file.openRead());
677                    StringBuffer sb = new StringBuffer();
678                    while (true) {
679                        String packageName = readToken(in, sb, ' ');
680                        if (packageName == null) {
681                            break;
682                        }
683                        String timeInMillisString = readToken(in, sb, '\n');
684                        if (timeInMillisString == null) {
685                            throw new IOException("Failed to find last usage time for package "
686                                                  + packageName);
687                        }
688                        PackageParser.Package pkg = mPackages.get(packageName);
689                        if (pkg == null) {
690                            continue;
691                        }
692                        long timeInMillis;
693                        try {
694                            timeInMillis = Long.parseLong(timeInMillisString.toString());
695                        } catch (NumberFormatException e) {
696                            throw new IOException("Failed to parse " + timeInMillisString
697                                                  + " as a long.", e);
698                        }
699                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
700                    }
701                } catch (FileNotFoundException expected) {
702                    mIsFirstBoot = true;
703                } catch (IOException e) {
704                    Log.w(TAG, "Failed to read package usage times", e);
705                } finally {
706                    IoUtils.closeQuietly(in);
707                }
708            }
709            mLastWritten.set(SystemClock.elapsedRealtime());
710        }
711
712        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
713                throws IOException {
714            sb.setLength(0);
715            while (true) {
716                int ch = in.read();
717                if (ch == -1) {
718                    if (sb.length() == 0) {
719                        return null;
720                    }
721                    throw new IOException("Unexpected EOF");
722                }
723                if (ch == endOfToken) {
724                    return sb.toString();
725                }
726                sb.append((char)ch);
727            }
728        }
729
730        private AtomicFile getFile() {
731            File dataDir = Environment.getDataDirectory();
732            File systemDir = new File(dataDir, "system");
733            File fname = new File(systemDir, "package-usage.list");
734            return new AtomicFile(fname);
735        }
736    }
737
738    class PackageHandler extends Handler {
739        private boolean mBound = false;
740        final ArrayList<HandlerParams> mPendingInstalls =
741            new ArrayList<HandlerParams>();
742
743        private boolean connectToService() {
744            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
745                    " DefaultContainerService");
746            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
747            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
748            if (mContext.bindServiceAsUser(service, mDefContainerConn,
749                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
750                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751                mBound = true;
752                return true;
753            }
754            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755            return false;
756        }
757
758        private void disconnectService() {
759            mContainerService = null;
760            mBound = false;
761            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
762            mContext.unbindService(mDefContainerConn);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764        }
765
766        PackageHandler(Looper looper) {
767            super(looper);
768        }
769
770        public void handleMessage(Message msg) {
771            try {
772                doHandleMessage(msg);
773            } finally {
774                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            }
776        }
777
778        void doHandleMessage(Message msg) {
779            switch (msg.what) {
780                case INIT_COPY: {
781                    HandlerParams params = (HandlerParams) msg.obj;
782                    int idx = mPendingInstalls.size();
783                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
784                    // If a bind was already initiated we dont really
785                    // need to do anything. The pending install
786                    // will be processed later on.
787                    if (!mBound) {
788                        // If this is the only one pending we might
789                        // have to bind to the service again.
790                        if (!connectToService()) {
791                            Slog.e(TAG, "Failed to bind to media container service");
792                            params.serviceError();
793                            return;
794                        } else {
795                            // Once we bind to the service, the first
796                            // pending request will be processed.
797                            mPendingInstalls.add(idx, params);
798                        }
799                    } else {
800                        mPendingInstalls.add(idx, params);
801                        // Already bound to the service. Just make
802                        // sure we trigger off processing the first request.
803                        if (idx == 0) {
804                            mHandler.sendEmptyMessage(MCS_BOUND);
805                        }
806                    }
807                    break;
808                }
809                case MCS_BOUND: {
810                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
811                    if (msg.obj != null) {
812                        mContainerService = (IMediaContainerService) msg.obj;
813                    }
814                    if (mContainerService == null) {
815                        // Something seriously wrong. Bail out
816                        Slog.e(TAG, "Cannot bind to media container service");
817                        for (HandlerParams params : mPendingInstalls) {
818                            // Indicate service bind error
819                            params.serviceError();
820                        }
821                        mPendingInstalls.clear();
822                    } else if (mPendingInstalls.size() > 0) {
823                        HandlerParams params = mPendingInstalls.get(0);
824                        if (params != null) {
825                            if (params.startCopy()) {
826                                // We are done...  look for more work or to
827                                // go idle.
828                                if (DEBUG_SD_INSTALL) Log.i(TAG,
829                                        "Checking for more work or unbind...");
830                                // Delete pending install
831                                if (mPendingInstalls.size() > 0) {
832                                    mPendingInstalls.remove(0);
833                                }
834                                if (mPendingInstalls.size() == 0) {
835                                    if (mBound) {
836                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
837                                                "Posting delayed MCS_UNBIND");
838                                        removeMessages(MCS_UNBIND);
839                                        Message ubmsg = obtainMessage(MCS_UNBIND);
840                                        // Unbind after a little delay, to avoid
841                                        // continual thrashing.
842                                        sendMessageDelayed(ubmsg, 10000);
843                                    }
844                                } else {
845                                    // There are more pending requests in queue.
846                                    // Just post MCS_BOUND message to trigger processing
847                                    // of next pending install.
848                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                            "Posting MCS_BOUND for next woek");
850                                    mHandler.sendEmptyMessage(MCS_BOUND);
851                                }
852                            }
853                        }
854                    } else {
855                        // Should never happen ideally.
856                        Slog.w(TAG, "Empty queue");
857                    }
858                    break;
859                }
860                case MCS_RECONNECT: {
861                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
862                    if (mPendingInstalls.size() > 0) {
863                        if (mBound) {
864                            disconnectService();
865                        }
866                        if (!connectToService()) {
867                            Slog.e(TAG, "Failed to bind to media container service");
868                            for (HandlerParams params : mPendingInstalls) {
869                                // Indicate service bind error
870                                params.serviceError();
871                            }
872                            mPendingInstalls.clear();
873                        }
874                    }
875                    break;
876                }
877                case MCS_UNBIND: {
878                    // If there is no actual work left, then time to unbind.
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
880
881                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
882                        if (mBound) {
883                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
884
885                            disconnectService();
886                        }
887                    } else if (mPendingInstalls.size() > 0) {
888                        // There are more pending requests in queue.
889                        // Just post MCS_BOUND message to trigger processing
890                        // of next pending install.
891                        mHandler.sendEmptyMessage(MCS_BOUND);
892                    }
893
894                    break;
895                }
896                case MCS_GIVE_UP: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
898                    mPendingInstalls.remove(0);
899                    break;
900                }
901                case SEND_PENDING_BROADCAST: {
902                    String packages[];
903                    ArrayList<String> components[];
904                    int size = 0;
905                    int uids[];
906                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
907                    synchronized (mPackages) {
908                        if (mPendingBroadcasts == null) {
909                            return;
910                        }
911                        size = mPendingBroadcasts.size();
912                        if (size <= 0) {
913                            // Nothing to be done. Just return
914                            return;
915                        }
916                        packages = new String[size];
917                        components = new ArrayList[size];
918                        uids = new int[size];
919                        int i = 0;  // filling out the above arrays
920
921                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
922                            int packageUserId = mPendingBroadcasts.userIdAt(n);
923                            Iterator<Map.Entry<String, ArrayList<String>>> it
924                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
925                                            .entrySet().iterator();
926                            while (it.hasNext() && i < size) {
927                                Map.Entry<String, ArrayList<String>> ent = it.next();
928                                packages[i] = ent.getKey();
929                                components[i] = ent.getValue();
930                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
931                                uids[i] = (ps != null)
932                                        ? UserHandle.getUid(packageUserId, ps.appId)
933                                        : -1;
934                                i++;
935                            }
936                        }
937                        size = i;
938                        mPendingBroadcasts.clear();
939                    }
940                    // Send broadcasts
941                    for (int i = 0; i < size; i++) {
942                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
943                    }
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
945                    break;
946                }
947                case START_CLEANING_PACKAGE: {
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
949                    final String packageName = (String)msg.obj;
950                    final int userId = msg.arg1;
951                    final boolean andCode = msg.arg2 != 0;
952                    synchronized (mPackages) {
953                        if (userId == UserHandle.USER_ALL) {
954                            int[] users = sUserManager.getUserIds();
955                            for (int user : users) {
956                                mSettings.addPackageToCleanLPw(
957                                        new PackageCleanItem(user, packageName, andCode));
958                            }
959                        } else {
960                            mSettings.addPackageToCleanLPw(
961                                    new PackageCleanItem(userId, packageName, andCode));
962                        }
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    startCleaningPackages();
966                } break;
967                case POST_INSTALL: {
968                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
969                    PostInstallData data = mRunningInstalls.get(msg.arg1);
970                    mRunningInstalls.delete(msg.arg1);
971                    boolean deleteOld = false;
972
973                    if (data != null) {
974                        InstallArgs args = data.args;
975                        PackageInstalledInfo res = data.res;
976
977                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
978                            res.removedInfo.sendBroadcast(false, true, false);
979                            Bundle extras = new Bundle(1);
980                            extras.putInt(Intent.EXTRA_UID, res.uid);
981                            // Determine the set of users who are adding this
982                            // package for the first time vs. those who are seeing
983                            // an update.
984                            int[] firstUsers;
985                            int[] updateUsers = new int[0];
986                            if (res.origUsers == null || res.origUsers.length == 0) {
987                                firstUsers = res.newUsers;
988                            } else {
989                                firstUsers = new int[0];
990                                for (int i=0; i<res.newUsers.length; i++) {
991                                    int user = res.newUsers[i];
992                                    boolean isNew = true;
993                                    for (int j=0; j<res.origUsers.length; j++) {
994                                        if (res.origUsers[j] == user) {
995                                            isNew = false;
996                                            break;
997                                        }
998                                    }
999                                    if (isNew) {
1000                                        int[] newFirst = new int[firstUsers.length+1];
1001                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1002                                                firstUsers.length);
1003                                        newFirst[firstUsers.length] = user;
1004                                        firstUsers = newFirst;
1005                                    } else {
1006                                        int[] newUpdate = new int[updateUsers.length+1];
1007                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1008                                                updateUsers.length);
1009                                        newUpdate[updateUsers.length] = user;
1010                                        updateUsers = newUpdate;
1011                                    }
1012                                }
1013                            }
1014                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1015                                    res.pkg.applicationInfo.packageName,
1016                                    extras, null, null, firstUsers);
1017                            final boolean update = res.removedInfo.removedPackage != null;
1018                            if (update) {
1019                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, updateUsers);
1024                            if (update) {
1025                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1026                                        res.pkg.applicationInfo.packageName,
1027                                        extras, null, null, updateUsers);
1028                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1029                                        null, null,
1030                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1031
1032                                // treat asec-hosted packages like removable media on upgrade
1033                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1034                                    if (DEBUG_INSTALL) {
1035                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1036                                                + " is ASEC-hosted -> AVAILABLE");
1037                                    }
1038                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1039                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1040                                    pkgList.add(res.pkg.applicationInfo.packageName);
1041                                    sendResourcesChangedBroadcast(true, true,
1042                                            pkgList,uidArray, null);
1043                                }
1044                            }
1045                            if (res.removedInfo.args != null) {
1046                                // Remove the replaced package's older resources safely now
1047                                deleteOld = true;
1048                            }
1049
1050                            // Log current value of "unknown sources" setting
1051                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1052                                getUnknownSourcesSettings());
1053                        }
1054                        // Force a gc to clear up things
1055                        Runtime.getRuntime().gc();
1056                        // We delete after a gc for applications  on sdcard.
1057                        if (deleteOld) {
1058                            synchronized (mInstallLock) {
1059                                res.removedInfo.args.doPostDeleteLI(true);
1060                            }
1061                        }
1062                        if (args.observer != null) {
1063                            try {
1064                                args.observer.packageInstalled(res.name, res.returnCode);
1065                            } catch (RemoteException e) {
1066                                Slog.i(TAG, "Observer no longer exists.");
1067                            }
1068                        }
1069                    } else {
1070                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1071                    }
1072                } break;
1073                case UPDATED_MEDIA_STATUS: {
1074                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1075                    boolean reportStatus = msg.arg1 == 1;
1076                    boolean doGc = msg.arg2 == 1;
1077                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1078                    if (doGc) {
1079                        // Force a gc to clear up stale containers.
1080                        Runtime.getRuntime().gc();
1081                    }
1082                    if (msg.obj != null) {
1083                        @SuppressWarnings("unchecked")
1084                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1085                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1086                        // Unload containers
1087                        unloadAllContainers(args);
1088                    }
1089                    if (reportStatus) {
1090                        try {
1091                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1092                            PackageHelper.getMountService().finishMediaUpdate();
1093                        } catch (RemoteException e) {
1094                            Log.e(TAG, "MountService not running?");
1095                        }
1096                    }
1097                } break;
1098                case WRITE_SETTINGS: {
1099                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1100                    synchronized (mPackages) {
1101                        removeMessages(WRITE_SETTINGS);
1102                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1103                        mSettings.writeLPr();
1104                        mDirtyUsers.clear();
1105                    }
1106                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1107                } break;
1108                case WRITE_PACKAGE_RESTRICTIONS: {
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110                    synchronized (mPackages) {
1111                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1112                        for (int userId : mDirtyUsers) {
1113                            mSettings.writePackageRestrictionsLPr(userId);
1114                        }
1115                        mDirtyUsers.clear();
1116                    }
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1118                } break;
1119                case CHECK_PENDING_VERIFICATION: {
1120                    final int verificationId = msg.arg1;
1121                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1122
1123                    if ((state != null) && !state.timeoutExtended()) {
1124                        final InstallArgs args = state.getInstallArgs();
1125                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1126                        mPendingVerification.remove(verificationId);
1127
1128                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1129
1130                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1131                            Slog.i(TAG, "Continuing with installation of "
1132                                    + args.packageURI.toString());
1133                            state.setVerifierResponse(Binder.getCallingUid(),
1134                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1135                            broadcastPackageVerified(verificationId, args.packageURI,
1136                                    PackageManager.VERIFICATION_ALLOW,
1137                                    state.getInstallArgs().getUser());
1138                            try {
1139                                ret = args.copyApk(mContainerService, true);
1140                            } catch (RemoteException e) {
1141                                Slog.e(TAG, "Could not contact the ContainerService");
1142                            }
1143                        } else {
1144                            broadcastPackageVerified(verificationId, args.packageURI,
1145                                    PackageManager.VERIFICATION_REJECT,
1146                                    state.getInstallArgs().getUser());
1147                        }
1148
1149                        processPendingInstall(args, ret);
1150                        mHandler.sendEmptyMessage(MCS_UNBIND);
1151                    }
1152                    break;
1153                }
1154                case PACKAGE_VERIFIED: {
1155                    final int verificationId = msg.arg1;
1156
1157                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1158                    if (state == null) {
1159                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1160                        break;
1161                    }
1162
1163                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1164
1165                    state.setVerifierResponse(response.callerUid, response.code);
1166
1167                    if (state.isVerificationComplete()) {
1168                        mPendingVerification.remove(verificationId);
1169
1170                        final InstallArgs args = state.getInstallArgs();
1171
1172                        int ret;
1173                        if (state.isInstallAllowed()) {
1174                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1175                            broadcastPackageVerified(verificationId, args.packageURI,
1176                                    response.code, state.getInstallArgs().getUser());
1177                            try {
1178                                ret = args.copyApk(mContainerService, true);
1179                            } catch (RemoteException e) {
1180                                Slog.e(TAG, "Could not contact the ContainerService");
1181                            }
1182                        } else {
1183                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1184                        }
1185
1186                        processPendingInstall(args, ret);
1187
1188                        mHandler.sendEmptyMessage(MCS_UNBIND);
1189                    }
1190
1191                    break;
1192                }
1193            }
1194        }
1195    }
1196
1197    void scheduleWriteSettingsLocked() {
1198        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1199            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1200        }
1201    }
1202
1203    void scheduleWritePackageRestrictionsLocked(int userId) {
1204        if (!sUserManager.exists(userId)) return;
1205        mDirtyUsers.add(userId);
1206        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1207            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1208        }
1209    }
1210
1211    public static final IPackageManager main(Context context, Installer installer,
1212            boolean factoryTest, boolean onlyCore) {
1213        PackageManagerService m = new PackageManagerService(context, installer,
1214                factoryTest, onlyCore);
1215        ServiceManager.addService("package", m);
1216        return m;
1217    }
1218
1219    static String[] splitString(String str, char sep) {
1220        int count = 1;
1221        int i = 0;
1222        while ((i=str.indexOf(sep, i)) >= 0) {
1223            count++;
1224            i++;
1225        }
1226
1227        String[] res = new String[count];
1228        i=0;
1229        count = 0;
1230        int lastI=0;
1231        while ((i=str.indexOf(sep, i)) >= 0) {
1232            res[count] = str.substring(lastI, i);
1233            count++;
1234            i++;
1235            lastI = i;
1236        }
1237        res[count] = str.substring(lastI, str.length());
1238        return res;
1239    }
1240
1241    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1242        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1243                Context.DISPLAY_SERVICE);
1244        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1245    }
1246
1247    public PackageManagerService(Context context, Installer installer,
1248            boolean factoryTest, boolean onlyCore) {
1249        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1250                SystemClock.uptimeMillis());
1251
1252        if (mSdkVersion <= 0) {
1253            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1254        }
1255
1256        mContext = context;
1257        mFactoryTest = factoryTest;
1258        mOnlyCore = onlyCore;
1259        mMetrics = new DisplayMetrics();
1260        mSettings = new Settings(context);
1261        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1262                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1263        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1264                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1265        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1266                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1267        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1268                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1269        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1270                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1271        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1272                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1273
1274        String separateProcesses = SystemProperties.get("debug.separate_processes");
1275        if (separateProcesses != null && separateProcesses.length() > 0) {
1276            if ("*".equals(separateProcesses)) {
1277                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1278                mSeparateProcesses = null;
1279                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1280            } else {
1281                mDefParseFlags = 0;
1282                mSeparateProcesses = separateProcesses.split(",");
1283                Slog.w(TAG, "Running with debug.separate_processes: "
1284                        + separateProcesses);
1285            }
1286        } else {
1287            mDefParseFlags = 0;
1288            mSeparateProcesses = null;
1289        }
1290
1291        mInstaller = installer;
1292
1293        getDefaultDisplayMetrics(context, mMetrics);
1294
1295        synchronized (mInstallLock) {
1296        // writer
1297        synchronized (mPackages) {
1298            mHandlerThread = new ServiceThread(TAG,
1299                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1300            mHandlerThread.start();
1301            mHandler = new PackageHandler(mHandlerThread.getLooper());
1302            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1303
1304            File dataDir = Environment.getDataDirectory();
1305            mAppDataDir = new File(dataDir, "data");
1306            mAppInstallDir = new File(dataDir, "app");
1307            mAppLibInstallDir = new File(dataDir, "app-lib");
1308            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1309            mUserAppDataDir = new File(dataDir, "user");
1310            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1311
1312            sUserManager = new UserManagerService(context, this,
1313                    mInstallLock, mPackages);
1314
1315            readPermissions();
1316
1317            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1318
1319            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1320                    mSdkVersion, mOnlyCore);
1321
1322            String customResolverActivity = Resources.getSystem().getString(
1323                    R.string.config_customResolverActivity);
1324            if (TextUtils.isEmpty(customResolverActivity)) {
1325                customResolverActivity = null;
1326            } else {
1327                mCustomResolverComponentName = ComponentName.unflattenFromString(
1328                        customResolverActivity);
1329            }
1330
1331            long startTime = SystemClock.uptimeMillis();
1332
1333            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1334                    startTime);
1335
1336            // Set flag to monitor and not change apk file paths when
1337            // scanning install directories.
1338            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1339
1340            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1341
1342            /**
1343             * Add everything in the in the boot class path to the
1344             * list of process files because dexopt will have been run
1345             * if necessary during zygote startup.
1346             */
1347            String bootClassPath = System.getProperty("java.boot.class.path");
1348            if (bootClassPath != null) {
1349                String[] paths = splitString(bootClassPath, ':');
1350                for (int i=0; i<paths.length; i++) {
1351                    alreadyDexOpted.add(paths[i]);
1352                }
1353            } else {
1354                Slog.w(TAG, "No BOOTCLASSPATH found!");
1355            }
1356
1357            boolean didDexOptLibraryOrTool = false;
1358
1359            final List<String> instructionSets = getAllInstructionSets();
1360
1361            /**
1362             * Ensure all external libraries have had dexopt run on them.
1363             */
1364            if (mSharedLibraries.size() > 0) {
1365                // NOTE: For now, we're compiling these system "shared libraries"
1366                // (and framework jars) into all available architectures. It's possible
1367                // to compile them only when we come across an app that uses them (there's
1368                // already logic for that in scanPackageLI) but that adds some complexity.
1369                for (String instructionSet : instructionSets) {
1370                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1371                        final String lib = libEntry.path;
1372                        if (lib == null) {
1373                            continue;
1374                        }
1375
1376                        try {
1377                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1378                                alreadyDexOpted.add(lib);
1379
1380                                // The list of "shared libraries" we have at this point is
1381                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1382                                didDexOptLibraryOrTool = true;
1383                            }
1384                        } catch (FileNotFoundException e) {
1385                            Slog.w(TAG, "Library not found: " + lib);
1386                        } catch (IOException e) {
1387                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1388                                    + e.getMessage());
1389                        }
1390                    }
1391                }
1392            }
1393
1394            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1395
1396            // Gross hack for now: we know this file doesn't contain any
1397            // code, so don't dexopt it to avoid the resulting log spew.
1398            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1399
1400            // Gross hack for now: we know this file is only part of
1401            // the boot class path for art, so don't dexopt it to
1402            // avoid the resulting log spew.
1403            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1404
1405            /**
1406             * And there are a number of commands implemented in Java, which
1407             * we currently need to do the dexopt on so that they can be
1408             * run from a non-root shell.
1409             */
1410            String[] frameworkFiles = frameworkDir.list();
1411            if (frameworkFiles != null) {
1412                // TODO: We could compile these only for the most preferred ABI. We should
1413                // first double check that the dex files for these commands are not referenced
1414                // by other system apps.
1415                for (String instructionSet : instructionSets) {
1416                    for (int i=0; i<frameworkFiles.length; i++) {
1417                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1418                        String path = libPath.getPath();
1419                        // Skip the file if we already did it.
1420                        if (alreadyDexOpted.contains(path)) {
1421                            continue;
1422                        }
1423                        // Skip the file if it is not a type we want to dexopt.
1424                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1425                            continue;
1426                        }
1427                        try {
1428                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1429                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1430                                didDexOptLibraryOrTool = true;
1431                            }
1432                        } catch (FileNotFoundException e) {
1433                            Slog.w(TAG, "Jar not found: " + path);
1434                        } catch (IOException e) {
1435                            Slog.w(TAG, "Exception reading jar: " + path, e);
1436                        }
1437                    }
1438                }
1439            }
1440
1441            if (didDexOptLibraryOrTool) {
1442                // If we dexopted a library or tool, then something on the system has
1443                // changed. Consider this significant, and wipe away all other
1444                // existing dexopt files to ensure we don't leave any dangling around.
1445                //
1446                // Additionally, delete all dex files from the root directory
1447                // since there shouldn't be any there anyway.
1448                //
1449                // TODO: This should be revisited because it isn't as good an indicator
1450                // as it used to be. It used to include the boot classpath but at some point
1451                // DexFile.isDexOptNeeded started returning false for the boot
1452                // class path files in all cases. It is very possible in a
1453                // small maintenance release update that the library and tool
1454                // jars may be unchanged but APK could be removed resulting in
1455                // unused dalvik-cache files.
1456                mInstaller.pruneDexCache();
1457            }
1458
1459            // Collect vendor overlay packages.
1460            // (Do this before scanning any apps.)
1461            // For security and version matching reason, only consider
1462            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1463            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1464            mVendorOverlayInstallObserver = new AppDirObserver(
1465                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1466            mVendorOverlayInstallObserver.startWatching();
1467            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1468                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1469
1470            // Find base frameworks (resource packages without code).
1471            mFrameworkInstallObserver = new AppDirObserver(
1472                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1473            mFrameworkInstallObserver.startWatching();
1474            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1475                    | PackageParser.PARSE_IS_SYSTEM_DIR
1476                    | PackageParser.PARSE_IS_PRIVILEGED,
1477                    scanMode | SCAN_NO_DEX, 0);
1478
1479            // Collected privileged system packages.
1480            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1481            mPrivilegedInstallObserver = new AppDirObserver(
1482                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1483            mPrivilegedInstallObserver.startWatching();
1484                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1485                        | PackageParser.PARSE_IS_SYSTEM_DIR
1486                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1487
1488            // Collect ordinary system packages.
1489            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1490            mSystemInstallObserver = new AppDirObserver(
1491                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1492            mSystemInstallObserver.startWatching();
1493            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1494                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1495
1496            // Collect all vendor packages.
1497            File vendorAppDir = new File("/vendor/app");
1498            try {
1499                vendorAppDir = vendorAppDir.getCanonicalFile();
1500            } catch (IOException e) {
1501                // failed to look up canonical path, continue with original one
1502            }
1503            mVendorInstallObserver = new AppDirObserver(
1504                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1505            mVendorInstallObserver.startWatching();
1506            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1507                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1508
1509            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1510            mInstaller.moveFiles();
1511
1512            // Prune any system packages that no longer exist.
1513            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1514            if (!mOnlyCore) {
1515                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1516                while (psit.hasNext()) {
1517                    PackageSetting ps = psit.next();
1518
1519                    /*
1520                     * If this is not a system app, it can't be a
1521                     * disable system app.
1522                     */
1523                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1524                        continue;
1525                    }
1526
1527                    /*
1528                     * If the package is scanned, it's not erased.
1529                     */
1530                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1531                    if (scannedPkg != null) {
1532                        /*
1533                         * If the system app is both scanned and in the
1534                         * disabled packages list, then it must have been
1535                         * added via OTA. Remove it from the currently
1536                         * scanned package so the previously user-installed
1537                         * application can be scanned.
1538                         */
1539                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1540                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1541                                    + "; removing system app");
1542                            removePackageLI(ps, true);
1543                        }
1544
1545                        continue;
1546                    }
1547
1548                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1549                        psit.remove();
1550                        String msg = "System package " + ps.name
1551                                + " no longer exists; wiping its data";
1552                        reportSettingsProblem(Log.WARN, msg);
1553                        removeDataDirsLI(ps.name);
1554                    } else {
1555                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1556                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1557                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1558                        }
1559                    }
1560                }
1561            }
1562
1563            //look for any incomplete package installations
1564            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1565            //clean up list
1566            for(int i = 0; i < deletePkgsList.size(); i++) {
1567                //clean up here
1568                cleanupInstallFailedPackage(deletePkgsList.get(i));
1569            }
1570            //delete tmp files
1571            deleteTempPackageFiles();
1572
1573            // Remove any shared userIDs that have no associated packages
1574            mSettings.pruneSharedUsersLPw();
1575
1576            if (!mOnlyCore) {
1577                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1578                        SystemClock.uptimeMillis());
1579                mAppInstallObserver = new AppDirObserver(
1580                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1581                mAppInstallObserver.startWatching();
1582                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1583
1584                mDrmAppInstallObserver = new AppDirObserver(
1585                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1586                mDrmAppInstallObserver.startWatching();
1587                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1588                        scanMode, 0);
1589
1590                /**
1591                 * Remove disable package settings for any updated system
1592                 * apps that were removed via an OTA. If they're not a
1593                 * previously-updated app, remove them completely.
1594                 * Otherwise, just revoke their system-level permissions.
1595                 */
1596                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1597                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1598                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1599
1600                    String msg;
1601                    if (deletedPkg == null) {
1602                        msg = "Updated system package " + deletedAppName
1603                                + " no longer exists; wiping its data";
1604                        removeDataDirsLI(deletedAppName);
1605                    } else {
1606                        msg = "Updated system app + " + deletedAppName
1607                                + " no longer present; removing system privileges for "
1608                                + deletedAppName;
1609
1610                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1611
1612                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1613                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1614                    }
1615                    reportSettingsProblem(Log.WARN, msg);
1616                }
1617            } else {
1618                mAppInstallObserver = null;
1619                mDrmAppInstallObserver = null;
1620            }
1621
1622            // Now that we know all of the shared libraries, update all clients to have
1623            // the correct library paths.
1624            updateAllSharedLibrariesLPw();
1625
1626            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1627                // NOTE: We ignore potential failures here during a system scan (like
1628                // the rest of the commands above) because there's precious little we
1629                // can do about it. A settings error is reported, though.
1630                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1631                        false /* force dexopt */, false /* defer dexopt */);
1632            }
1633
1634            // Now that we know all the packages we are keeping,
1635            // read and update their last usage times.
1636            mPackageUsage.readLP();
1637
1638            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1639                    SystemClock.uptimeMillis());
1640            Slog.i(TAG, "Time to scan packages: "
1641                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1642                    + " seconds");
1643
1644            // If the platform SDK has changed since the last time we booted,
1645            // we need to re-grant app permission to catch any new ones that
1646            // appear.  This is really a hack, and means that apps can in some
1647            // cases get permissions that the user didn't initially explicitly
1648            // allow...  it would be nice to have some better way to handle
1649            // this situation.
1650            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1651                    != mSdkVersion;
1652            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1653                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1654                    + "; regranting permissions for internal storage");
1655            mSettings.mInternalSdkPlatform = mSdkVersion;
1656
1657            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1658                    | (regrantPermissions
1659                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1660                            : 0));
1661
1662            // If this is the first boot, and it is a normal boot, then
1663            // we need to initialize the default preferred apps.
1664            if (!mRestoredSettings && !onlyCore) {
1665                mSettings.readDefaultPreferredAppsLPw(this, 0);
1666            }
1667
1668            // can downgrade to reader
1669            mSettings.writeLPr();
1670
1671            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1672                    SystemClock.uptimeMillis());
1673
1674            // Now after opening every single application zip, make sure they
1675            // are all flushed.  Not really needed, but keeps things nice and
1676            // tidy.
1677            Runtime.getRuntime().gc();
1678
1679            mRequiredVerifierPackage = getRequiredVerifierLPr();
1680        } // synchronized (mPackages)
1681        } // synchronized (mInstallLock)
1682    }
1683
1684    @Override
1685    public boolean isFirstBoot() {
1686        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1687    }
1688
1689    @Override
1690    public boolean isOnlyCoreApps() {
1691        return mOnlyCore;
1692    }
1693
1694    private String getRequiredVerifierLPr() {
1695        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1696        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1697                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1698
1699        String requiredVerifier = null;
1700
1701        final int N = receivers.size();
1702        for (int i = 0; i < N; i++) {
1703            final ResolveInfo info = receivers.get(i);
1704
1705            if (info.activityInfo == null) {
1706                continue;
1707            }
1708
1709            final String packageName = info.activityInfo.packageName;
1710
1711            final PackageSetting ps = mSettings.mPackages.get(packageName);
1712            if (ps == null) {
1713                continue;
1714            }
1715
1716            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1717            if (!gp.grantedPermissions
1718                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1719                continue;
1720            }
1721
1722            if (requiredVerifier != null) {
1723                throw new RuntimeException("There can be only one required verifier");
1724            }
1725
1726            requiredVerifier = packageName;
1727        }
1728
1729        return requiredVerifier;
1730    }
1731
1732    @Override
1733    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1734            throws RemoteException {
1735        try {
1736            return super.onTransact(code, data, reply, flags);
1737        } catch (RuntimeException e) {
1738            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1739                Slog.wtf(TAG, "Package Manager Crash", e);
1740            }
1741            throw e;
1742        }
1743    }
1744
1745    void cleanupInstallFailedPackage(PackageSetting ps) {
1746        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1747        removeDataDirsLI(ps.name);
1748        if (ps.codePath != null) {
1749            if (!ps.codePath.delete()) {
1750                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1751            }
1752        }
1753        if (ps.resourcePath != null) {
1754            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1755                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1756            }
1757        }
1758        mSettings.removePackageLPw(ps.name);
1759    }
1760
1761    void readPermissions() {
1762        // Read permissions from .../etc/permission directory.
1763        File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1764        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1765            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1766            return;
1767        }
1768        if (!libraryDir.canRead()) {
1769            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1770            return;
1771        }
1772
1773        // Iterate over the files in the directory and scan .xml files
1774        for (File f : libraryDir.listFiles()) {
1775            // We'll read platform.xml last
1776            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1777                continue;
1778            }
1779
1780            if (!f.getPath().endsWith(".xml")) {
1781                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1782                continue;
1783            }
1784            if (!f.canRead()) {
1785                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1786                continue;
1787            }
1788
1789            readPermissionsFromXml(f);
1790        }
1791
1792        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1793        final File permFile = new File(Environment.getRootDirectory(),
1794                "etc/permissions/platform.xml");
1795        readPermissionsFromXml(permFile);
1796    }
1797
1798    private void readPermissionsFromXml(File permFile) {
1799        FileReader permReader = null;
1800        try {
1801            permReader = new FileReader(permFile);
1802        } catch (FileNotFoundException e) {
1803            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1804            return;
1805        }
1806
1807        try {
1808            XmlPullParser parser = Xml.newPullParser();
1809            parser.setInput(permReader);
1810
1811            XmlUtils.beginDocument(parser, "permissions");
1812
1813            while (true) {
1814                XmlUtils.nextElement(parser);
1815                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1816                    break;
1817                }
1818
1819                String name = parser.getName();
1820                if ("group".equals(name)) {
1821                    String gidStr = parser.getAttributeValue(null, "gid");
1822                    if (gidStr != null) {
1823                        int gid = Process.getGidForName(gidStr);
1824                        mGlobalGids = appendInt(mGlobalGids, gid);
1825                    } else {
1826                        Slog.w(TAG, "<group> without gid at "
1827                                + parser.getPositionDescription());
1828                    }
1829
1830                    XmlUtils.skipCurrentTag(parser);
1831                    continue;
1832                } else if ("permission".equals(name)) {
1833                    String perm = parser.getAttributeValue(null, "name");
1834                    if (perm == null) {
1835                        Slog.w(TAG, "<permission> without name at "
1836                                + parser.getPositionDescription());
1837                        XmlUtils.skipCurrentTag(parser);
1838                        continue;
1839                    }
1840                    perm = perm.intern();
1841                    readPermission(parser, perm);
1842
1843                } else if ("assign-permission".equals(name)) {
1844                    String perm = parser.getAttributeValue(null, "name");
1845                    if (perm == null) {
1846                        Slog.w(TAG, "<assign-permission> without name at "
1847                                + parser.getPositionDescription());
1848                        XmlUtils.skipCurrentTag(parser);
1849                        continue;
1850                    }
1851                    String uidStr = parser.getAttributeValue(null, "uid");
1852                    if (uidStr == null) {
1853                        Slog.w(TAG, "<assign-permission> without uid at "
1854                                + parser.getPositionDescription());
1855                        XmlUtils.skipCurrentTag(parser);
1856                        continue;
1857                    }
1858                    int uid = Process.getUidForName(uidStr);
1859                    if (uid < 0) {
1860                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1861                                + uidStr + "\" at "
1862                                + parser.getPositionDescription());
1863                        XmlUtils.skipCurrentTag(parser);
1864                        continue;
1865                    }
1866                    perm = perm.intern();
1867                    HashSet<String> perms = mSystemPermissions.get(uid);
1868                    if (perms == null) {
1869                        perms = new HashSet<String>();
1870                        mSystemPermissions.put(uid, perms);
1871                    }
1872                    perms.add(perm);
1873                    XmlUtils.skipCurrentTag(parser);
1874
1875                } else if ("library".equals(name)) {
1876                    String lname = parser.getAttributeValue(null, "name");
1877                    String lfile = parser.getAttributeValue(null, "file");
1878                    if (lname == null) {
1879                        Slog.w(TAG, "<library> without name at "
1880                                + parser.getPositionDescription());
1881                    } else if (lfile == null) {
1882                        Slog.w(TAG, "<library> without file at "
1883                                + parser.getPositionDescription());
1884                    } else {
1885                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1886                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1887                    }
1888                    XmlUtils.skipCurrentTag(parser);
1889                    continue;
1890
1891                } else if ("feature".equals(name)) {
1892                    String fname = parser.getAttributeValue(null, "name");
1893                    if (fname == null) {
1894                        Slog.w(TAG, "<feature> without name at "
1895                                + parser.getPositionDescription());
1896                    } else {
1897                        //Log.i(TAG, "Got feature " + fname);
1898                        FeatureInfo fi = new FeatureInfo();
1899                        fi.name = fname;
1900                        mAvailableFeatures.put(fname, fi);
1901                    }
1902                    XmlUtils.skipCurrentTag(parser);
1903                    continue;
1904
1905                } else {
1906                    XmlUtils.skipCurrentTag(parser);
1907                    continue;
1908                }
1909
1910            }
1911            permReader.close();
1912        } catch (XmlPullParserException e) {
1913            Slog.w(TAG, "Got execption parsing permissions.", e);
1914        } catch (IOException e) {
1915            Slog.w(TAG, "Got execption parsing permissions.", e);
1916        }
1917    }
1918
1919    void readPermission(XmlPullParser parser, String name)
1920            throws IOException, XmlPullParserException {
1921
1922        name = name.intern();
1923
1924        BasePermission bp = mSettings.mPermissions.get(name);
1925        if (bp == null) {
1926            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1927            mSettings.mPermissions.put(name, bp);
1928        }
1929        int outerDepth = parser.getDepth();
1930        int type;
1931        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1932               && (type != XmlPullParser.END_TAG
1933                       || parser.getDepth() > outerDepth)) {
1934            if (type == XmlPullParser.END_TAG
1935                    || type == XmlPullParser.TEXT) {
1936                continue;
1937            }
1938
1939            String tagName = parser.getName();
1940            if ("group".equals(tagName)) {
1941                String gidStr = parser.getAttributeValue(null, "gid");
1942                if (gidStr != null) {
1943                    int gid = Process.getGidForName(gidStr);
1944                    bp.gids = appendInt(bp.gids, gid);
1945                } else {
1946                    Slog.w(TAG, "<group> without gid at "
1947                            + parser.getPositionDescription());
1948                }
1949            }
1950            XmlUtils.skipCurrentTag(parser);
1951        }
1952    }
1953
1954    static int[] appendInts(int[] cur, int[] add) {
1955        if (add == null) return cur;
1956        if (cur == null) return add;
1957        final int N = add.length;
1958        for (int i=0; i<N; i++) {
1959            cur = appendInt(cur, add[i]);
1960        }
1961        return cur;
1962    }
1963
1964    static int[] removeInts(int[] cur, int[] rem) {
1965        if (rem == null) return cur;
1966        if (cur == null) return cur;
1967        final int N = rem.length;
1968        for (int i=0; i<N; i++) {
1969            cur = removeInt(cur, rem[i]);
1970        }
1971        return cur;
1972    }
1973
1974    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1975        if (!sUserManager.exists(userId)) return null;
1976        final PackageSetting ps = (PackageSetting) p.mExtras;
1977        if (ps == null) {
1978            return null;
1979        }
1980        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1981        final PackageUserState state = ps.readUserState(userId);
1982        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1983                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1984                state, userId);
1985    }
1986
1987    @Override
1988    public boolean isPackageAvailable(String packageName, int userId) {
1989        if (!sUserManager.exists(userId)) return false;
1990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1991        synchronized (mPackages) {
1992            PackageParser.Package p = mPackages.get(packageName);
1993            if (p != null) {
1994                final PackageSetting ps = (PackageSetting) p.mExtras;
1995                if (ps != null) {
1996                    final PackageUserState state = ps.readUserState(userId);
1997                    if (state != null) {
1998                        return PackageParser.isAvailable(state);
1999                    }
2000                }
2001            }
2002        }
2003        return false;
2004    }
2005
2006    @Override
2007    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2008        if (!sUserManager.exists(userId)) return null;
2009        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2010        // reader
2011        synchronized (mPackages) {
2012            PackageParser.Package p = mPackages.get(packageName);
2013            if (DEBUG_PACKAGE_INFO)
2014                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2015            if (p != null) {
2016                return generatePackageInfo(p, flags, userId);
2017            }
2018            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2019                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2020            }
2021        }
2022        return null;
2023    }
2024
2025    @Override
2026    public String[] currentToCanonicalPackageNames(String[] names) {
2027        String[] out = new String[names.length];
2028        // reader
2029        synchronized (mPackages) {
2030            for (int i=names.length-1; i>=0; i--) {
2031                PackageSetting ps = mSettings.mPackages.get(names[i]);
2032                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2033            }
2034        }
2035        return out;
2036    }
2037
2038    @Override
2039    public String[] canonicalToCurrentPackageNames(String[] names) {
2040        String[] out = new String[names.length];
2041        // reader
2042        synchronized (mPackages) {
2043            for (int i=names.length-1; i>=0; i--) {
2044                String cur = mSettings.mRenamedPackages.get(names[i]);
2045                out[i] = cur != null ? cur : names[i];
2046            }
2047        }
2048        return out;
2049    }
2050
2051    @Override
2052    public int getPackageUid(String packageName, int userId) {
2053        if (!sUserManager.exists(userId)) return -1;
2054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2055        // reader
2056        synchronized (mPackages) {
2057            PackageParser.Package p = mPackages.get(packageName);
2058            if(p != null) {
2059                return UserHandle.getUid(userId, p.applicationInfo.uid);
2060            }
2061            PackageSetting ps = mSettings.mPackages.get(packageName);
2062            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2063                return -1;
2064            }
2065            p = ps.pkg;
2066            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2067        }
2068    }
2069
2070    @Override
2071    public int[] getPackageGids(String packageName) {
2072        // reader
2073        synchronized (mPackages) {
2074            PackageParser.Package p = mPackages.get(packageName);
2075            if (DEBUG_PACKAGE_INFO)
2076                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2077            if (p != null) {
2078                final PackageSetting ps = (PackageSetting)p.mExtras;
2079                return ps.getGids();
2080            }
2081        }
2082        // stupid thing to indicate an error.
2083        return new int[0];
2084    }
2085
2086    static final PermissionInfo generatePermissionInfo(
2087            BasePermission bp, int flags) {
2088        if (bp.perm != null) {
2089            return PackageParser.generatePermissionInfo(bp.perm, flags);
2090        }
2091        PermissionInfo pi = new PermissionInfo();
2092        pi.name = bp.name;
2093        pi.packageName = bp.sourcePackage;
2094        pi.nonLocalizedLabel = bp.name;
2095        pi.protectionLevel = bp.protectionLevel;
2096        return pi;
2097    }
2098
2099    @Override
2100    public PermissionInfo getPermissionInfo(String name, int flags) {
2101        // reader
2102        synchronized (mPackages) {
2103            final BasePermission p = mSettings.mPermissions.get(name);
2104            if (p != null) {
2105                return generatePermissionInfo(p, flags);
2106            }
2107            return null;
2108        }
2109    }
2110
2111    @Override
2112    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2113        // reader
2114        synchronized (mPackages) {
2115            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2116            for (BasePermission p : mSettings.mPermissions.values()) {
2117                if (group == null) {
2118                    if (p.perm == null || p.perm.info.group == null) {
2119                        out.add(generatePermissionInfo(p, flags));
2120                    }
2121                } else {
2122                    if (p.perm != null && group.equals(p.perm.info.group)) {
2123                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2124                    }
2125                }
2126            }
2127
2128            if (out.size() > 0) {
2129                return out;
2130            }
2131            return mPermissionGroups.containsKey(group) ? out : null;
2132        }
2133    }
2134
2135    @Override
2136    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2137        // reader
2138        synchronized (mPackages) {
2139            return PackageParser.generatePermissionGroupInfo(
2140                    mPermissionGroups.get(name), flags);
2141        }
2142    }
2143
2144    @Override
2145    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2146        // reader
2147        synchronized (mPackages) {
2148            final int N = mPermissionGroups.size();
2149            ArrayList<PermissionGroupInfo> out
2150                    = new ArrayList<PermissionGroupInfo>(N);
2151            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2152                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2153            }
2154            return out;
2155        }
2156    }
2157
2158    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2159            int userId) {
2160        if (!sUserManager.exists(userId)) return null;
2161        PackageSetting ps = mSettings.mPackages.get(packageName);
2162        if (ps != null) {
2163            if (ps.pkg == null) {
2164                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2165                        flags, userId);
2166                if (pInfo != null) {
2167                    return pInfo.applicationInfo;
2168                }
2169                return null;
2170            }
2171            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2172                    ps.readUserState(userId), userId);
2173        }
2174        return null;
2175    }
2176
2177    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2178            int userId) {
2179        if (!sUserManager.exists(userId)) return null;
2180        PackageSetting ps = mSettings.mPackages.get(packageName);
2181        if (ps != null) {
2182            PackageParser.Package pkg = ps.pkg;
2183            if (pkg == null) {
2184                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2185                    return null;
2186                }
2187                pkg = new PackageParser.Package(packageName);
2188                pkg.applicationInfo.packageName = packageName;
2189                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2190                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2191                pkg.applicationInfo.sourceDir = ps.codePathString;
2192                pkg.applicationInfo.dataDir =
2193                        getDataPathForPackage(packageName, 0).getPath();
2194                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2195                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2196            }
2197            return generatePackageInfo(pkg, flags, userId);
2198        }
2199        return null;
2200    }
2201
2202    @Override
2203    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2204        if (!sUserManager.exists(userId)) return null;
2205        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2206        // writer
2207        synchronized (mPackages) {
2208            PackageParser.Package p = mPackages.get(packageName);
2209            if (DEBUG_PACKAGE_INFO) Log.v(
2210                    TAG, "getApplicationInfo " + packageName
2211                    + ": " + p);
2212            if (p != null) {
2213                PackageSetting ps = mSettings.mPackages.get(packageName);
2214                if (ps == null) return null;
2215                // Note: isEnabledLP() does not apply here - always return info
2216                return PackageParser.generateApplicationInfo(
2217                        p, flags, ps.readUserState(userId), userId);
2218            }
2219            if ("android".equals(packageName)||"system".equals(packageName)) {
2220                return mAndroidApplication;
2221            }
2222            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2223                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2224            }
2225        }
2226        return null;
2227    }
2228
2229
2230    @Override
2231    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2232        mContext.enforceCallingOrSelfPermission(
2233                android.Manifest.permission.CLEAR_APP_CACHE, null);
2234        // Queue up an async operation since clearing cache may take a little while.
2235        mHandler.post(new Runnable() {
2236            public void run() {
2237                mHandler.removeCallbacks(this);
2238                int retCode = -1;
2239                synchronized (mInstallLock) {
2240                    retCode = mInstaller.freeCache(freeStorageSize);
2241                    if (retCode < 0) {
2242                        Slog.w(TAG, "Couldn't clear application caches");
2243                    }
2244                }
2245                if (observer != null) {
2246                    try {
2247                        observer.onRemoveCompleted(null, (retCode >= 0));
2248                    } catch (RemoteException e) {
2249                        Slog.w(TAG, "RemoveException when invoking call back");
2250                    }
2251                }
2252            }
2253        });
2254    }
2255
2256    @Override
2257    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2258        mContext.enforceCallingOrSelfPermission(
2259                android.Manifest.permission.CLEAR_APP_CACHE, null);
2260        // Queue up an async operation since clearing cache may take a little while.
2261        mHandler.post(new Runnable() {
2262            public void run() {
2263                mHandler.removeCallbacks(this);
2264                int retCode = -1;
2265                synchronized (mInstallLock) {
2266                    retCode = mInstaller.freeCache(freeStorageSize);
2267                    if (retCode < 0) {
2268                        Slog.w(TAG, "Couldn't clear application caches");
2269                    }
2270                }
2271                if(pi != null) {
2272                    try {
2273                        // Callback via pending intent
2274                        int code = (retCode >= 0) ? 1 : 0;
2275                        pi.sendIntent(null, code, null,
2276                                null, null);
2277                    } catch (SendIntentException e1) {
2278                        Slog.i(TAG, "Failed to send pending intent");
2279                    }
2280                }
2281            }
2282        });
2283    }
2284
2285    @Override
2286    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2287        if (!sUserManager.exists(userId)) return null;
2288        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2289        synchronized (mPackages) {
2290            PackageParser.Activity a = mActivities.mActivities.get(component);
2291
2292            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2293            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2294                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2295                if (ps == null) return null;
2296                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2297                        userId);
2298            }
2299            if (mResolveComponentName.equals(component)) {
2300                return mResolveActivity;
2301            }
2302        }
2303        return null;
2304    }
2305
2306    @Override
2307    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2308        if (!sUserManager.exists(userId)) return null;
2309        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2310        synchronized (mPackages) {
2311            PackageParser.Activity a = mReceivers.mActivities.get(component);
2312            if (DEBUG_PACKAGE_INFO) Log.v(
2313                TAG, "getReceiverInfo " + 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        }
2321        return null;
2322    }
2323
2324    @Override
2325    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2326        if (!sUserManager.exists(userId)) return null;
2327        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2328        synchronized (mPackages) {
2329            PackageParser.Service s = mServices.mServices.get(component);
2330            if (DEBUG_PACKAGE_INFO) Log.v(
2331                TAG, "getServiceInfo " + component + ": " + s);
2332            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2333                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2334                if (ps == null) return null;
2335                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2336                        userId);
2337            }
2338        }
2339        return null;
2340    }
2341
2342    @Override
2343    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2344        if (!sUserManager.exists(userId)) return null;
2345        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2346        synchronized (mPackages) {
2347            PackageParser.Provider p = mProviders.mProviders.get(component);
2348            if (DEBUG_PACKAGE_INFO) Log.v(
2349                TAG, "getProviderInfo " + component + ": " + p);
2350            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2351                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2352                if (ps == null) return null;
2353                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2354                        userId);
2355            }
2356        }
2357        return null;
2358    }
2359
2360    @Override
2361    public String[] getSystemSharedLibraryNames() {
2362        Set<String> libSet;
2363        synchronized (mPackages) {
2364            libSet = mSharedLibraries.keySet();
2365            int size = libSet.size();
2366            if (size > 0) {
2367                String[] libs = new String[size];
2368                libSet.toArray(libs);
2369                return libs;
2370            }
2371        }
2372        return null;
2373    }
2374
2375    @Override
2376    public FeatureInfo[] getSystemAvailableFeatures() {
2377        Collection<FeatureInfo> featSet;
2378        synchronized (mPackages) {
2379            featSet = mAvailableFeatures.values();
2380            int size = featSet.size();
2381            if (size > 0) {
2382                FeatureInfo[] features = new FeatureInfo[size+1];
2383                featSet.toArray(features);
2384                FeatureInfo fi = new FeatureInfo();
2385                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2386                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2387                features[size] = fi;
2388                return features;
2389            }
2390        }
2391        return null;
2392    }
2393
2394    @Override
2395    public boolean hasSystemFeature(String name) {
2396        synchronized (mPackages) {
2397            return mAvailableFeatures.containsKey(name);
2398        }
2399    }
2400
2401    private void checkValidCaller(int uid, int userId) {
2402        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2403            return;
2404
2405        throw new SecurityException("Caller uid=" + uid
2406                + " is not privileged to communicate with user=" + userId);
2407    }
2408
2409    @Override
2410    public int checkPermission(String permName, String pkgName) {
2411        synchronized (mPackages) {
2412            PackageParser.Package p = mPackages.get(pkgName);
2413            if (p != null && p.mExtras != null) {
2414                PackageSetting ps = (PackageSetting)p.mExtras;
2415                if (ps.sharedUser != null) {
2416                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2417                        return PackageManager.PERMISSION_GRANTED;
2418                    }
2419                } else if (ps.grantedPermissions.contains(permName)) {
2420                    return PackageManager.PERMISSION_GRANTED;
2421                }
2422            }
2423        }
2424        return PackageManager.PERMISSION_DENIED;
2425    }
2426
2427    @Override
2428    public int checkUidPermission(String permName, int uid) {
2429        synchronized (mPackages) {
2430            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2431            if (obj != null) {
2432                GrantedPermissions gp = (GrantedPermissions)obj;
2433                if (gp.grantedPermissions.contains(permName)) {
2434                    return PackageManager.PERMISSION_GRANTED;
2435                }
2436            } else {
2437                HashSet<String> perms = mSystemPermissions.get(uid);
2438                if (perms != null && perms.contains(permName)) {
2439                    return PackageManager.PERMISSION_GRANTED;
2440                }
2441            }
2442        }
2443        return PackageManager.PERMISSION_DENIED;
2444    }
2445
2446    /**
2447     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2448     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2449     * @param message the message to log on security exception
2450     * @return
2451     */
2452    private void enforceCrossUserPermission(int callingUid, int userId,
2453            boolean requireFullPermission, String message) {
2454        if (userId < 0) {
2455            throw new IllegalArgumentException("Invalid userId " + userId);
2456        }
2457        if (userId == UserHandle.getUserId(callingUid)) return;
2458        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2459            if (requireFullPermission) {
2460                mContext.enforceCallingOrSelfPermission(
2461                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2462            } else {
2463                try {
2464                    mContext.enforceCallingOrSelfPermission(
2465                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2466                } catch (SecurityException se) {
2467                    mContext.enforceCallingOrSelfPermission(
2468                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2469                }
2470            }
2471        }
2472    }
2473
2474    private BasePermission findPermissionTreeLP(String permName) {
2475        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2476            if (permName.startsWith(bp.name) &&
2477                    permName.length() > bp.name.length() &&
2478                    permName.charAt(bp.name.length()) == '.') {
2479                return bp;
2480            }
2481        }
2482        return null;
2483    }
2484
2485    private BasePermission checkPermissionTreeLP(String permName) {
2486        if (permName != null) {
2487            BasePermission bp = findPermissionTreeLP(permName);
2488            if (bp != null) {
2489                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2490                    return bp;
2491                }
2492                throw new SecurityException("Calling uid "
2493                        + Binder.getCallingUid()
2494                        + " is not allowed to add to permission tree "
2495                        + bp.name + " owned by uid " + bp.uid);
2496            }
2497        }
2498        throw new SecurityException("No permission tree found for " + permName);
2499    }
2500
2501    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2502        if (s1 == null) {
2503            return s2 == null;
2504        }
2505        if (s2 == null) {
2506            return false;
2507        }
2508        if (s1.getClass() != s2.getClass()) {
2509            return false;
2510        }
2511        return s1.equals(s2);
2512    }
2513
2514    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2515        if (pi1.icon != pi2.icon) return false;
2516        if (pi1.logo != pi2.logo) return false;
2517        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2518        if (!compareStrings(pi1.name, pi2.name)) return false;
2519        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2520        // We'll take care of setting this one.
2521        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2522        // These are not currently stored in settings.
2523        //if (!compareStrings(pi1.group, pi2.group)) return false;
2524        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2525        //if (pi1.labelRes != pi2.labelRes) return false;
2526        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2527        return true;
2528    }
2529
2530    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2531        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2532            throw new SecurityException("Label must be specified in permission");
2533        }
2534        BasePermission tree = checkPermissionTreeLP(info.name);
2535        BasePermission bp = mSettings.mPermissions.get(info.name);
2536        boolean added = bp == null;
2537        boolean changed = true;
2538        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2539        if (added) {
2540            bp = new BasePermission(info.name, tree.sourcePackage,
2541                    BasePermission.TYPE_DYNAMIC);
2542        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2543            throw new SecurityException(
2544                    "Not allowed to modify non-dynamic permission "
2545                    + info.name);
2546        } else {
2547            if (bp.protectionLevel == fixedLevel
2548                    && bp.perm.owner.equals(tree.perm.owner)
2549                    && bp.uid == tree.uid
2550                    && comparePermissionInfos(bp.perm.info, info)) {
2551                changed = false;
2552            }
2553        }
2554        bp.protectionLevel = fixedLevel;
2555        info = new PermissionInfo(info);
2556        info.protectionLevel = fixedLevel;
2557        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2558        bp.perm.info.packageName = tree.perm.info.packageName;
2559        bp.uid = tree.uid;
2560        if (added) {
2561            mSettings.mPermissions.put(info.name, bp);
2562        }
2563        if (changed) {
2564            if (!async) {
2565                mSettings.writeLPr();
2566            } else {
2567                scheduleWriteSettingsLocked();
2568            }
2569        }
2570        return added;
2571    }
2572
2573    @Override
2574    public boolean addPermission(PermissionInfo info) {
2575        synchronized (mPackages) {
2576            return addPermissionLocked(info, false);
2577        }
2578    }
2579
2580    @Override
2581    public boolean addPermissionAsync(PermissionInfo info) {
2582        synchronized (mPackages) {
2583            return addPermissionLocked(info, true);
2584        }
2585    }
2586
2587    @Override
2588    public void removePermission(String name) {
2589        synchronized (mPackages) {
2590            checkPermissionTreeLP(name);
2591            BasePermission bp = mSettings.mPermissions.get(name);
2592            if (bp != null) {
2593                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2594                    throw new SecurityException(
2595                            "Not allowed to modify non-dynamic permission "
2596                            + name);
2597                }
2598                mSettings.mPermissions.remove(name);
2599                mSettings.writeLPr();
2600            }
2601        }
2602    }
2603
2604    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2605        int index = pkg.requestedPermissions.indexOf(bp.name);
2606        if (index == -1) {
2607            throw new SecurityException("Package " + pkg.packageName
2608                    + " has not requested permission " + bp.name);
2609        }
2610        boolean isNormal =
2611                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2612                        == PermissionInfo.PROTECTION_NORMAL);
2613        boolean isDangerous =
2614                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2615                        == PermissionInfo.PROTECTION_DANGEROUS);
2616        boolean isDevelopment =
2617                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2618
2619        if (!isNormal && !isDangerous && !isDevelopment) {
2620            throw new SecurityException("Permission " + bp.name
2621                    + " is not a changeable permission type");
2622        }
2623
2624        if (isNormal || isDangerous) {
2625            if (pkg.requestedPermissionsRequired.get(index)) {
2626                throw new SecurityException("Can't change " + bp.name
2627                        + ". It is required by the application");
2628            }
2629        }
2630    }
2631
2632    @Override
2633    public void grantPermission(String packageName, String permissionName) {
2634        mContext.enforceCallingOrSelfPermission(
2635                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2636        synchronized (mPackages) {
2637            final PackageParser.Package pkg = mPackages.get(packageName);
2638            if (pkg == null) {
2639                throw new IllegalArgumentException("Unknown package: " + packageName);
2640            }
2641            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2642            if (bp == null) {
2643                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2644            }
2645
2646            checkGrantRevokePermissions(pkg, bp);
2647
2648            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2649            if (ps == null) {
2650                return;
2651            }
2652            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2653            if (gp.grantedPermissions.add(permissionName)) {
2654                if (ps.haveGids) {
2655                    gp.gids = appendInts(gp.gids, bp.gids);
2656                }
2657                mSettings.writeLPr();
2658            }
2659        }
2660    }
2661
2662    @Override
2663    public void revokePermission(String packageName, String permissionName) {
2664        int changedAppId = -1;
2665
2666        synchronized (mPackages) {
2667            final PackageParser.Package pkg = mPackages.get(packageName);
2668            if (pkg == null) {
2669                throw new IllegalArgumentException("Unknown package: " + packageName);
2670            }
2671            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2672                mContext.enforceCallingOrSelfPermission(
2673                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2674            }
2675            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2676            if (bp == null) {
2677                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2678            }
2679
2680            checkGrantRevokePermissions(pkg, bp);
2681
2682            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2683            if (ps == null) {
2684                return;
2685            }
2686            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2687            if (gp.grantedPermissions.remove(permissionName)) {
2688                gp.grantedPermissions.remove(permissionName);
2689                if (ps.haveGids) {
2690                    gp.gids = removeInts(gp.gids, bp.gids);
2691                }
2692                mSettings.writeLPr();
2693                changedAppId = ps.appId;
2694            }
2695        }
2696
2697        if (changedAppId >= 0) {
2698            // We changed the perm on someone, kill its processes.
2699            IActivityManager am = ActivityManagerNative.getDefault();
2700            if (am != null) {
2701                final int callingUserId = UserHandle.getCallingUserId();
2702                final long ident = Binder.clearCallingIdentity();
2703                try {
2704                    //XXX we should only revoke for the calling user's app permissions,
2705                    // but for now we impact all users.
2706                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2707                    //        "revoke " + permissionName);
2708                    int[] users = sUserManager.getUserIds();
2709                    for (int user : users) {
2710                        am.killUid(UserHandle.getUid(user, changedAppId),
2711                                "revoke " + permissionName);
2712                    }
2713                } catch (RemoteException e) {
2714                } finally {
2715                    Binder.restoreCallingIdentity(ident);
2716                }
2717            }
2718        }
2719    }
2720
2721    @Override
2722    public boolean isProtectedBroadcast(String actionName) {
2723        synchronized (mPackages) {
2724            return mProtectedBroadcasts.contains(actionName);
2725        }
2726    }
2727
2728    @Override
2729    public int checkSignatures(String pkg1, String pkg2) {
2730        synchronized (mPackages) {
2731            final PackageParser.Package p1 = mPackages.get(pkg1);
2732            final PackageParser.Package p2 = mPackages.get(pkg2);
2733            if (p1 == null || p1.mExtras == null
2734                    || p2 == null || p2.mExtras == null) {
2735                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2736            }
2737            return compareSignatures(p1.mSignatures, p2.mSignatures);
2738        }
2739    }
2740
2741    @Override
2742    public int checkUidSignatures(int uid1, int uid2) {
2743        // Map to base uids.
2744        uid1 = UserHandle.getAppId(uid1);
2745        uid2 = UserHandle.getAppId(uid2);
2746        // reader
2747        synchronized (mPackages) {
2748            Signature[] s1;
2749            Signature[] s2;
2750            Object obj = mSettings.getUserIdLPr(uid1);
2751            if (obj != null) {
2752                if (obj instanceof SharedUserSetting) {
2753                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2754                } else if (obj instanceof PackageSetting) {
2755                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2756                } else {
2757                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2758                }
2759            } else {
2760                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2761            }
2762            obj = mSettings.getUserIdLPr(uid2);
2763            if (obj != null) {
2764                if (obj instanceof SharedUserSetting) {
2765                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2766                } else if (obj instanceof PackageSetting) {
2767                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2768                } else {
2769                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2770                }
2771            } else {
2772                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2773            }
2774            return compareSignatures(s1, s2);
2775        }
2776    }
2777
2778    /**
2779     * Compares two sets of signatures. Returns:
2780     * <br />
2781     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2782     * <br />
2783     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2784     * <br />
2785     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2786     * <br />
2787     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2788     * <br />
2789     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2790     */
2791    static int compareSignatures(Signature[] s1, Signature[] s2) {
2792        if (s1 == null) {
2793            return s2 == null
2794                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2795                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2796        }
2797
2798        if (s2 == null) {
2799            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2800        }
2801
2802        if (s1.length != s2.length) {
2803            return PackageManager.SIGNATURE_NO_MATCH;
2804        }
2805
2806        // Since both signature sets are of size 1, we can compare without HashSets.
2807        if (s1.length == 1) {
2808            return s1[0].equals(s2[0]) ?
2809                    PackageManager.SIGNATURE_MATCH :
2810                    PackageManager.SIGNATURE_NO_MATCH;
2811        }
2812
2813        HashSet<Signature> set1 = new HashSet<Signature>();
2814        for (Signature sig : s1) {
2815            set1.add(sig);
2816        }
2817        HashSet<Signature> set2 = new HashSet<Signature>();
2818        for (Signature sig : s2) {
2819            set2.add(sig);
2820        }
2821        // Make sure s2 contains all signatures in s1.
2822        if (set1.equals(set2)) {
2823            return PackageManager.SIGNATURE_MATCH;
2824        }
2825        return PackageManager.SIGNATURE_NO_MATCH;
2826    }
2827
2828    @Override
2829    public String[] getPackagesForUid(int uid) {
2830        uid = UserHandle.getAppId(uid);
2831        // reader
2832        synchronized (mPackages) {
2833            Object obj = mSettings.getUserIdLPr(uid);
2834            if (obj instanceof SharedUserSetting) {
2835                final SharedUserSetting sus = (SharedUserSetting) obj;
2836                final int N = sus.packages.size();
2837                final String[] res = new String[N];
2838                final Iterator<PackageSetting> it = sus.packages.iterator();
2839                int i = 0;
2840                while (it.hasNext()) {
2841                    res[i++] = it.next().name;
2842                }
2843                return res;
2844            } else if (obj instanceof PackageSetting) {
2845                final PackageSetting ps = (PackageSetting) obj;
2846                return new String[] { ps.name };
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public String getNameForUid(int uid) {
2854        // reader
2855        synchronized (mPackages) {
2856            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2857            if (obj instanceof SharedUserSetting) {
2858                final SharedUserSetting sus = (SharedUserSetting) obj;
2859                return sus.name + ":" + sus.userId;
2860            } else if (obj instanceof PackageSetting) {
2861                final PackageSetting ps = (PackageSetting) obj;
2862                return ps.name;
2863            }
2864        }
2865        return null;
2866    }
2867
2868    @Override
2869    public int getUidForSharedUser(String sharedUserName) {
2870        if(sharedUserName == null) {
2871            return -1;
2872        }
2873        // reader
2874        synchronized (mPackages) {
2875            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2876            if (suid == null) {
2877                return -1;
2878            }
2879            return suid.userId;
2880        }
2881    }
2882
2883    @Override
2884    public int getFlagsForUid(int uid) {
2885        synchronized (mPackages) {
2886            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2887            if (obj instanceof SharedUserSetting) {
2888                final SharedUserSetting sus = (SharedUserSetting) obj;
2889                return sus.pkgFlags;
2890            } else if (obj instanceof PackageSetting) {
2891                final PackageSetting ps = (PackageSetting) obj;
2892                return ps.pkgFlags;
2893            }
2894        }
2895        return 0;
2896    }
2897
2898    @Override
2899    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2900            int flags, int userId) {
2901        if (!sUserManager.exists(userId)) return null;
2902        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2903        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2904        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2905    }
2906
2907    @Override
2908    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2909            IntentFilter filter, int match, ComponentName activity) {
2910        final int userId = UserHandle.getCallingUserId();
2911        if (DEBUG_PREFERRED) {
2912            Log.v(TAG, "setLastChosenActivity intent=" + intent
2913                + " resolvedType=" + resolvedType
2914                + " flags=" + flags
2915                + " filter=" + filter
2916                + " match=" + match
2917                + " activity=" + activity);
2918            filter.dump(new PrintStreamPrinter(System.out), "    ");
2919        }
2920        intent.setComponent(null);
2921        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2922        // Find any earlier preferred or last chosen entries and nuke them
2923        findPreferredActivity(intent, resolvedType,
2924                flags, query, 0, false, true, false, userId);
2925        // Add the new activity as the last chosen for this filter
2926        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2927    }
2928
2929    @Override
2930    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2931        final int userId = UserHandle.getCallingUserId();
2932        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2933        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2934        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2935                false, false, false, userId);
2936    }
2937
2938    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2939            int flags, List<ResolveInfo> query, int userId) {
2940        if (query != null) {
2941            final int N = query.size();
2942            if (N == 1) {
2943                return query.get(0);
2944            } else if (N > 1) {
2945                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2946                // If there is more than one activity with the same priority,
2947                // then let the user decide between them.
2948                ResolveInfo r0 = query.get(0);
2949                ResolveInfo r1 = query.get(1);
2950                if (DEBUG_INTENT_MATCHING || debug) {
2951                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2952                            + r1.activityInfo.name + "=" + r1.priority);
2953                }
2954                // If the first activity has a higher priority, or a different
2955                // default, then it is always desireable to pick it.
2956                if (r0.priority != r1.priority
2957                        || r0.preferredOrder != r1.preferredOrder
2958                        || r0.isDefault != r1.isDefault) {
2959                    return query.get(0);
2960                }
2961                // If we have saved a preference for a preferred activity for
2962                // this Intent, use that.
2963                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2964                        flags, query, r0.priority, true, false, debug, userId);
2965                if (ri != null) {
2966                    return ri;
2967                }
2968                if (userId != 0) {
2969                    ri = new ResolveInfo(mResolveInfo);
2970                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2971                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2972                            ri.activityInfo.applicationInfo);
2973                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2974                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2975                    return ri;
2976                }
2977                return mResolveInfo;
2978            }
2979        }
2980        return null;
2981    }
2982
2983    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
2984            List<ResolveInfo> query, int priority, boolean always,
2985            boolean removeMatches, boolean debug, int userId) {
2986        if (!sUserManager.exists(userId)) return null;
2987        // writer
2988        synchronized (mPackages) {
2989            if (intent.getSelector() != null) {
2990                intent = intent.getSelector();
2991            }
2992            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2993            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2994            // Get the list of preferred activities that handle the intent
2995            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
2996            List<PreferredActivity> prefs = pir != null
2997                    ? pir.queryIntent(intent, resolvedType,
2998                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2999                    : null;
3000            if (prefs != null && prefs.size() > 0) {
3001                // First figure out how good the original match set is.
3002                // We will only allow preferred activities that came
3003                // from the same match quality.
3004                int match = 0;
3005
3006                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3007
3008                final int N = query.size();
3009                for (int j=0; j<N; j++) {
3010                    final ResolveInfo ri = query.get(j);
3011                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3012                            + ": 0x" + Integer.toHexString(match));
3013                    if (ri.match > match) {
3014                        match = ri.match;
3015                    }
3016                }
3017
3018                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3019                        + Integer.toHexString(match));
3020
3021                match &= IntentFilter.MATCH_CATEGORY_MASK;
3022                final int M = prefs.size();
3023                for (int i=0; i<M; i++) {
3024                    final PreferredActivity pa = prefs.get(i);
3025                    if (DEBUG_PREFERRED || debug) {
3026                        Slog.v(TAG, "Checking PreferredActivity ds="
3027                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3028                                + "\n  component=" + pa.mPref.mComponent);
3029                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3030                    }
3031                    if (pa.mPref.mMatch != match) {
3032                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3033                                + Integer.toHexString(pa.mPref.mMatch));
3034                        continue;
3035                    }
3036                    // If it's not an "always" type preferred activity and that's what we're
3037                    // looking for, skip it.
3038                    if (always && !pa.mPref.mAlways) {
3039                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3040                        continue;
3041                    }
3042                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3043                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3044                    if (DEBUG_PREFERRED || debug) {
3045                        Slog.v(TAG, "Found preferred activity:");
3046                        if (ai != null) {
3047                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3048                        } else {
3049                            Slog.v(TAG, "  null");
3050                        }
3051                    }
3052                    if (ai == null) {
3053                        // This previously registered preferred activity
3054                        // component is no longer known.  Most likely an update
3055                        // to the app was installed and in the new version this
3056                        // component no longer exists.  Clean it up by removing
3057                        // it from the preferred activities list, and skip it.
3058                        Slog.w(TAG, "Removing dangling preferred activity: "
3059                                + pa.mPref.mComponent);
3060                        pir.removeFilter(pa);
3061                        continue;
3062                    }
3063                    for (int j=0; j<N; j++) {
3064                        final ResolveInfo ri = query.get(j);
3065                        if (!ri.activityInfo.applicationInfo.packageName
3066                                .equals(ai.applicationInfo.packageName)) {
3067                            continue;
3068                        }
3069                        if (!ri.activityInfo.name.equals(ai.name)) {
3070                            continue;
3071                        }
3072
3073                        if (removeMatches) {
3074                            pir.removeFilter(pa);
3075                            if (DEBUG_PREFERRED) {
3076                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3077                            }
3078                            break;
3079                        }
3080
3081                        // Okay we found a previously set preferred or last chosen app.
3082                        // If the result set is different from when this
3083                        // was created, we need to clear it and re-ask the
3084                        // user their preference, if we're looking for an "always" type entry.
3085                        if (always && !pa.mPref.sameSet(query, priority)) {
3086                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3087                                    + intent + " type " + resolvedType);
3088                            if (DEBUG_PREFERRED) {
3089                                Slog.v(TAG, "Removing preferred activity since set changed "
3090                                        + pa.mPref.mComponent);
3091                            }
3092                            pir.removeFilter(pa);
3093                            // Re-add the filter as a "last chosen" entry (!always)
3094                            PreferredActivity lastChosen = new PreferredActivity(
3095                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3096                            pir.addFilter(lastChosen);
3097                            mSettings.writePackageRestrictionsLPr(userId);
3098                            return null;
3099                        }
3100
3101                        // Yay! Either the set matched or we're looking for the last chosen
3102                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3103                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3104                        mSettings.writePackageRestrictionsLPr(userId);
3105                        return ri;
3106                    }
3107                }
3108            }
3109            mSettings.writePackageRestrictionsLPr(userId);
3110        }
3111        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3112        return null;
3113    }
3114
3115    @Override
3116    public List<ResolveInfo> queryIntentActivities(Intent intent,
3117            String resolvedType, int flags, int userId) {
3118        if (!sUserManager.exists(userId)) return Collections.emptyList();
3119        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3120        ComponentName comp = intent.getComponent();
3121        if (comp == null) {
3122            if (intent.getSelector() != null) {
3123                intent = intent.getSelector();
3124                comp = intent.getComponent();
3125            }
3126        }
3127
3128        if (comp != null) {
3129            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3130            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3131            if (ai != null) {
3132                final ResolveInfo ri = new ResolveInfo();
3133                ri.activityInfo = ai;
3134                list.add(ri);
3135            }
3136            return list;
3137        }
3138
3139        // reader
3140        synchronized (mPackages) {
3141            final String pkgName = intent.getPackage();
3142            if (pkgName == null) {
3143                return mActivities.queryIntent(intent, resolvedType, flags, userId);
3144            }
3145            final PackageParser.Package pkg = mPackages.get(pkgName);
3146            if (pkg != null) {
3147                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3148                        pkg.activities, userId);
3149            }
3150            return new ArrayList<ResolveInfo>();
3151        }
3152    }
3153
3154    @Override
3155    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3156            Intent[] specifics, String[] specificTypes, Intent intent,
3157            String resolvedType, int flags, int userId) {
3158        if (!sUserManager.exists(userId)) return Collections.emptyList();
3159        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3160                "query intent activity options");
3161        final String resultsAction = intent.getAction();
3162
3163        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3164                | PackageManager.GET_RESOLVED_FILTER, userId);
3165
3166        if (DEBUG_INTENT_MATCHING) {
3167            Log.v(TAG, "Query " + intent + ": " + results);
3168        }
3169
3170        int specificsPos = 0;
3171        int N;
3172
3173        // todo: note that the algorithm used here is O(N^2).  This
3174        // isn't a problem in our current environment, but if we start running
3175        // into situations where we have more than 5 or 10 matches then this
3176        // should probably be changed to something smarter...
3177
3178        // First we go through and resolve each of the specific items
3179        // that were supplied, taking care of removing any corresponding
3180        // duplicate items in the generic resolve list.
3181        if (specifics != null) {
3182            for (int i=0; i<specifics.length; i++) {
3183                final Intent sintent = specifics[i];
3184                if (sintent == null) {
3185                    continue;
3186                }
3187
3188                if (DEBUG_INTENT_MATCHING) {
3189                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3190                }
3191
3192                String action = sintent.getAction();
3193                if (resultsAction != null && resultsAction.equals(action)) {
3194                    // If this action was explicitly requested, then don't
3195                    // remove things that have it.
3196                    action = null;
3197                }
3198
3199                ResolveInfo ri = null;
3200                ActivityInfo ai = null;
3201
3202                ComponentName comp = sintent.getComponent();
3203                if (comp == null) {
3204                    ri = resolveIntent(
3205                        sintent,
3206                        specificTypes != null ? specificTypes[i] : null,
3207                            flags, userId);
3208                    if (ri == null) {
3209                        continue;
3210                    }
3211                    if (ri == mResolveInfo) {
3212                        // ACK!  Must do something better with this.
3213                    }
3214                    ai = ri.activityInfo;
3215                    comp = new ComponentName(ai.applicationInfo.packageName,
3216                            ai.name);
3217                } else {
3218                    ai = getActivityInfo(comp, flags, userId);
3219                    if (ai == null) {
3220                        continue;
3221                    }
3222                }
3223
3224                // Look for any generic query activities that are duplicates
3225                // of this specific one, and remove them from the results.
3226                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3227                N = results.size();
3228                int j;
3229                for (j=specificsPos; j<N; j++) {
3230                    ResolveInfo sri = results.get(j);
3231                    if ((sri.activityInfo.name.equals(comp.getClassName())
3232                            && sri.activityInfo.applicationInfo.packageName.equals(
3233                                    comp.getPackageName()))
3234                        || (action != null && sri.filter.matchAction(action))) {
3235                        results.remove(j);
3236                        if (DEBUG_INTENT_MATCHING) Log.v(
3237                            TAG, "Removing duplicate item from " + j
3238                            + " due to specific " + specificsPos);
3239                        if (ri == null) {
3240                            ri = sri;
3241                        }
3242                        j--;
3243                        N--;
3244                    }
3245                }
3246
3247                // Add this specific item to its proper place.
3248                if (ri == null) {
3249                    ri = new ResolveInfo();
3250                    ri.activityInfo = ai;
3251                }
3252                results.add(specificsPos, ri);
3253                ri.specificIndex = i;
3254                specificsPos++;
3255            }
3256        }
3257
3258        // Now we go through the remaining generic results and remove any
3259        // duplicate actions that are found here.
3260        N = results.size();
3261        for (int i=specificsPos; i<N-1; i++) {
3262            final ResolveInfo rii = results.get(i);
3263            if (rii.filter == null) {
3264                continue;
3265            }
3266
3267            // Iterate over all of the actions of this result's intent
3268            // filter...  typically this should be just one.
3269            final Iterator<String> it = rii.filter.actionsIterator();
3270            if (it == null) {
3271                continue;
3272            }
3273            while (it.hasNext()) {
3274                final String action = it.next();
3275                if (resultsAction != null && resultsAction.equals(action)) {
3276                    // If this action was explicitly requested, then don't
3277                    // remove things that have it.
3278                    continue;
3279                }
3280                for (int j=i+1; j<N; j++) {
3281                    final ResolveInfo rij = results.get(j);
3282                    if (rij.filter != null && rij.filter.hasAction(action)) {
3283                        results.remove(j);
3284                        if (DEBUG_INTENT_MATCHING) Log.v(
3285                            TAG, "Removing duplicate item from " + j
3286                            + " due to action " + action + " at " + i);
3287                        j--;
3288                        N--;
3289                    }
3290                }
3291            }
3292
3293            // If the caller didn't request filter information, drop it now
3294            // so we don't have to marshall/unmarshall it.
3295            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3296                rii.filter = null;
3297            }
3298        }
3299
3300        // Filter out the caller activity if so requested.
3301        if (caller != null) {
3302            N = results.size();
3303            for (int i=0; i<N; i++) {
3304                ActivityInfo ainfo = results.get(i).activityInfo;
3305                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3306                        && caller.getClassName().equals(ainfo.name)) {
3307                    results.remove(i);
3308                    break;
3309                }
3310            }
3311        }
3312
3313        // If the caller didn't request filter information,
3314        // drop them now so we don't have to
3315        // marshall/unmarshall it.
3316        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3317            N = results.size();
3318            for (int i=0; i<N; i++) {
3319                results.get(i).filter = null;
3320            }
3321        }
3322
3323        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3324        return results;
3325    }
3326
3327    @Override
3328    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3329            int userId) {
3330        if (!sUserManager.exists(userId)) return Collections.emptyList();
3331        ComponentName comp = intent.getComponent();
3332        if (comp == null) {
3333            if (intent.getSelector() != null) {
3334                intent = intent.getSelector();
3335                comp = intent.getComponent();
3336            }
3337        }
3338        if (comp != null) {
3339            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3340            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3341            if (ai != null) {
3342                ResolveInfo ri = new ResolveInfo();
3343                ri.activityInfo = ai;
3344                list.add(ri);
3345            }
3346            return list;
3347        }
3348
3349        // reader
3350        synchronized (mPackages) {
3351            String pkgName = intent.getPackage();
3352            if (pkgName == null) {
3353                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3354            }
3355            final PackageParser.Package pkg = mPackages.get(pkgName);
3356            if (pkg != null) {
3357                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3358                        userId);
3359            }
3360            return null;
3361        }
3362    }
3363
3364    @Override
3365    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3366        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3367        if (!sUserManager.exists(userId)) return null;
3368        if (query != null) {
3369            if (query.size() >= 1) {
3370                // If there is more than one service with the same priority,
3371                // just arbitrarily pick the first one.
3372                return query.get(0);
3373            }
3374        }
3375        return null;
3376    }
3377
3378    @Override
3379    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3380            int userId) {
3381        if (!sUserManager.exists(userId)) return Collections.emptyList();
3382        ComponentName comp = intent.getComponent();
3383        if (comp == null) {
3384            if (intent.getSelector() != null) {
3385                intent = intent.getSelector();
3386                comp = intent.getComponent();
3387            }
3388        }
3389        if (comp != null) {
3390            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3391            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3392            if (si != null) {
3393                final ResolveInfo ri = new ResolveInfo();
3394                ri.serviceInfo = si;
3395                list.add(ri);
3396            }
3397            return list;
3398        }
3399
3400        // reader
3401        synchronized (mPackages) {
3402            String pkgName = intent.getPackage();
3403            if (pkgName == null) {
3404                return mServices.queryIntent(intent, resolvedType, flags, userId);
3405            }
3406            final PackageParser.Package pkg = mPackages.get(pkgName);
3407            if (pkg != null) {
3408                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3409                        userId);
3410            }
3411            return null;
3412        }
3413    }
3414
3415    @Override
3416    public List<ResolveInfo> queryIntentContentProviders(
3417            Intent intent, String resolvedType, int flags, int userId) {
3418        if (!sUserManager.exists(userId)) return Collections.emptyList();
3419        ComponentName comp = intent.getComponent();
3420        if (comp == null) {
3421            if (intent.getSelector() != null) {
3422                intent = intent.getSelector();
3423                comp = intent.getComponent();
3424            }
3425        }
3426        if (comp != null) {
3427            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3428            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3429            if (pi != null) {
3430                final ResolveInfo ri = new ResolveInfo();
3431                ri.providerInfo = pi;
3432                list.add(ri);
3433            }
3434            return list;
3435        }
3436
3437        // reader
3438        synchronized (mPackages) {
3439            String pkgName = intent.getPackage();
3440            if (pkgName == null) {
3441                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3442            }
3443            final PackageParser.Package pkg = mPackages.get(pkgName);
3444            if (pkg != null) {
3445                return mProviders.queryIntentForPackage(
3446                        intent, resolvedType, flags, pkg.providers, userId);
3447            }
3448            return null;
3449        }
3450    }
3451
3452    @Override
3453    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3454        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3455
3456        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3457
3458        // writer
3459        synchronized (mPackages) {
3460            ArrayList<PackageInfo> list;
3461            if (listUninstalled) {
3462                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3463                for (PackageSetting ps : mSettings.mPackages.values()) {
3464                    PackageInfo pi;
3465                    if (ps.pkg != null) {
3466                        pi = generatePackageInfo(ps.pkg, flags, userId);
3467                    } else {
3468                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3469                    }
3470                    if (pi != null) {
3471                        list.add(pi);
3472                    }
3473                }
3474            } else {
3475                list = new ArrayList<PackageInfo>(mPackages.size());
3476                for (PackageParser.Package p : mPackages.values()) {
3477                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3478                    if (pi != null) {
3479                        list.add(pi);
3480                    }
3481                }
3482            }
3483
3484            return new ParceledListSlice<PackageInfo>(list);
3485        }
3486    }
3487
3488    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3489            String[] permissions, boolean[] tmp, int flags, int userId) {
3490        int numMatch = 0;
3491        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3492        for (int i=0; i<permissions.length; i++) {
3493            if (gp.grantedPermissions.contains(permissions[i])) {
3494                tmp[i] = true;
3495                numMatch++;
3496            } else {
3497                tmp[i] = false;
3498            }
3499        }
3500        if (numMatch == 0) {
3501            return;
3502        }
3503        PackageInfo pi;
3504        if (ps.pkg != null) {
3505            pi = generatePackageInfo(ps.pkg, flags, userId);
3506        } else {
3507            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3508        }
3509        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3510            if (numMatch == permissions.length) {
3511                pi.requestedPermissions = permissions;
3512            } else {
3513                pi.requestedPermissions = new String[numMatch];
3514                numMatch = 0;
3515                for (int i=0; i<permissions.length; i++) {
3516                    if (tmp[i]) {
3517                        pi.requestedPermissions[numMatch] = permissions[i];
3518                        numMatch++;
3519                    }
3520                }
3521            }
3522        }
3523        list.add(pi);
3524    }
3525
3526    @Override
3527    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3528            String[] permissions, int flags, int userId) {
3529        if (!sUserManager.exists(userId)) return null;
3530        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3531
3532        // writer
3533        synchronized (mPackages) {
3534            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3535            boolean[] tmpBools = new boolean[permissions.length];
3536            if (listUninstalled) {
3537                for (PackageSetting ps : mSettings.mPackages.values()) {
3538                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3539                }
3540            } else {
3541                for (PackageParser.Package pkg : mPackages.values()) {
3542                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3543                    if (ps != null) {
3544                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3545                                userId);
3546                    }
3547                }
3548            }
3549
3550            return new ParceledListSlice<PackageInfo>(list);
3551        }
3552    }
3553
3554    @Override
3555    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3556        if (!sUserManager.exists(userId)) return null;
3557        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3558
3559        // writer
3560        synchronized (mPackages) {
3561            ArrayList<ApplicationInfo> list;
3562            if (listUninstalled) {
3563                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3564                for (PackageSetting ps : mSettings.mPackages.values()) {
3565                    ApplicationInfo ai;
3566                    if (ps.pkg != null) {
3567                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3568                                ps.readUserState(userId), userId);
3569                    } else {
3570                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3571                    }
3572                    if (ai != null) {
3573                        list.add(ai);
3574                    }
3575                }
3576            } else {
3577                list = new ArrayList<ApplicationInfo>(mPackages.size());
3578                for (PackageParser.Package p : mPackages.values()) {
3579                    if (p.mExtras != null) {
3580                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3581                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3582                        if (ai != null) {
3583                            list.add(ai);
3584                        }
3585                    }
3586                }
3587            }
3588
3589            return new ParceledListSlice<ApplicationInfo>(list);
3590        }
3591    }
3592
3593    public List<ApplicationInfo> getPersistentApplications(int flags) {
3594        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3595
3596        // reader
3597        synchronized (mPackages) {
3598            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3599            final int userId = UserHandle.getCallingUserId();
3600            while (i.hasNext()) {
3601                final PackageParser.Package p = i.next();
3602                if (p.applicationInfo != null
3603                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3604                        && (!mSafeMode || isSystemApp(p))) {
3605                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3606                    if (ps != null) {
3607                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3608                                ps.readUserState(userId), userId);
3609                        if (ai != null) {
3610                            finalList.add(ai);
3611                        }
3612                    }
3613                }
3614            }
3615        }
3616
3617        return finalList;
3618    }
3619
3620    @Override
3621    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3622        if (!sUserManager.exists(userId)) return null;
3623        // reader
3624        synchronized (mPackages) {
3625            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3626            PackageSetting ps = provider != null
3627                    ? mSettings.mPackages.get(provider.owner.packageName)
3628                    : null;
3629            return ps != null
3630                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3631                    && (!mSafeMode || (provider.info.applicationInfo.flags
3632                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3633                    ? PackageParser.generateProviderInfo(provider, flags,
3634                            ps.readUserState(userId), userId)
3635                    : null;
3636        }
3637    }
3638
3639    /**
3640     * @deprecated
3641     */
3642    @Deprecated
3643    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3644        // reader
3645        synchronized (mPackages) {
3646            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3647                    .entrySet().iterator();
3648            final int userId = UserHandle.getCallingUserId();
3649            while (i.hasNext()) {
3650                Map.Entry<String, PackageParser.Provider> entry = i.next();
3651                PackageParser.Provider p = entry.getValue();
3652                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3653
3654                if (ps != null && p.syncable
3655                        && (!mSafeMode || (p.info.applicationInfo.flags
3656                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3657                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3658                            ps.readUserState(userId), userId);
3659                    if (info != null) {
3660                        outNames.add(entry.getKey());
3661                        outInfo.add(info);
3662                    }
3663                }
3664            }
3665        }
3666    }
3667
3668    @Override
3669    public List<ProviderInfo> queryContentProviders(String processName,
3670            int uid, int flags) {
3671        ArrayList<ProviderInfo> finalList = null;
3672        // reader
3673        synchronized (mPackages) {
3674            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3675            final int userId = processName != null ?
3676                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3677            while (i.hasNext()) {
3678                final PackageParser.Provider p = i.next();
3679                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3680                if (ps != null && p.info.authority != null
3681                        && (processName == null
3682                                || (p.info.processName.equals(processName)
3683                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3684                        && mSettings.isEnabledLPr(p.info, flags, userId)
3685                        && (!mSafeMode
3686                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3687                    if (finalList == null) {
3688                        finalList = new ArrayList<ProviderInfo>(3);
3689                    }
3690                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3691                            ps.readUserState(userId), userId);
3692                    if (info != null) {
3693                        finalList.add(info);
3694                    }
3695                }
3696            }
3697        }
3698
3699        if (finalList != null) {
3700            Collections.sort(finalList, mProviderInitOrderSorter);
3701        }
3702
3703        return finalList;
3704    }
3705
3706    @Override
3707    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3708            int flags) {
3709        // reader
3710        synchronized (mPackages) {
3711            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3712            return PackageParser.generateInstrumentationInfo(i, flags);
3713        }
3714    }
3715
3716    @Override
3717    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3718            int flags) {
3719        ArrayList<InstrumentationInfo> finalList =
3720            new ArrayList<InstrumentationInfo>();
3721
3722        // reader
3723        synchronized (mPackages) {
3724            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3725            while (i.hasNext()) {
3726                final PackageParser.Instrumentation p = i.next();
3727                if (targetPackage == null
3728                        || targetPackage.equals(p.info.targetPackage)) {
3729                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3730                            flags);
3731                    if (ii != null) {
3732                        finalList.add(ii);
3733                    }
3734                }
3735            }
3736        }
3737
3738        return finalList;
3739    }
3740
3741    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3742        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3743        if (overlays == null) {
3744            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3745            return;
3746        }
3747        for (PackageParser.Package opkg : overlays.values()) {
3748            // Not much to do if idmap fails: we already logged the error
3749            // and we certainly don't want to abort installation of pkg simply
3750            // because an overlay didn't fit properly. For these reasons,
3751            // ignore the return value of createIdmapForPackagePairLI.
3752            createIdmapForPackagePairLI(pkg, opkg);
3753        }
3754    }
3755
3756    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3757            PackageParser.Package opkg) {
3758        if (!opkg.mTrustedOverlay) {
3759            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3760                    opkg.mScanPath + ": overlay not trusted");
3761            return false;
3762        }
3763        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3764        if (overlaySet == null) {
3765            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3766                    opkg.mScanPath + " but target package has no known overlays");
3767            return false;
3768        }
3769        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3770        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3771            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3772            return false;
3773        }
3774        PackageParser.Package[] overlayArray =
3775            overlaySet.values().toArray(new PackageParser.Package[0]);
3776        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3777            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3778                return p1.mOverlayPriority - p2.mOverlayPriority;
3779            }
3780        };
3781        Arrays.sort(overlayArray, cmp);
3782
3783        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3784        int i = 0;
3785        for (PackageParser.Package p : overlayArray) {
3786            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3787        }
3788        return true;
3789    }
3790
3791    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3792        String[] files = dir.list();
3793        if (files == null) {
3794            Log.d(TAG, "No files in app dir " + dir);
3795            return;
3796        }
3797
3798        if (DEBUG_PACKAGE_SCANNING) {
3799            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3800                    + " flags=0x" + Integer.toHexString(flags));
3801        }
3802
3803        int i;
3804        for (i=0; i<files.length; i++) {
3805            File file = new File(dir, files[i]);
3806            if (!isPackageFilename(files[i])) {
3807                // Ignore entries which are not apk's
3808                continue;
3809            }
3810            PackageParser.Package pkg = scanPackageLI(file,
3811                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
3812            // Don't mess around with apps in system partition.
3813            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3814                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3815                // Delete the apk
3816                Slog.w(TAG, "Cleaning up failed install of " + file);
3817                file.delete();
3818            }
3819        }
3820    }
3821
3822    private static File getSettingsProblemFile() {
3823        File dataDir = Environment.getDataDirectory();
3824        File systemDir = new File(dataDir, "system");
3825        File fname = new File(systemDir, "uiderrors.txt");
3826        return fname;
3827    }
3828
3829    static void reportSettingsProblem(int priority, String msg) {
3830        try {
3831            File fname = getSettingsProblemFile();
3832            FileOutputStream out = new FileOutputStream(fname, true);
3833            PrintWriter pw = new FastPrintWriter(out);
3834            SimpleDateFormat formatter = new SimpleDateFormat();
3835            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3836            pw.println(dateString + ": " + msg);
3837            pw.close();
3838            FileUtils.setPermissions(
3839                    fname.toString(),
3840                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3841                    -1, -1);
3842        } catch (java.io.IOException e) {
3843        }
3844        Slog.println(priority, TAG, msg);
3845    }
3846
3847    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3848            PackageParser.Package pkg, File srcFile, int parseFlags) {
3849        if (GET_CERTIFICATES) {
3850            if (ps != null
3851                    && ps.codePath.equals(srcFile)
3852                    && ps.timeStamp == srcFile.lastModified()) {
3853                if (ps.signatures.mSignatures != null
3854                        && ps.signatures.mSignatures.length != 0) {
3855                    // Optimization: reuse the existing cached certificates
3856                    // if the package appears to be unchanged.
3857                    pkg.mSignatures = ps.signatures.mSignatures;
3858                    return true;
3859                }
3860
3861                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3862            } else {
3863                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3864            }
3865
3866            if (!pp.collectCertificates(pkg, parseFlags)) {
3867                mLastScanError = pp.getParseError();
3868                return false;
3869            }
3870        }
3871        return true;
3872    }
3873
3874    /*
3875     *  Scan a package and return the newly parsed package.
3876     *  Returns null in case of errors and the error code is stored in mLastScanError
3877     */
3878    private PackageParser.Package scanPackageLI(File scanFile,
3879            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
3880        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3881        String scanPath = scanFile.getPath();
3882        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3883        parseFlags |= mDefParseFlags;
3884        PackageParser pp = new PackageParser(scanPath);
3885        pp.setSeparateProcesses(mSeparateProcesses);
3886        pp.setOnlyCoreApps(mOnlyCore);
3887        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3888                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3889
3890        if (pkg == null) {
3891            mLastScanError = pp.getParseError();
3892            return null;
3893        }
3894
3895        PackageSetting ps = null;
3896        PackageSetting updatedPkg;
3897        // reader
3898        synchronized (mPackages) {
3899            // Look to see if we already know about this package.
3900            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3901            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3902                // This package has been renamed to its original name.  Let's
3903                // use that.
3904                ps = mSettings.peekPackageLPr(oldName);
3905            }
3906            // If there was no original package, see one for the real package name.
3907            if (ps == null) {
3908                ps = mSettings.peekPackageLPr(pkg.packageName);
3909            }
3910            // Check to see if this package could be hiding/updating a system
3911            // package.  Must look for it either under the original or real
3912            // package name depending on our state.
3913            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3914            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3915        }
3916        boolean updatedPkgBetter = false;
3917        // First check if this is a system package that may involve an update
3918        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3919            if (ps != null && !ps.codePath.equals(scanFile)) {
3920                // The path has changed from what was last scanned...  check the
3921                // version of the new path against what we have stored to determine
3922                // what to do.
3923                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3924                if (pkg.mVersionCode < ps.versionCode) {
3925                    // The system package has been updated and the code path does not match
3926                    // Ignore entry. Skip it.
3927                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3928                            + " ignored: updated version " + ps.versionCode
3929                            + " better than this " + pkg.mVersionCode);
3930                    if (!updatedPkg.codePath.equals(scanFile)) {
3931                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3932                                + ps.name + " changing from " + updatedPkg.codePathString
3933                                + " to " + scanFile);
3934                        updatedPkg.codePath = scanFile;
3935                        updatedPkg.codePathString = scanFile.toString();
3936                        // This is the point at which we know that the system-disk APK
3937                        // for this package has moved during a reboot (e.g. due to an OTA),
3938                        // so we need to reevaluate it for privilege policy.
3939                        if (locationIsPrivileged(scanFile)) {
3940                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3941                        }
3942                    }
3943                    updatedPkg.pkg = pkg;
3944                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3945                    return null;
3946                } else {
3947                    // The current app on the system partition is better than
3948                    // what we have updated to on the data partition; switch
3949                    // back to the system partition version.
3950                    // At this point, its safely assumed that package installation for
3951                    // apps in system partition will go through. If not there won't be a working
3952                    // version of the app
3953                    // writer
3954                    synchronized (mPackages) {
3955                        // Just remove the loaded entries from package lists.
3956                        mPackages.remove(ps.name);
3957                    }
3958                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3959                            + "reverting from " + ps.codePathString
3960                            + ": new version " + pkg.mVersionCode
3961                            + " better than installed " + ps.versionCode);
3962
3963                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3964                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
3965                            getAppInstructionSetFromSettings(ps));
3966                    synchronized (mInstallLock) {
3967                        args.cleanUpResourcesLI();
3968                    }
3969                    synchronized (mPackages) {
3970                        mSettings.enableSystemPackageLPw(ps.name);
3971                    }
3972                    updatedPkgBetter = true;
3973                }
3974            }
3975        }
3976
3977        if (updatedPkg != null) {
3978            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3979            // initially
3980            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3981
3982            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
3983            // flag set initially
3984            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3985                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
3986            }
3987        }
3988        // Verify certificates against what was last scanned
3989        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3990            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3991            return null;
3992        }
3993
3994        /*
3995         * A new system app appeared, but we already had a non-system one of the
3996         * same name installed earlier.
3997         */
3998        boolean shouldHideSystemApp = false;
3999        if (updatedPkg == null && ps != null
4000                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4001            /*
4002             * Check to make sure the signatures match first. If they don't,
4003             * wipe the installed application and its data.
4004             */
4005            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4006                    != PackageManager.SIGNATURE_MATCH) {
4007                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4008                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4009                ps = null;
4010            } else {
4011                /*
4012                 * If the newly-added system app is an older version than the
4013                 * already installed version, hide it. It will be scanned later
4014                 * and re-added like an update.
4015                 */
4016                if (pkg.mVersionCode < ps.versionCode) {
4017                    shouldHideSystemApp = true;
4018                } else {
4019                    /*
4020                     * The newly found system app is a newer version that the
4021                     * one previously installed. Simply remove the
4022                     * already-installed application and replace it with our own
4023                     * while keeping the application data.
4024                     */
4025                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4026                            + ps.codePathString + ": new version " + pkg.mVersionCode
4027                            + " better than installed " + ps.versionCode);
4028                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4029                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4030                            getAppInstructionSetFromSettings(ps));
4031                    synchronized (mInstallLock) {
4032                        args.cleanUpResourcesLI();
4033                    }
4034                }
4035            }
4036        }
4037
4038        // The apk is forward locked (not public) if its code and resources
4039        // are kept in different files. (except for app in either system or
4040        // vendor path).
4041        // TODO grab this value from PackageSettings
4042        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4043            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4044                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4045            }
4046        }
4047
4048        String codePath = null;
4049        String resPath = null;
4050        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4051            if (ps != null && ps.resourcePathString != null) {
4052                resPath = ps.resourcePathString;
4053            } else {
4054                // Should not happen at all. Just log an error.
4055                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4056            }
4057        } else {
4058            resPath = pkg.mScanPath;
4059        }
4060
4061        codePath = pkg.mScanPath;
4062        // Set application objects path explicitly.
4063        setApplicationInfoPaths(pkg, codePath, resPath);
4064        // Note that we invoke the following method only if we are about to unpack an application
4065        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4066                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4067
4068        /*
4069         * If the system app should be overridden by a previously installed
4070         * data, hide the system app now and let the /data/app scan pick it up
4071         * again.
4072         */
4073        if (shouldHideSystemApp) {
4074            synchronized (mPackages) {
4075                /*
4076                 * We have to grant systems permissions before we hide, because
4077                 * grantPermissions will assume the package update is trying to
4078                 * expand its permissions.
4079                 */
4080                grantPermissionsLPw(pkg, true);
4081                mSettings.disableSystemPackageLPw(pkg.packageName);
4082            }
4083        }
4084
4085        return scannedPkg;
4086    }
4087
4088    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4089            String destResPath) {
4090        pkg.mPath = pkg.mScanPath = destCodePath;
4091        pkg.applicationInfo.sourceDir = destCodePath;
4092        pkg.applicationInfo.publicSourceDir = destResPath;
4093    }
4094
4095    private static String fixProcessName(String defProcessName,
4096            String processName, int uid) {
4097        if (processName == null) {
4098            return defProcessName;
4099        }
4100        return processName;
4101    }
4102
4103    private boolean verifySignaturesLP(PackageSetting pkgSetting,
4104            PackageParser.Package pkg) {
4105        if (pkgSetting.signatures.mSignatures != null) {
4106            // Already existing package. Make sure signatures match
4107            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
4108                PackageManager.SIGNATURE_MATCH) {
4109                    Slog.e(TAG, "Package " + pkg.packageName
4110                            + " signatures do not match the previously installed version; ignoring!");
4111                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4112                    return false;
4113                }
4114        }
4115        // Check for shared user signatures
4116        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4117            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4118                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4119                Slog.e(TAG, "Package " + pkg.packageName
4120                        + " has no signatures that match those in shared user "
4121                        + pkgSetting.sharedUser.name + "; ignoring!");
4122                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4123                return false;
4124            }
4125        }
4126        return true;
4127    }
4128
4129    /**
4130     * Enforces that only the system UID or root's UID can call a method exposed
4131     * via Binder.
4132     *
4133     * @param message used as message if SecurityException is thrown
4134     * @throws SecurityException if the caller is not system or root
4135     */
4136    private static final void enforceSystemOrRoot(String message) {
4137        final int uid = Binder.getCallingUid();
4138        if (uid != Process.SYSTEM_UID && uid != 0) {
4139            throw new SecurityException(message);
4140        }
4141    }
4142
4143    @Override
4144    public void performBootDexOpt() {
4145        enforceSystemOrRoot("Only the system can request dexopt be performed");
4146
4147        final HashSet<PackageParser.Package> pkgs;
4148        synchronized (mPackages) {
4149            pkgs = mDeferredDexOpt;
4150            mDeferredDexOpt = null;
4151        }
4152
4153        if (pkgs != null) {
4154            // Filter out packages that aren't recently used.
4155            //
4156            // The exception is first boot of a non-eng device, which
4157            // should do a full dexopt.
4158            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4159            if (eng || !isFirstBoot()) {
4160                // TODO: add a property to control this?
4161                long dexOptLRUThresholdInMinutes;
4162                if (eng) {
4163                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4164                } else {
4165                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4166                }
4167                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4168
4169                int total = pkgs.size();
4170                int skipped = 0;
4171                long now = System.currentTimeMillis();
4172                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4173                    PackageParser.Package pkg = i.next();
4174                    long then = pkg.mLastPackageUsageTimeInMills;
4175                    if (then + dexOptLRUThresholdInMills < now) {
4176                        if (DEBUG_DEXOPT) {
4177                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4178                                  ((then == 0) ? "never" : new Date(then)));
4179                        }
4180                        i.remove();
4181                        skipped++;
4182                    }
4183                }
4184                if (DEBUG_DEXOPT) {
4185                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4186                }
4187            }
4188
4189            int i = 0;
4190            for (PackageParser.Package pkg : pkgs) {
4191                i++;
4192                if (DEBUG_DEXOPT) {
4193                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4194                          + ": " + pkg.packageName);
4195                }
4196                if (!isFirstBoot()) {
4197                    try {
4198                        ActivityManagerNative.getDefault().showBootMessage(
4199                                mContext.getResources().getString(
4200                                        R.string.android_upgrading_apk,
4201                                        i, pkgs.size()), true);
4202                    } catch (RemoteException e) {
4203                    }
4204                }
4205                PackageParser.Package p = pkg;
4206                synchronized (mInstallLock) {
4207                    if (p.mDexOptNeeded) {
4208                        performDexOptLI(p, false /* force dex */, false /* defer */,
4209                                true /* include dependencies */);
4210                    }
4211                }
4212            }
4213        }
4214    }
4215
4216    @Override
4217    public boolean performDexOpt(String packageName) {
4218        enforceSystemOrRoot("Only the system can request dexopt be performed");
4219        return performDexOpt(packageName, true);
4220    }
4221
4222    public boolean performDexOpt(String packageName, boolean updateUsage) {
4223
4224        PackageParser.Package p;
4225        synchronized (mPackages) {
4226            p = mPackages.get(packageName);
4227            if (p == null) {
4228                return false;
4229            }
4230            if (updateUsage) {
4231                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4232            }
4233            mPackageUsage.write(false);
4234            if (!p.mDexOptNeeded) {
4235                return false;
4236            }
4237        }
4238
4239        synchronized (mInstallLock) {
4240            return performDexOptLI(p, false /* force dex */, false /* defer */,
4241                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4242        }
4243    }
4244
4245    public HashSet<String> getPackagesThatNeedDexOpt() {
4246        HashSet<String> pkgs = null;
4247        synchronized (mPackages) {
4248            for (PackageParser.Package p : mPackages.values()) {
4249                if (DEBUG_DEXOPT) {
4250                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4251                }
4252                if (!p.mDexOptNeeded) {
4253                    continue;
4254                }
4255                if (pkgs == null) {
4256                    pkgs = new HashSet<String>();
4257                }
4258                pkgs.add(p.packageName);
4259            }
4260        }
4261        return pkgs;
4262    }
4263
4264    public void shutdown() {
4265        mPackageUsage.write(true);
4266    }
4267
4268    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4269             boolean forceDex, boolean defer, HashSet<String> done) {
4270        for (int i=0; i<libs.size(); i++) {
4271            PackageParser.Package libPkg;
4272            String libName;
4273            synchronized (mPackages) {
4274                libName = libs.get(i);
4275                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4276                if (lib != null && lib.apk != null) {
4277                    libPkg = mPackages.get(lib.apk);
4278                } else {
4279                    libPkg = null;
4280                }
4281            }
4282            if (libPkg != null && !done.contains(libName)) {
4283                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4284            }
4285        }
4286    }
4287
4288    static final int DEX_OPT_SKIPPED = 0;
4289    static final int DEX_OPT_PERFORMED = 1;
4290    static final int DEX_OPT_DEFERRED = 2;
4291    static final int DEX_OPT_FAILED = -1;
4292
4293    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4294            boolean forceDex, boolean defer, HashSet<String> done) {
4295        final String instructionSet = instructionSetOverride != null ?
4296                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4297
4298        if (done != null) {
4299            done.add(pkg.packageName);
4300            if (pkg.usesLibraries != null) {
4301                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4302            }
4303            if (pkg.usesOptionalLibraries != null) {
4304                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4305            }
4306        }
4307
4308        boolean performed = false;
4309        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4310            String path = pkg.mScanPath;
4311            try {
4312                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4313                                                                                pkg.packageName,
4314                                                                                instructionSet,
4315                                                                                defer);
4316                // There are three basic cases here:
4317                // 1.) we need to dexopt, either because we are forced or it is needed
4318                // 2.) we are defering a needed dexopt
4319                // 3.) we are skipping an unneeded dexopt
4320                if (forceDex || (!defer && isDexOptNeededInternal)) {
4321                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4322                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4323                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4324                                                pkg.packageName, instructionSet);
4325                    // Note that we ran dexopt, since rerunning will
4326                    // probably just result in an error again.
4327                    pkg.mDexOptNeeded = false;
4328                    if (ret < 0) {
4329                        return DEX_OPT_FAILED;
4330                    }
4331                    return DEX_OPT_PERFORMED;
4332                }
4333                if (defer && isDexOptNeededInternal) {
4334                    if (mDeferredDexOpt == null) {
4335                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4336                    }
4337                    mDeferredDexOpt.add(pkg);
4338                    return DEX_OPT_DEFERRED;
4339                }
4340                pkg.mDexOptNeeded = false;
4341                return DEX_OPT_SKIPPED;
4342            } catch (FileNotFoundException e) {
4343                Slog.w(TAG, "Apk not found for dexopt: " + path);
4344                return DEX_OPT_FAILED;
4345            } catch (IOException e) {
4346                Slog.w(TAG, "IOException reading apk: " + path, e);
4347                return DEX_OPT_FAILED;
4348            } catch (StaleDexCacheError e) {
4349                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4350                return DEX_OPT_FAILED;
4351            } catch (Exception e) {
4352                Slog.w(TAG, "Exception when doing dexopt : ", e);
4353                return DEX_OPT_FAILED;
4354            }
4355        }
4356        return DEX_OPT_SKIPPED;
4357    }
4358
4359    private String getAppInstructionSet(ApplicationInfo info) {
4360        String instructionSet = getPreferredInstructionSet();
4361
4362        if (info.cpuAbi != null) {
4363            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4364        }
4365
4366        return instructionSet;
4367    }
4368
4369    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4370        String instructionSet = getPreferredInstructionSet();
4371
4372        if (ps.cpuAbiString != null) {
4373            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4374        }
4375
4376        return instructionSet;
4377    }
4378
4379    private static String getPreferredInstructionSet() {
4380        if (sPreferredInstructionSet == null) {
4381            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4382        }
4383
4384        return sPreferredInstructionSet;
4385    }
4386
4387    private static List<String> getAllInstructionSets() {
4388        final String[] allAbis = Build.SUPPORTED_ABIS;
4389        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4390
4391        for (String abi : allAbis) {
4392            final String instructionSet = VMRuntime.getInstructionSet(abi);
4393            if (!allInstructionSets.contains(instructionSet)) {
4394                allInstructionSets.add(instructionSet);
4395            }
4396        }
4397
4398        return allInstructionSets;
4399    }
4400
4401    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4402            boolean inclDependencies) {
4403        HashSet<String> done;
4404        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4405            done = new HashSet<String>();
4406            done.add(pkg.packageName);
4407        } else {
4408            done = null;
4409        }
4410        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4411    }
4412
4413    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4414        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4415            Slog.w(TAG, "Unable to update from " + oldPkg.name
4416                    + " to " + newPkg.packageName
4417                    + ": old package not in system partition");
4418            return false;
4419        } else if (mPackages.get(oldPkg.name) != null) {
4420            Slog.w(TAG, "Unable to update from " + oldPkg.name
4421                    + " to " + newPkg.packageName
4422                    + ": old package still exists");
4423            return false;
4424        }
4425        return true;
4426    }
4427
4428    File getDataPathForUser(int userId) {
4429        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4430    }
4431
4432    private File getDataPathForPackage(String packageName, int userId) {
4433        /*
4434         * Until we fully support multiple users, return the directory we
4435         * previously would have. The PackageManagerTests will need to be
4436         * revised when this is changed back..
4437         */
4438        if (userId == 0) {
4439            return new File(mAppDataDir, packageName);
4440        } else {
4441            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4442                + File.separator + packageName);
4443        }
4444    }
4445
4446    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4447        int[] users = sUserManager.getUserIds();
4448        int res = mInstaller.install(packageName, uid, uid, seinfo);
4449        if (res < 0) {
4450            return res;
4451        }
4452        for (int user : users) {
4453            if (user != 0) {
4454                res = mInstaller.createUserData(packageName,
4455                        UserHandle.getUid(user, uid), user, seinfo);
4456                if (res < 0) {
4457                    return res;
4458                }
4459            }
4460        }
4461        return res;
4462    }
4463
4464    private int removeDataDirsLI(String packageName) {
4465        int[] users = sUserManager.getUserIds();
4466        int res = 0;
4467        for (int user : users) {
4468            int resInner = mInstaller.remove(packageName, user);
4469            if (resInner < 0) {
4470                res = resInner;
4471            }
4472        }
4473
4474        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4475        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4476        if (!nativeLibraryFile.delete()) {
4477            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4478        }
4479
4480        return res;
4481    }
4482
4483    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4484            PackageParser.Package changingLib) {
4485        if (file.path != null) {
4486            mTmpSharedLibraries[num] = file.path;
4487            return num+1;
4488        }
4489        PackageParser.Package p = mPackages.get(file.apk);
4490        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4491            // If we are doing this while in the middle of updating a library apk,
4492            // then we need to make sure to use that new apk for determining the
4493            // dependencies here.  (We haven't yet finished committing the new apk
4494            // to the package manager state.)
4495            if (p == null || p.packageName.equals(changingLib.packageName)) {
4496                p = changingLib;
4497            }
4498        }
4499        if (p != null) {
4500            String path = p.mPath;
4501            for (int i=0; i<num; i++) {
4502                if (mTmpSharedLibraries[i].equals(path)) {
4503                    return num;
4504                }
4505            }
4506            mTmpSharedLibraries[num] = p.mPath;
4507            return num+1;
4508        }
4509        return num;
4510    }
4511
4512    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4513            PackageParser.Package changingLib) {
4514        // We might be upgrading from a version of the platform that did not
4515        // provide per-package native library directories for system apps.
4516        // Fix that up here.
4517        if (isSystemApp(pkg)) {
4518            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4519            setInternalAppNativeLibraryPath(pkg, ps);
4520        }
4521
4522        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4523            if (mTmpSharedLibraries == null ||
4524                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4525                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4526            }
4527            int num = 0;
4528            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4529            for (int i=0; i<N; i++) {
4530                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4531                if (file == null) {
4532                    Slog.e(TAG, "Package " + pkg.packageName
4533                            + " requires unavailable shared library "
4534                            + pkg.usesLibraries.get(i) + "; failing!");
4535                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4536                    return false;
4537                }
4538                num = addSharedLibraryLPw(file, num, changingLib);
4539            }
4540            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4541            for (int i=0; i<N; i++) {
4542                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4543                if (file == null) {
4544                    Slog.w(TAG, "Package " + pkg.packageName
4545                            + " desires unavailable shared library "
4546                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4547                } else {
4548                    num = addSharedLibraryLPw(file, num, changingLib);
4549                }
4550            }
4551            if (num > 0) {
4552                pkg.usesLibraryFiles = new String[num];
4553                System.arraycopy(mTmpSharedLibraries, 0,
4554                        pkg.usesLibraryFiles, 0, num);
4555            } else {
4556                pkg.usesLibraryFiles = null;
4557            }
4558        }
4559        return true;
4560    }
4561
4562    private static boolean hasString(List<String> list, List<String> which) {
4563        if (list == null) {
4564            return false;
4565        }
4566        for (int i=list.size()-1; i>=0; i--) {
4567            for (int j=which.size()-1; j>=0; j--) {
4568                if (which.get(j).equals(list.get(i))) {
4569                    return true;
4570                }
4571            }
4572        }
4573        return false;
4574    }
4575
4576    private void updateAllSharedLibrariesLPw() {
4577        for (PackageParser.Package pkg : mPackages.values()) {
4578            updateSharedLibrariesLPw(pkg, null);
4579        }
4580    }
4581
4582    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4583            PackageParser.Package changingPkg) {
4584        ArrayList<PackageParser.Package> res = null;
4585        for (PackageParser.Package pkg : mPackages.values()) {
4586            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4587                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4588                if (res == null) {
4589                    res = new ArrayList<PackageParser.Package>();
4590                }
4591                res.add(pkg);
4592                updateSharedLibrariesLPw(pkg, changingPkg);
4593            }
4594        }
4595        return res;
4596    }
4597
4598    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4599            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4600        File scanFile = new File(pkg.mScanPath);
4601        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4602                pkg.applicationInfo.publicSourceDir == null) {
4603            // Bail out. The resource and code paths haven't been set.
4604            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4605            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4606            return null;
4607        }
4608
4609        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4610            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4611        }
4612
4613        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4614            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4615        }
4616
4617        if (mCustomResolverComponentName != null &&
4618                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4619            setUpCustomResolverActivity(pkg);
4620        }
4621
4622        if (pkg.packageName.equals("android")) {
4623            synchronized (mPackages) {
4624                if (mAndroidApplication != null) {
4625                    Slog.w(TAG, "*************************************************");
4626                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4627                    Slog.w(TAG, " file=" + scanFile);
4628                    Slog.w(TAG, "*************************************************");
4629                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4630                    return null;
4631                }
4632
4633                // Set up information for our fall-back user intent resolution activity.
4634                mPlatformPackage = pkg;
4635                pkg.mVersionCode = mSdkVersion;
4636                mAndroidApplication = pkg.applicationInfo;
4637
4638                if (!mResolverReplaced) {
4639                    mResolveActivity.applicationInfo = mAndroidApplication;
4640                    mResolveActivity.name = ResolverActivity.class.getName();
4641                    mResolveActivity.packageName = mAndroidApplication.packageName;
4642                    mResolveActivity.processName = "system:ui";
4643                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4644                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4645                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4646                    mResolveActivity.exported = true;
4647                    mResolveActivity.enabled = true;
4648                    mResolveInfo.activityInfo = mResolveActivity;
4649                    mResolveInfo.priority = 0;
4650                    mResolveInfo.preferredOrder = 0;
4651                    mResolveInfo.match = 0;
4652                    mResolveComponentName = new ComponentName(
4653                            mAndroidApplication.packageName, mResolveActivity.name);
4654                }
4655            }
4656        }
4657
4658        if (DEBUG_PACKAGE_SCANNING) {
4659            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4660                Log.d(TAG, "Scanning package " + pkg.packageName);
4661        }
4662
4663        if (mPackages.containsKey(pkg.packageName)
4664                || mSharedLibraries.containsKey(pkg.packageName)) {
4665            Slog.w(TAG, "Application package " + pkg.packageName
4666                    + " already installed.  Skipping duplicate.");
4667            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4668            return null;
4669        }
4670
4671        // Initialize package source and resource directories
4672        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4673        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4674
4675        SharedUserSetting suid = null;
4676        PackageSetting pkgSetting = null;
4677
4678        if (!isSystemApp(pkg)) {
4679            // Only system apps can use these features.
4680            pkg.mOriginalPackages = null;
4681            pkg.mRealPackage = null;
4682            pkg.mAdoptPermissions = null;
4683        }
4684
4685        // writer
4686        synchronized (mPackages) {
4687            if (pkg.mSharedUserId != null) {
4688                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4689                if (suid == null) {
4690                    Slog.w(TAG, "Creating application package " + pkg.packageName
4691                            + " for shared user failed");
4692                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4693                    return null;
4694                }
4695                if (DEBUG_PACKAGE_SCANNING) {
4696                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4697                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4698                                + "): packages=" + suid.packages);
4699                }
4700            }
4701
4702            // Check if we are renaming from an original package name.
4703            PackageSetting origPackage = null;
4704            String realName = null;
4705            if (pkg.mOriginalPackages != null) {
4706                // This package may need to be renamed to a previously
4707                // installed name.  Let's check on that...
4708                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4709                if (pkg.mOriginalPackages.contains(renamed)) {
4710                    // This package had originally been installed as the
4711                    // original name, and we have already taken care of
4712                    // transitioning to the new one.  Just update the new
4713                    // one to continue using the old name.
4714                    realName = pkg.mRealPackage;
4715                    if (!pkg.packageName.equals(renamed)) {
4716                        // Callers into this function may have already taken
4717                        // care of renaming the package; only do it here if
4718                        // it is not already done.
4719                        pkg.setPackageName(renamed);
4720                    }
4721
4722                } else {
4723                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4724                        if ((origPackage = mSettings.peekPackageLPr(
4725                                pkg.mOriginalPackages.get(i))) != null) {
4726                            // We do have the package already installed under its
4727                            // original name...  should we use it?
4728                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4729                                // New package is not compatible with original.
4730                                origPackage = null;
4731                                continue;
4732                            } else if (origPackage.sharedUser != null) {
4733                                // Make sure uid is compatible between packages.
4734                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4735                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4736                                            + " to " + pkg.packageName + ": old uid "
4737                                            + origPackage.sharedUser.name
4738                                            + " differs from " + pkg.mSharedUserId);
4739                                    origPackage = null;
4740                                    continue;
4741                                }
4742                            } else {
4743                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4744                                        + pkg.packageName + " to old name " + origPackage.name);
4745                            }
4746                            break;
4747                        }
4748                    }
4749                }
4750            }
4751
4752            if (mTransferedPackages.contains(pkg.packageName)) {
4753                Slog.w(TAG, "Package " + pkg.packageName
4754                        + " was transferred to another, but its .apk remains");
4755            }
4756
4757            // Just create the setting, don't add it yet. For already existing packages
4758            // the PkgSetting exists already and doesn't have to be created.
4759            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4760                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4761                    pkg.applicationInfo.cpuAbi,
4762                    pkg.applicationInfo.flags, user, false);
4763            if (pkgSetting == null) {
4764                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4765                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4766                return null;
4767            }
4768
4769            if (pkgSetting.origPackage != null) {
4770                // If we are first transitioning from an original package,
4771                // fix up the new package's name now.  We need to do this after
4772                // looking up the package under its new name, so getPackageLP
4773                // can take care of fiddling things correctly.
4774                pkg.setPackageName(origPackage.name);
4775
4776                // File a report about this.
4777                String msg = "New package " + pkgSetting.realName
4778                        + " renamed to replace old package " + pkgSetting.name;
4779                reportSettingsProblem(Log.WARN, msg);
4780
4781                // Make a note of it.
4782                mTransferedPackages.add(origPackage.name);
4783
4784                // No longer need to retain this.
4785                pkgSetting.origPackage = null;
4786            }
4787
4788            if (realName != null) {
4789                // Make a note of it.
4790                mTransferedPackages.add(pkg.packageName);
4791            }
4792
4793            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4794                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4795            }
4796
4797            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4798                // Check all shared libraries and map to their actual file path.
4799                // We only do this here for apps not on a system dir, because those
4800                // are the only ones that can fail an install due to this.  We
4801                // will take care of the system apps by updating all of their
4802                // library paths after the scan is done.
4803                if (!updateSharedLibrariesLPw(pkg, null)) {
4804                    return null;
4805                }
4806            }
4807
4808            if (mFoundPolicyFile) {
4809                SELinuxMMAC.assignSeinfoValue(pkg);
4810            }
4811
4812            pkg.applicationInfo.uid = pkgSetting.appId;
4813            pkg.mExtras = pkgSetting;
4814
4815            if (!verifySignaturesLP(pkgSetting, pkg)) {
4816                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4817                    return null;
4818                }
4819                // The signature has changed, but this package is in the system
4820                // image...  let's recover!
4821                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4822                // However...  if this package is part of a shared user, but it
4823                // doesn't match the signature of the shared user, let's fail.
4824                // What this means is that you can't change the signatures
4825                // associated with an overall shared user, which doesn't seem all
4826                // that unreasonable.
4827                if (pkgSetting.sharedUser != null) {
4828                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4829                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4830                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4831                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4832                        return null;
4833                    }
4834                }
4835                // File a report about this.
4836                String msg = "System package " + pkg.packageName
4837                        + " signature changed; retaining data.";
4838                reportSettingsProblem(Log.WARN, msg);
4839            }
4840
4841            // Verify that this new package doesn't have any content providers
4842            // that conflict with existing packages.  Only do this if the
4843            // package isn't already installed, since we don't want to break
4844            // things that are installed.
4845            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4846                final int N = pkg.providers.size();
4847                int i;
4848                for (i=0; i<N; i++) {
4849                    PackageParser.Provider p = pkg.providers.get(i);
4850                    if (p.info.authority != null) {
4851                        String names[] = p.info.authority.split(";");
4852                        for (int j = 0; j < names.length; j++) {
4853                            if (mProvidersByAuthority.containsKey(names[j])) {
4854                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4855                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4856                                        " (in package " + pkg.applicationInfo.packageName +
4857                                        ") is already used by "
4858                                        + ((other != null && other.getComponentName() != null)
4859                                                ? other.getComponentName().getPackageName() : "?"));
4860                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4861                                return null;
4862                            }
4863                        }
4864                    }
4865                }
4866            }
4867
4868            if (pkg.mAdoptPermissions != null) {
4869                // This package wants to adopt ownership of permissions from
4870                // another package.
4871                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4872                    final String origName = pkg.mAdoptPermissions.get(i);
4873                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4874                    if (orig != null) {
4875                        if (verifyPackageUpdateLPr(orig, pkg)) {
4876                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4877                                    + pkg.packageName);
4878                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4879                        }
4880                    }
4881                }
4882            }
4883        }
4884
4885        final String pkgName = pkg.packageName;
4886
4887        final long scanFileTime = scanFile.lastModified();
4888        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4889        pkg.applicationInfo.processName = fixProcessName(
4890                pkg.applicationInfo.packageName,
4891                pkg.applicationInfo.processName,
4892                pkg.applicationInfo.uid);
4893
4894        File dataPath;
4895        if (mPlatformPackage == pkg) {
4896            // The system package is special.
4897            dataPath = new File (Environment.getDataDirectory(), "system");
4898            pkg.applicationInfo.dataDir = dataPath.getPath();
4899        } else {
4900            // This is a normal package, need to make its data directory.
4901            dataPath = getDataPathForPackage(pkg.packageName, 0);
4902
4903            boolean uidError = false;
4904
4905            if (dataPath.exists()) {
4906                int currentUid = 0;
4907                try {
4908                    StructStat stat = Os.stat(dataPath.getPath());
4909                    currentUid = stat.st_uid;
4910                } catch (ErrnoException e) {
4911                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4912                }
4913
4914                // If we have mismatched owners for the data path, we have a problem.
4915                if (currentUid != pkg.applicationInfo.uid) {
4916                    boolean recovered = false;
4917                    if (currentUid == 0) {
4918                        // The directory somehow became owned by root.  Wow.
4919                        // This is probably because the system was stopped while
4920                        // installd was in the middle of messing with its libs
4921                        // directory.  Ask installd to fix that.
4922                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4923                                pkg.applicationInfo.uid);
4924                        if (ret >= 0) {
4925                            recovered = true;
4926                            String msg = "Package " + pkg.packageName
4927                                    + " unexpectedly changed to uid 0; recovered to " +
4928                                    + pkg.applicationInfo.uid;
4929                            reportSettingsProblem(Log.WARN, msg);
4930                        }
4931                    }
4932                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4933                            || (scanMode&SCAN_BOOTING) != 0)) {
4934                        // If this is a system app, we can at least delete its
4935                        // current data so the application will still work.
4936                        int ret = removeDataDirsLI(pkgName);
4937                        if (ret >= 0) {
4938                            // TODO: Kill the processes first
4939                            // Old data gone!
4940                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4941                                    ? "System package " : "Third party package ";
4942                            String msg = prefix + pkg.packageName
4943                                    + " has changed from uid: "
4944                                    + currentUid + " to "
4945                                    + pkg.applicationInfo.uid + "; old data erased";
4946                            reportSettingsProblem(Log.WARN, msg);
4947                            recovered = true;
4948
4949                            // And now re-install the app.
4950                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4951                                                   pkg.applicationInfo.seinfo);
4952                            if (ret == -1) {
4953                                // Ack should not happen!
4954                                msg = prefix + pkg.packageName
4955                                        + " could not have data directory re-created after delete.";
4956                                reportSettingsProblem(Log.WARN, msg);
4957                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4958                                return null;
4959                            }
4960                        }
4961                        if (!recovered) {
4962                            mHasSystemUidErrors = true;
4963                        }
4964                    } else if (!recovered) {
4965                        // If we allow this install to proceed, we will be broken.
4966                        // Abort, abort!
4967                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4968                        return null;
4969                    }
4970                    if (!recovered) {
4971                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4972                            + pkg.applicationInfo.uid + "/fs_"
4973                            + currentUid;
4974                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4975                        String msg = "Package " + pkg.packageName
4976                                + " has mismatched uid: "
4977                                + currentUid + " on disk, "
4978                                + pkg.applicationInfo.uid + " in settings";
4979                        // writer
4980                        synchronized (mPackages) {
4981                            mSettings.mReadMessages.append(msg);
4982                            mSettings.mReadMessages.append('\n');
4983                            uidError = true;
4984                            if (!pkgSetting.uidError) {
4985                                reportSettingsProblem(Log.ERROR, msg);
4986                            }
4987                        }
4988                    }
4989                }
4990                pkg.applicationInfo.dataDir = dataPath.getPath();
4991                if (mShouldRestoreconData) {
4992                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
4993                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
4994                                pkg.applicationInfo.uid);
4995                }
4996            } else {
4997                if (DEBUG_PACKAGE_SCANNING) {
4998                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4999                        Log.v(TAG, "Want this data dir: " + dataPath);
5000                }
5001                //invoke installer to do the actual installation
5002                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5003                                           pkg.applicationInfo.seinfo);
5004                if (ret < 0) {
5005                    // Error from installer
5006                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5007                    return null;
5008                }
5009
5010                if (dataPath.exists()) {
5011                    pkg.applicationInfo.dataDir = dataPath.getPath();
5012                } else {
5013                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5014                    pkg.applicationInfo.dataDir = null;
5015                }
5016            }
5017
5018            /*
5019             * Set the data dir to the default "/data/data/<package name>/lib"
5020             * if we got here without anyone telling us different (e.g., apps
5021             * stored on SD card have their native libraries stored in the ASEC
5022             * container with the APK).
5023             *
5024             * This happens during an upgrade from a package settings file that
5025             * doesn't have a native library path attribute at all.
5026             */
5027            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5028                if (pkgSetting.nativeLibraryPathString == null) {
5029                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5030                } else {
5031                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5032                }
5033            }
5034            pkgSetting.uidError = uidError;
5035        }
5036
5037        String path = scanFile.getPath();
5038        /* Note: We don't want to unpack the native binaries for
5039         *        system applications, unless they have been updated
5040         *        (the binaries are already under /system/lib).
5041         *        Also, don't unpack libs for apps on the external card
5042         *        since they should have their libraries in the ASEC
5043         *        container already.
5044         *
5045         *        In other words, we're going to unpack the binaries
5046         *        only for non-system apps and system app upgrades.
5047         */
5048        if (pkg.applicationInfo.nativeLibraryDir != null) {
5049            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5050            try {
5051                // Enable gross and lame hacks for apps that are built with old
5052                // SDK tools. We must scan their APKs for renderscript bitcode and
5053                // not launch them if it's present. Don't bother checking on devices
5054                // that don't have 64 bit support.
5055                String[] abiList = Build.SUPPORTED_ABIS;
5056                boolean hasLegacyRenderscriptBitcode = false;
5057                if (abiOverride != null) {
5058                    abiList = new String[] { abiOverride };
5059                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5060                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5061                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5062                    hasLegacyRenderscriptBitcode = true;
5063                }
5064
5065                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5066                final String dataPathString = dataPath.getCanonicalPath();
5067
5068                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5069                    /*
5070                     * Upgrading from a previous version of the OS sometimes
5071                     * leaves native libraries in the /data/data/<app>/lib
5072                     * directory for system apps even when they shouldn't be.
5073                     * Recent changes in the JNI library search path
5074                     * necessitates we remove those to match previous behavior.
5075                     */
5076                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5077                        Log.i(TAG, "removed obsolete native libraries for system package "
5078                                + path);
5079                    }
5080                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5081                        pkg.applicationInfo.cpuAbi = abiList[0];
5082                        pkgSetting.cpuAbiString = abiList[0];
5083                    } else {
5084                        setInternalAppAbi(pkg, pkgSetting);
5085                    }
5086                } else {
5087                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5088                        /*
5089                        * Update native library dir if it starts with
5090                        * /data/data
5091                        */
5092                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5093                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5094                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5095                        }
5096
5097                        try {
5098                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5099                                    nativeLibraryDir, abiList);
5100                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5101                                Slog.e(TAG, "Unable to copy native libraries");
5102                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5103                                return null;
5104                            }
5105
5106                            // We've successfully copied native libraries across, so we make a
5107                            // note of what ABI we're using
5108                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5109                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5110                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5111                                pkg.applicationInfo.cpuAbi = abiList[0];
5112                            } else {
5113                                pkg.applicationInfo.cpuAbi = null;
5114                            }
5115                        } catch (IOException e) {
5116                            Slog.e(TAG, "Unable to copy native libraries", e);
5117                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5118                            return null;
5119                        }
5120                    } else {
5121                        // We don't have to copy the shared libraries if we're in the ASEC container
5122                        // but we still need to scan the file to figure out what ABI the app needs.
5123                        //
5124                        // TODO: This duplicates work done in the default container service. It's possible
5125                        // to clean this up but we'll need to change the interface between this service
5126                        // and IMediaContainerService (but doing so will spread this logic out, rather
5127                        // than centralizing it).
5128                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5129                        if (abi >= 0) {
5130                            pkg.applicationInfo.cpuAbi = abiList[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                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5136                                pkg.applicationInfo.cpuAbi = abiList[0];
5137                            } else {
5138                                pkg.applicationInfo.cpuAbi = null;
5139                            }
5140                        } else {
5141                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5142                            return null;
5143                        }
5144                    }
5145
5146                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5147                    final int[] userIds = sUserManager.getUserIds();
5148                    synchronized (mInstallLock) {
5149                        for (int userId : userIds) {
5150                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5151                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5152                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5153                                        + ")");
5154                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5155                                return null;
5156                            }
5157                        }
5158                    }
5159                }
5160
5161                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5162            } catch (IOException ioe) {
5163                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5164            } finally {
5165                handle.close();
5166            }
5167        }
5168        pkg.mScanPath = path;
5169
5170        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5171            // We don't do this here during boot because we can do it all
5172            // at once after scanning all existing packages.
5173            //
5174            // We also do this *before* we perform dexopt on this package, so that
5175            // we can avoid redundant dexopts, and also to make sure we've got the
5176            // code and package path correct.
5177            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5178                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5179                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5180                return null;
5181            }
5182        }
5183
5184        if ((scanMode&SCAN_NO_DEX) == 0) {
5185            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5186                    == DEX_OPT_FAILED) {
5187                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5188                    removeDataDirsLI(pkg.packageName);
5189                }
5190
5191                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5192                return null;
5193            }
5194        }
5195
5196        if (mFactoryTest && pkg.requestedPermissions.contains(
5197                android.Manifest.permission.FACTORY_TEST)) {
5198            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5199        }
5200
5201        ArrayList<PackageParser.Package> clientLibPkgs = null;
5202
5203        // writer
5204        synchronized (mPackages) {
5205            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5206                // Only system apps can add new shared libraries.
5207                if (pkg.libraryNames != null) {
5208                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5209                        String name = pkg.libraryNames.get(i);
5210                        boolean allowed = false;
5211                        if (isUpdatedSystemApp(pkg)) {
5212                            // New library entries can only be added through the
5213                            // system image.  This is important to get rid of a lot
5214                            // of nasty edge cases: for example if we allowed a non-
5215                            // system update of the app to add a library, then uninstalling
5216                            // the update would make the library go away, and assumptions
5217                            // we made such as through app install filtering would now
5218                            // have allowed apps on the device which aren't compatible
5219                            // with it.  Better to just have the restriction here, be
5220                            // conservative, and create many fewer cases that can negatively
5221                            // impact the user experience.
5222                            final PackageSetting sysPs = mSettings
5223                                    .getDisabledSystemPkgLPr(pkg.packageName);
5224                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5225                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5226                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5227                                        allowed = true;
5228                                        allowed = true;
5229                                        break;
5230                                    }
5231                                }
5232                            }
5233                        } else {
5234                            allowed = true;
5235                        }
5236                        if (allowed) {
5237                            if (!mSharedLibraries.containsKey(name)) {
5238                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5239                            } else if (!name.equals(pkg.packageName)) {
5240                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5241                                        + name + " already exists; skipping");
5242                            }
5243                        } else {
5244                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5245                                    + name + " that is not declared on system image; skipping");
5246                        }
5247                    }
5248                    if ((scanMode&SCAN_BOOTING) == 0) {
5249                        // If we are not booting, we need to update any applications
5250                        // that are clients of our shared library.  If we are booting,
5251                        // this will all be done once the scan is complete.
5252                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5253                    }
5254                }
5255            }
5256        }
5257
5258        // We also need to dexopt any apps that are dependent on this library.  Note that
5259        // if these fail, we should abort the install since installing the library will
5260        // result in some apps being broken.
5261        if (clientLibPkgs != null) {
5262            if ((scanMode&SCAN_NO_DEX) == 0) {
5263                for (int i=0; i<clientLibPkgs.size(); i++) {
5264                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5265                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5266                            == DEX_OPT_FAILED) {
5267                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5268                            removeDataDirsLI(pkg.packageName);
5269                        }
5270
5271                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5272                        return null;
5273                    }
5274                }
5275            }
5276        }
5277
5278        // Request the ActivityManager to kill the process(only for existing packages)
5279        // so that we do not end up in a confused state while the user is still using the older
5280        // version of the application while the new one gets installed.
5281        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5282            // If the package lives in an asec, tell everyone that the container is going
5283            // away so they can clean up any references to its resources (which would prevent
5284            // vold from being able to unmount the asec)
5285            if (isForwardLocked(pkg) || isExternal(pkg)) {
5286                if (DEBUG_INSTALL) {
5287                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5288                }
5289                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5290                final ArrayList<String> pkgList = new ArrayList<String>(1);
5291                pkgList.add(pkg.applicationInfo.packageName);
5292                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5293            }
5294
5295            // Post the request that it be killed now that the going-away broadcast is en route
5296            killApplication(pkg.applicationInfo.packageName,
5297                        pkg.applicationInfo.uid, "update pkg");
5298        }
5299
5300        // Also need to kill any apps that are dependent on the library.
5301        if (clientLibPkgs != null) {
5302            for (int i=0; i<clientLibPkgs.size(); i++) {
5303                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5304                killApplication(clientPkg.applicationInfo.packageName,
5305                        clientPkg.applicationInfo.uid, "update lib");
5306            }
5307        }
5308
5309        // writer
5310        synchronized (mPackages) {
5311            // We don't expect installation to fail beyond this point,
5312            if ((scanMode&SCAN_MONITOR) != 0) {
5313                mAppDirs.put(pkg.mPath, pkg);
5314            }
5315            // Add the new setting to mSettings
5316            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5317            // Add the new setting to mPackages
5318            mPackages.put(pkg.applicationInfo.packageName, pkg);
5319            // Make sure we don't accidentally delete its data.
5320            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5321            while (iter.hasNext()) {
5322                PackageCleanItem item = iter.next();
5323                if (pkgName.equals(item.packageName)) {
5324                    iter.remove();
5325                }
5326            }
5327
5328            // Take care of first install / last update times.
5329            if (currentTime != 0) {
5330                if (pkgSetting.firstInstallTime == 0) {
5331                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5332                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5333                    pkgSetting.lastUpdateTime = currentTime;
5334                }
5335            } else if (pkgSetting.firstInstallTime == 0) {
5336                // We need *something*.  Take time time stamp of the file.
5337                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5338            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5339                if (scanFileTime != pkgSetting.timeStamp) {
5340                    // A package on the system image has changed; consider this
5341                    // to be an update.
5342                    pkgSetting.lastUpdateTime = scanFileTime;
5343                }
5344            }
5345
5346            // Add the package's KeySets to the global KeySetManager
5347            KeySetManager ksm = mSettings.mKeySetManager;
5348            try {
5349                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5350                if (pkg.mKeySetMapping != null) {
5351                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5352                        if (entry.getValue() != null) {
5353                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5354                                entry.getValue(), entry.getKey());
5355                        }
5356                    }
5357                }
5358            } catch (NullPointerException e) {
5359                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5360            } catch (IllegalArgumentException e) {
5361                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5362            }
5363
5364            int N = pkg.providers.size();
5365            StringBuilder r = null;
5366            int i;
5367            for (i=0; i<N; i++) {
5368                PackageParser.Provider p = pkg.providers.get(i);
5369                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5370                        p.info.processName, pkg.applicationInfo.uid);
5371                mProviders.addProvider(p);
5372                p.syncable = p.info.isSyncable;
5373                if (p.info.authority != null) {
5374                    String names[] = p.info.authority.split(";");
5375                    p.info.authority = null;
5376                    for (int j = 0; j < names.length; j++) {
5377                        if (j == 1 && p.syncable) {
5378                            // We only want the first authority for a provider to possibly be
5379                            // syncable, so if we already added this provider using a different
5380                            // authority clear the syncable flag. We copy the provider before
5381                            // changing it because the mProviders object contains a reference
5382                            // to a provider that we don't want to change.
5383                            // Only do this for the second authority since the resulting provider
5384                            // object can be the same for all future authorities for this provider.
5385                            p = new PackageParser.Provider(p);
5386                            p.syncable = false;
5387                        }
5388                        if (!mProvidersByAuthority.containsKey(names[j])) {
5389                            mProvidersByAuthority.put(names[j], p);
5390                            if (p.info.authority == null) {
5391                                p.info.authority = names[j];
5392                            } else {
5393                                p.info.authority = p.info.authority + ";" + names[j];
5394                            }
5395                            if (DEBUG_PACKAGE_SCANNING) {
5396                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5397                                    Log.d(TAG, "Registered content provider: " + names[j]
5398                                            + ", className = " + p.info.name + ", isSyncable = "
5399                                            + p.info.isSyncable);
5400                            }
5401                        } else {
5402                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5403                            Slog.w(TAG, "Skipping provider name " + names[j] +
5404                                    " (in package " + pkg.applicationInfo.packageName +
5405                                    "): name already used by "
5406                                    + ((other != null && other.getComponentName() != null)
5407                                            ? other.getComponentName().getPackageName() : "?"));
5408                        }
5409                    }
5410                }
5411                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5412                    if (r == null) {
5413                        r = new StringBuilder(256);
5414                    } else {
5415                        r.append(' ');
5416                    }
5417                    r.append(p.info.name);
5418                }
5419            }
5420            if (r != null) {
5421                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5422            }
5423
5424            N = pkg.services.size();
5425            r = null;
5426            for (i=0; i<N; i++) {
5427                PackageParser.Service s = pkg.services.get(i);
5428                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5429                        s.info.processName, pkg.applicationInfo.uid);
5430                mServices.addService(s);
5431                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5432                    if (r == null) {
5433                        r = new StringBuilder(256);
5434                    } else {
5435                        r.append(' ');
5436                    }
5437                    r.append(s.info.name);
5438                }
5439            }
5440            if (r != null) {
5441                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5442            }
5443
5444            N = pkg.receivers.size();
5445            r = null;
5446            for (i=0; i<N; i++) {
5447                PackageParser.Activity a = pkg.receivers.get(i);
5448                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5449                        a.info.processName, pkg.applicationInfo.uid);
5450                mReceivers.addActivity(a, "receiver");
5451                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5452                    if (r == null) {
5453                        r = new StringBuilder(256);
5454                    } else {
5455                        r.append(' ');
5456                    }
5457                    r.append(a.info.name);
5458                }
5459            }
5460            if (r != null) {
5461                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5462            }
5463
5464            N = pkg.activities.size();
5465            r = null;
5466            for (i=0; i<N; i++) {
5467                PackageParser.Activity a = pkg.activities.get(i);
5468                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5469                        a.info.processName, pkg.applicationInfo.uid);
5470                mActivities.addActivity(a, "activity");
5471                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5472                    if (r == null) {
5473                        r = new StringBuilder(256);
5474                    } else {
5475                        r.append(' ');
5476                    }
5477                    r.append(a.info.name);
5478                }
5479            }
5480            if (r != null) {
5481                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5482            }
5483
5484            N = pkg.permissionGroups.size();
5485            r = null;
5486            for (i=0; i<N; i++) {
5487                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5488                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5489                if (cur == null) {
5490                    mPermissionGroups.put(pg.info.name, pg);
5491                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5492                        if (r == null) {
5493                            r = new StringBuilder(256);
5494                        } else {
5495                            r.append(' ');
5496                        }
5497                        r.append(pg.info.name);
5498                    }
5499                } else {
5500                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5501                            + pg.info.packageName + " ignored: original from "
5502                            + cur.info.packageName);
5503                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5504                        if (r == null) {
5505                            r = new StringBuilder(256);
5506                        } else {
5507                            r.append(' ');
5508                        }
5509                        r.append("DUP:");
5510                        r.append(pg.info.name);
5511                    }
5512                }
5513            }
5514            if (r != null) {
5515                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5516            }
5517
5518            N = pkg.permissions.size();
5519            r = null;
5520            for (i=0; i<N; i++) {
5521                PackageParser.Permission p = pkg.permissions.get(i);
5522                HashMap<String, BasePermission> permissionMap =
5523                        p.tree ? mSettings.mPermissionTrees
5524                        : mSettings.mPermissions;
5525                p.group = mPermissionGroups.get(p.info.group);
5526                if (p.info.group == null || p.group != null) {
5527                    BasePermission bp = permissionMap.get(p.info.name);
5528                    if (bp == null) {
5529                        bp = new BasePermission(p.info.name, p.info.packageName,
5530                                BasePermission.TYPE_NORMAL);
5531                        permissionMap.put(p.info.name, bp);
5532                    }
5533                    if (bp.perm == null) {
5534                        if (bp.sourcePackage != null
5535                                && !bp.sourcePackage.equals(p.info.packageName)) {
5536                            // If this is a permission that was formerly defined by a non-system
5537                            // app, but is now defined by a system app (following an upgrade),
5538                            // discard the previous declaration and consider the system's to be
5539                            // canonical.
5540                            if (isSystemApp(p.owner)) {
5541                                Slog.i(TAG, "New decl " + p.owner + " of permission  "
5542                                        + p.info.name + " is system");
5543                                bp.sourcePackage = null;
5544                            }
5545                        }
5546                        if (bp.sourcePackage == null
5547                                || bp.sourcePackage.equals(p.info.packageName)) {
5548                            BasePermission tree = findPermissionTreeLP(p.info.name);
5549                            if (tree == null
5550                                    || tree.sourcePackage.equals(p.info.packageName)) {
5551                                bp.packageSetting = pkgSetting;
5552                                bp.perm = p;
5553                                bp.uid = pkg.applicationInfo.uid;
5554                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5555                                    if (r == null) {
5556                                        r = new StringBuilder(256);
5557                                    } else {
5558                                        r.append(' ');
5559                                    }
5560                                    r.append(p.info.name);
5561                                }
5562                            } else {
5563                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5564                                        + p.info.packageName + " ignored: base tree "
5565                                        + tree.name + " is from package "
5566                                        + tree.sourcePackage);
5567                            }
5568                        } else {
5569                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5570                                    + p.info.packageName + " ignored: original from "
5571                                    + bp.sourcePackage);
5572                        }
5573                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5574                        if (r == null) {
5575                            r = new StringBuilder(256);
5576                        } else {
5577                            r.append(' ');
5578                        }
5579                        r.append("DUP:");
5580                        r.append(p.info.name);
5581                    }
5582                    if (bp.perm == p) {
5583                        bp.protectionLevel = p.info.protectionLevel;
5584                    }
5585                } else {
5586                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5587                            + p.info.packageName + " ignored: no group "
5588                            + p.group);
5589                }
5590            }
5591            if (r != null) {
5592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5593            }
5594
5595            N = pkg.instrumentation.size();
5596            r = null;
5597            for (i=0; i<N; i++) {
5598                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5599                a.info.packageName = pkg.applicationInfo.packageName;
5600                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5601                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5602                a.info.dataDir = pkg.applicationInfo.dataDir;
5603                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5604                mInstrumentation.put(a.getComponentName(), a);
5605                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5606                    if (r == null) {
5607                        r = new StringBuilder(256);
5608                    } else {
5609                        r.append(' ');
5610                    }
5611                    r.append(a.info.name);
5612                }
5613            }
5614            if (r != null) {
5615                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5616            }
5617
5618            if (pkg.protectedBroadcasts != null) {
5619                N = pkg.protectedBroadcasts.size();
5620                for (i=0; i<N; i++) {
5621                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5622                }
5623            }
5624
5625            pkgSetting.setTimeStamp(scanFileTime);
5626
5627            // Create idmap files for pairs of (packages, overlay packages).
5628            // Note: "android", ie framework-res.apk, is handled by native layers.
5629            if (pkg.mOverlayTarget != null) {
5630                // This is an overlay package.
5631                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5632                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5633                        mOverlays.put(pkg.mOverlayTarget,
5634                                new HashMap<String, PackageParser.Package>());
5635                    }
5636                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5637                    map.put(pkg.packageName, pkg);
5638                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5639                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5640                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5641                        return null;
5642                    }
5643                }
5644            } else if (mOverlays.containsKey(pkg.packageName) &&
5645                    !pkg.packageName.equals("android")) {
5646                // This is a regular package, with one or more known overlay packages.
5647                createIdmapsForPackageLI(pkg);
5648            }
5649        }
5650
5651        return pkg;
5652    }
5653
5654    /**
5655     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5656     * i.e, so that all packages can be run inside a single process if required.
5657     *
5658     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5659     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5660     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5661     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5662     * updating a package that belongs to a shared user.
5663     */
5664    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5665            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5666        String requiredInstructionSet = null;
5667        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5668            requiredInstructionSet = VMRuntime.getInstructionSet(
5669                     scannedPackage.applicationInfo.cpuAbi);
5670        }
5671
5672        PackageSetting requirer = null;
5673        for (PackageSetting ps : packagesForUser) {
5674            // If packagesForUser contains scannedPackage, we skip it. This will happen
5675            // when scannedPackage is an update of an existing package. Without this check,
5676            // we will never be able to change the ABI of any package belonging to a shared
5677            // user, even if it's compatible with other packages.
5678            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
5679                if (ps.cpuAbiString == null) {
5680                    continue;
5681                }
5682
5683                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5684                if (requiredInstructionSet != null) {
5685                    if (!instructionSet.equals(requiredInstructionSet)) {
5686                        // We have a mismatch between instruction sets (say arm vs arm64).
5687                        // bail out.
5688                        String errorMessage = "Instruction set mismatch, "
5689                                + ((requirer == null) ? "[caller]" : requirer)
5690                                + " requires " + requiredInstructionSet + " whereas " + ps
5691                                + " requires " + instructionSet;
5692                        Slog.e(TAG, errorMessage);
5693
5694                        reportSettingsProblem(Log.WARN, errorMessage);
5695                        // Give up, don't bother making any other changes to the package settings.
5696                        return false;
5697                    }
5698                } else {
5699                    requiredInstructionSet = instructionSet;
5700                    requirer = ps;
5701                }
5702            }
5703        }
5704
5705        if (requiredInstructionSet != null) {
5706            String adjustedAbi;
5707            if (requirer != null) {
5708                // requirer != null implies that either scannedPackage was null or that scannedPackage
5709                // did not require an ABI, in which case we have to adjust scannedPackage to match
5710                // the ABI of the set (which is the same as requirer's ABI)
5711                adjustedAbi = requirer.cpuAbiString;
5712                if (scannedPackage != null) {
5713                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
5714                }
5715            } else {
5716                // requirer == null implies that we're updating all ABIs in the set to
5717                // match scannedPackage.
5718                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
5719            }
5720
5721            for (PackageSetting ps : packagesForUser) {
5722                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
5723                    if (ps.cpuAbiString != null) {
5724                        continue;
5725                    }
5726
5727                    ps.cpuAbiString = adjustedAbi;
5728                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5729                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
5730                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
5731
5732                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
5733                            ps.cpuAbiString = null;
5734                            ps.pkg.applicationInfo.cpuAbi = null;
5735                            return false;
5736                        } else {
5737                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5738                        }
5739                    }
5740                }
5741            }
5742        }
5743
5744        return true;
5745    }
5746
5747    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5748        synchronized (mPackages) {
5749            mResolverReplaced = true;
5750            // Set up information for custom user intent resolution activity.
5751            mResolveActivity.applicationInfo = pkg.applicationInfo;
5752            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5753            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5754            mResolveActivity.processName = null;
5755            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5756            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5757                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5758            mResolveActivity.theme = 0;
5759            mResolveActivity.exported = true;
5760            mResolveActivity.enabled = true;
5761            mResolveInfo.activityInfo = mResolveActivity;
5762            mResolveInfo.priority = 0;
5763            mResolveInfo.preferredOrder = 0;
5764            mResolveInfo.match = 0;
5765            mResolveComponentName = mCustomResolverComponentName;
5766            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5767                    mResolveComponentName);
5768        }
5769    }
5770
5771    private String calculateApkRoot(final String codePathString) {
5772        final File codePath = new File(codePathString);
5773        final File codeRoot;
5774        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5775            codeRoot = Environment.getRootDirectory();
5776        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5777            codeRoot = Environment.getOemDirectory();
5778        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5779            codeRoot = Environment.getVendorDirectory();
5780        } else {
5781            // Unrecognized code path; take its top real segment as the apk root:
5782            // e.g. /something/app/blah.apk => /something
5783            try {
5784                File f = codePath.getCanonicalFile();
5785                File parent = f.getParentFile();    // non-null because codePath is a file
5786                File tmp;
5787                while ((tmp = parent.getParentFile()) != null) {
5788                    f = parent;
5789                    parent = tmp;
5790                }
5791                codeRoot = f;
5792                Slog.w(TAG, "Unrecognized code path "
5793                        + codePath + " - using " + codeRoot);
5794            } catch (IOException e) {
5795                // Can't canonicalize the lib path -- shenanigans?
5796                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5797                return Environment.getRootDirectory().getPath();
5798            }
5799        }
5800        return codeRoot.getPath();
5801    }
5802
5803    // This is the initial scan-time determination of how to handle a given
5804    // package for purposes of native library location.
5805    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5806            PackageSetting pkgSetting) {
5807        // "bundled" here means system-installed with no overriding update
5808        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5809        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5810        final File libDir;
5811        if (bundledApk) {
5812            // If "/system/lib64/apkname" exists, assume that is the per-package
5813            // native library directory to use; otherwise use "/system/lib/apkname".
5814            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5815            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5816            File packLib64 = new File(lib64, apkName);
5817            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5818        } else {
5819            libDir = mAppLibInstallDir;
5820        }
5821        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5822        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5823        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5824    }
5825
5826    // Deduces the required ABI of an upgraded system app.
5827    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
5828        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5829        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5830
5831        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
5832        // or similar.
5833        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
5834        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
5835
5836        // Assume that the bundled native libraries always correspond to the
5837        // most preferred 32 or 64 bit ABI.
5838        if (lib64.exists()) {
5839            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
5840            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
5841        } else if (lib.exists()) {
5842            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5843            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
5844        } else {
5845            // This is the case where the app has no native code.
5846            pkg.applicationInfo.cpuAbi = null;
5847            pkgSetting.cpuAbiString = null;
5848        }
5849    }
5850
5851    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
5852            final File nativeLibraryDir, String[] abiList) throws IOException {
5853        if (!nativeLibraryDir.isDirectory()) {
5854            nativeLibraryDir.delete();
5855
5856            if (!nativeLibraryDir.mkdir()) {
5857                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5858            }
5859
5860            try {
5861                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5862            } catch (ErrnoException e) {
5863                throw new IOException("Cannot chmod native library directory "
5864                        + nativeLibraryDir.getPath(), e);
5865            }
5866        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5867            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5868        }
5869
5870        /*
5871         * If this is an internal application or our nativeLibraryPath points to
5872         * the app-lib directory, unpack the libraries if necessary.
5873         */
5874        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5875        if (abi >= 0) {
5876            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5877                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5878            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5879                return copyRet;
5880            }
5881        }
5882
5883        return abi;
5884    }
5885
5886    private void killApplication(String pkgName, int appId, String reason) {
5887        // Request the ActivityManager to kill the process(only for existing packages)
5888        // so that we do not end up in a confused state while the user is still using the older
5889        // version of the application while the new one gets installed.
5890        IActivityManager am = ActivityManagerNative.getDefault();
5891        if (am != null) {
5892            try {
5893                am.killApplicationWithAppId(pkgName, appId, reason);
5894            } catch (RemoteException e) {
5895            }
5896        }
5897    }
5898
5899    void removePackageLI(PackageSetting ps, boolean chatty) {
5900        if (DEBUG_INSTALL) {
5901            if (chatty)
5902                Log.d(TAG, "Removing package " + ps.name);
5903        }
5904
5905        // writer
5906        synchronized (mPackages) {
5907            mPackages.remove(ps.name);
5908            if (ps.codePathString != null) {
5909                mAppDirs.remove(ps.codePathString);
5910            }
5911
5912            final PackageParser.Package pkg = ps.pkg;
5913            if (pkg != null) {
5914                cleanPackageDataStructuresLILPw(pkg, chatty);
5915            }
5916        }
5917    }
5918
5919    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5920        if (DEBUG_INSTALL) {
5921            if (chatty)
5922                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5923        }
5924
5925        // writer
5926        synchronized (mPackages) {
5927            mPackages.remove(pkg.applicationInfo.packageName);
5928            if (pkg.mPath != null) {
5929                mAppDirs.remove(pkg.mPath);
5930            }
5931            cleanPackageDataStructuresLILPw(pkg, chatty);
5932        }
5933    }
5934
5935    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5936        int N = pkg.providers.size();
5937        StringBuilder r = null;
5938        int i;
5939        for (i=0; i<N; i++) {
5940            PackageParser.Provider p = pkg.providers.get(i);
5941            mProviders.removeProvider(p);
5942            if (p.info.authority == null) {
5943
5944                /* There was another ContentProvider with this authority when
5945                 * this app was installed so this authority is null,
5946                 * Ignore it as we don't have to unregister the provider.
5947                 */
5948                continue;
5949            }
5950            String names[] = p.info.authority.split(";");
5951            for (int j = 0; j < names.length; j++) {
5952                if (mProvidersByAuthority.get(names[j]) == p) {
5953                    mProvidersByAuthority.remove(names[j]);
5954                    if (DEBUG_REMOVE) {
5955                        if (chatty)
5956                            Log.d(TAG, "Unregistered content provider: " + names[j]
5957                                    + ", className = " + p.info.name + ", isSyncable = "
5958                                    + p.info.isSyncable);
5959                    }
5960                }
5961            }
5962            if (DEBUG_REMOVE && chatty) {
5963                if (r == null) {
5964                    r = new StringBuilder(256);
5965                } else {
5966                    r.append(' ');
5967                }
5968                r.append(p.info.name);
5969            }
5970        }
5971        if (r != null) {
5972            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5973        }
5974
5975        N = pkg.services.size();
5976        r = null;
5977        for (i=0; i<N; i++) {
5978            PackageParser.Service s = pkg.services.get(i);
5979            mServices.removeService(s);
5980            if (chatty) {
5981                if (r == null) {
5982                    r = new StringBuilder(256);
5983                } else {
5984                    r.append(' ');
5985                }
5986                r.append(s.info.name);
5987            }
5988        }
5989        if (r != null) {
5990            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5991        }
5992
5993        N = pkg.receivers.size();
5994        r = null;
5995        for (i=0; i<N; i++) {
5996            PackageParser.Activity a = pkg.receivers.get(i);
5997            mReceivers.removeActivity(a, "receiver");
5998            if (DEBUG_REMOVE && chatty) {
5999                if (r == null) {
6000                    r = new StringBuilder(256);
6001                } else {
6002                    r.append(' ');
6003                }
6004                r.append(a.info.name);
6005            }
6006        }
6007        if (r != null) {
6008            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6009        }
6010
6011        N = pkg.activities.size();
6012        r = null;
6013        for (i=0; i<N; i++) {
6014            PackageParser.Activity a = pkg.activities.get(i);
6015            mActivities.removeActivity(a, "activity");
6016            if (DEBUG_REMOVE && chatty) {
6017                if (r == null) {
6018                    r = new StringBuilder(256);
6019                } else {
6020                    r.append(' ');
6021                }
6022                r.append(a.info.name);
6023            }
6024        }
6025        if (r != null) {
6026            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6027        }
6028
6029        N = pkg.permissions.size();
6030        r = null;
6031        for (i=0; i<N; i++) {
6032            PackageParser.Permission p = pkg.permissions.get(i);
6033            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6034            if (bp == null) {
6035                bp = mSettings.mPermissionTrees.get(p.info.name);
6036            }
6037            if (bp != null && bp.perm == p) {
6038                bp.perm = null;
6039                if (DEBUG_REMOVE && chatty) {
6040                    if (r == null) {
6041                        r = new StringBuilder(256);
6042                    } else {
6043                        r.append(' ');
6044                    }
6045                    r.append(p.info.name);
6046                }
6047            }
6048        }
6049        if (r != null) {
6050            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6051        }
6052
6053        N = pkg.instrumentation.size();
6054        r = null;
6055        for (i=0; i<N; i++) {
6056            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6057            mInstrumentation.remove(a.getComponentName());
6058            if (DEBUG_REMOVE && chatty) {
6059                if (r == null) {
6060                    r = new StringBuilder(256);
6061                } else {
6062                    r.append(' ');
6063                }
6064                r.append(a.info.name);
6065            }
6066        }
6067        if (r != null) {
6068            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6069        }
6070
6071        r = null;
6072        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6073            // Only system apps can hold shared libraries.
6074            if (pkg.libraryNames != null) {
6075                for (i=0; i<pkg.libraryNames.size(); i++) {
6076                    String name = pkg.libraryNames.get(i);
6077                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6078                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6079                        mSharedLibraries.remove(name);
6080                        if (DEBUG_REMOVE && chatty) {
6081                            if (r == null) {
6082                                r = new StringBuilder(256);
6083                            } else {
6084                                r.append(' ');
6085                            }
6086                            r.append(name);
6087                        }
6088                    }
6089                }
6090            }
6091        }
6092        if (r != null) {
6093            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6094        }
6095    }
6096
6097    private static final boolean isPackageFilename(String name) {
6098        return name != null && name.endsWith(".apk");
6099    }
6100
6101    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6102        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6103            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6104                return true;
6105            }
6106        }
6107        return false;
6108    }
6109
6110    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6111    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6112    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6113
6114    private void updatePermissionsLPw(String changingPkg,
6115            PackageParser.Package pkgInfo, int flags) {
6116        // Make sure there are no dangling permission trees.
6117        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6118        while (it.hasNext()) {
6119            final BasePermission bp = it.next();
6120            if (bp.packageSetting == null) {
6121                // We may not yet have parsed the package, so just see if
6122                // we still know about its settings.
6123                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6124            }
6125            if (bp.packageSetting == null) {
6126                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6127                        + " from package " + bp.sourcePackage);
6128                it.remove();
6129            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6130                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6131                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6132                            + " from package " + bp.sourcePackage);
6133                    flags |= UPDATE_PERMISSIONS_ALL;
6134                    it.remove();
6135                }
6136            }
6137        }
6138
6139        // Make sure all dynamic permissions have been assigned to a package,
6140        // and make sure there are no dangling permissions.
6141        it = mSettings.mPermissions.values().iterator();
6142        while (it.hasNext()) {
6143            final BasePermission bp = it.next();
6144            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6145                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6146                        + bp.name + " pkg=" + bp.sourcePackage
6147                        + " info=" + bp.pendingInfo);
6148                if (bp.packageSetting == null && bp.pendingInfo != null) {
6149                    final BasePermission tree = findPermissionTreeLP(bp.name);
6150                    if (tree != null && tree.perm != null) {
6151                        bp.packageSetting = tree.packageSetting;
6152                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6153                                new PermissionInfo(bp.pendingInfo));
6154                        bp.perm.info.packageName = tree.perm.info.packageName;
6155                        bp.perm.info.name = bp.name;
6156                        bp.uid = tree.uid;
6157                    }
6158                }
6159            }
6160            if (bp.packageSetting == null) {
6161                // We may not yet have parsed the package, so just see if
6162                // we still know about its settings.
6163                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6164            }
6165            if (bp.packageSetting == null) {
6166                Slog.w(TAG, "Removing dangling permission: " + bp.name
6167                        + " from package " + bp.sourcePackage);
6168                it.remove();
6169            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6170                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6171                    Slog.i(TAG, "Removing old permission: " + bp.name
6172                            + " from package " + bp.sourcePackage);
6173                    flags |= UPDATE_PERMISSIONS_ALL;
6174                    it.remove();
6175                }
6176            }
6177        }
6178
6179        // Now update the permissions for all packages, in particular
6180        // replace the granted permissions of the system packages.
6181        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6182            for (PackageParser.Package pkg : mPackages.values()) {
6183                if (pkg != pkgInfo) {
6184                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6185                }
6186            }
6187        }
6188
6189        if (pkgInfo != null) {
6190            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6191        }
6192    }
6193
6194    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6195        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6196        if (ps == null) {
6197            return;
6198        }
6199        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6200        HashSet<String> origPermissions = gp.grantedPermissions;
6201        boolean changedPermission = false;
6202
6203        if (replace) {
6204            ps.permissionsFixed = false;
6205            if (gp == ps) {
6206                origPermissions = new HashSet<String>(gp.grantedPermissions);
6207                gp.grantedPermissions.clear();
6208                gp.gids = mGlobalGids;
6209            }
6210        }
6211
6212        if (gp.gids == null) {
6213            gp.gids = mGlobalGids;
6214        }
6215
6216        final int N = pkg.requestedPermissions.size();
6217        for (int i=0; i<N; i++) {
6218            final String name = pkg.requestedPermissions.get(i);
6219            final boolean required = pkg.requestedPermissionsRequired.get(i);
6220            final BasePermission bp = mSettings.mPermissions.get(name);
6221            if (DEBUG_INSTALL) {
6222                if (gp != ps) {
6223                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6224                }
6225            }
6226
6227            if (bp == null || bp.packageSetting == null) {
6228                Slog.w(TAG, "Unknown permission " + name
6229                        + " in package " + pkg.packageName);
6230                continue;
6231            }
6232
6233            final String perm = bp.name;
6234            boolean allowed;
6235            boolean allowedSig = false;
6236            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6237            if (level == PermissionInfo.PROTECTION_NORMAL
6238                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6239                // We grant a normal or dangerous permission if any of the following
6240                // are true:
6241                // 1) The permission is required
6242                // 2) The permission is optional, but was granted in the past
6243                // 3) The permission is optional, but was requested by an
6244                //    app in /system (not /data)
6245                //
6246                // Otherwise, reject the permission.
6247                allowed = (required || origPermissions.contains(perm)
6248                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6249            } else if (bp.packageSetting == null) {
6250                // This permission is invalid; skip it.
6251                allowed = false;
6252            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6253                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6254                if (allowed) {
6255                    allowedSig = true;
6256                }
6257            } else {
6258                allowed = false;
6259            }
6260            if (DEBUG_INSTALL) {
6261                if (gp != ps) {
6262                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6263                }
6264            }
6265            if (allowed) {
6266                if (!isSystemApp(ps) && ps.permissionsFixed) {
6267                    // If this is an existing, non-system package, then
6268                    // we can't add any new permissions to it.
6269                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6270                        // Except...  if this is a permission that was added
6271                        // to the platform (note: need to only do this when
6272                        // updating the platform).
6273                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6274                    }
6275                }
6276                if (allowed) {
6277                    if (!gp.grantedPermissions.contains(perm)) {
6278                        changedPermission = true;
6279                        gp.grantedPermissions.add(perm);
6280                        gp.gids = appendInts(gp.gids, bp.gids);
6281                    } else if (!ps.haveGids) {
6282                        gp.gids = appendInts(gp.gids, bp.gids);
6283                    }
6284                } else {
6285                    Slog.w(TAG, "Not granting permission " + perm
6286                            + " to package " + pkg.packageName
6287                            + " because it was previously installed without");
6288                }
6289            } else {
6290                if (gp.grantedPermissions.remove(perm)) {
6291                    changedPermission = true;
6292                    gp.gids = removeInts(gp.gids, bp.gids);
6293                    Slog.i(TAG, "Un-granting permission " + perm
6294                            + " from package " + pkg.packageName
6295                            + " (protectionLevel=" + bp.protectionLevel
6296                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6297                            + ")");
6298                } else {
6299                    Slog.w(TAG, "Not granting permission " + perm
6300                            + " to package " + pkg.packageName
6301                            + " (protectionLevel=" + bp.protectionLevel
6302                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6303                            + ")");
6304                }
6305            }
6306        }
6307
6308        if ((changedPermission || replace) && !ps.permissionsFixed &&
6309                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6310            // This is the first that we have heard about this package, so the
6311            // permissions we have now selected are fixed until explicitly
6312            // changed.
6313            ps.permissionsFixed = true;
6314        }
6315        ps.haveGids = true;
6316    }
6317
6318    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6319        boolean allowed = false;
6320        final int NP = PackageParser.NEW_PERMISSIONS.length;
6321        for (int ip=0; ip<NP; ip++) {
6322            final PackageParser.NewPermissionInfo npi
6323                    = PackageParser.NEW_PERMISSIONS[ip];
6324            if (npi.name.equals(perm)
6325                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6326                allowed = true;
6327                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6328                        + pkg.packageName);
6329                break;
6330            }
6331        }
6332        return allowed;
6333    }
6334
6335    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6336                                          BasePermission bp, HashSet<String> origPermissions) {
6337        boolean allowed;
6338        allowed = (compareSignatures(
6339                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6340                        == PackageManager.SIGNATURE_MATCH)
6341                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6342                        == PackageManager.SIGNATURE_MATCH);
6343        if (!allowed && (bp.protectionLevel
6344                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6345            if (isSystemApp(pkg)) {
6346                // For updated system applications, a system permission
6347                // is granted only if it had been defined by the original application.
6348                if (isUpdatedSystemApp(pkg)) {
6349                    final PackageSetting sysPs = mSettings
6350                            .getDisabledSystemPkgLPr(pkg.packageName);
6351                    final GrantedPermissions origGp = sysPs.sharedUser != null
6352                            ? sysPs.sharedUser : sysPs;
6353
6354                    if (origGp.grantedPermissions.contains(perm)) {
6355                        // If the original was granted this permission, we take
6356                        // that grant decision as read and propagate it to the
6357                        // update.
6358                        allowed = true;
6359                    } else {
6360                        // The system apk may have been updated with an older
6361                        // version of the one on the data partition, but which
6362                        // granted a new system permission that it didn't have
6363                        // before.  In this case we do want to allow the app to
6364                        // now get the new permission if the ancestral apk is
6365                        // privileged to get it.
6366                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6367                            for (int j=0;
6368                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6369                                if (perm.equals(
6370                                        sysPs.pkg.requestedPermissions.get(j))) {
6371                                    allowed = true;
6372                                    break;
6373                                }
6374                            }
6375                        }
6376                    }
6377                } else {
6378                    allowed = isPrivilegedApp(pkg);
6379                }
6380            }
6381        }
6382        if (!allowed && (bp.protectionLevel
6383                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6384            // For development permissions, a development permission
6385            // is granted only if it was already granted.
6386            allowed = origPermissions.contains(perm);
6387        }
6388        return allowed;
6389    }
6390
6391    final class ActivityIntentResolver
6392            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6393        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6394                boolean defaultOnly, int userId) {
6395            if (!sUserManager.exists(userId)) return null;
6396            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6397            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6398        }
6399
6400        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6401                int userId) {
6402            if (!sUserManager.exists(userId)) return null;
6403            mFlags = flags;
6404            return super.queryIntent(intent, resolvedType,
6405                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6406        }
6407
6408        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6409                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6410            if (!sUserManager.exists(userId)) return null;
6411            if (packageActivities == null) {
6412                return null;
6413            }
6414            mFlags = flags;
6415            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6416            final int N = packageActivities.size();
6417            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6418                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6419
6420            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6421            for (int i = 0; i < N; ++i) {
6422                intentFilters = packageActivities.get(i).intents;
6423                if (intentFilters != null && intentFilters.size() > 0) {
6424                    PackageParser.ActivityIntentInfo[] array =
6425                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6426                    intentFilters.toArray(array);
6427                    listCut.add(array);
6428                }
6429            }
6430            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6431        }
6432
6433        public final void addActivity(PackageParser.Activity a, String type) {
6434            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6435            mActivities.put(a.getComponentName(), a);
6436            if (DEBUG_SHOW_INFO)
6437                Log.v(
6438                TAG, "  " + type + " " +
6439                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6440            if (DEBUG_SHOW_INFO)
6441                Log.v(TAG, "    Class=" + a.info.name);
6442            final int NI = a.intents.size();
6443            for (int j=0; j<NI; j++) {
6444                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6445                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6446                    intent.setPriority(0);
6447                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6448                            + a.className + " with priority > 0, forcing to 0");
6449                }
6450                if (DEBUG_SHOW_INFO) {
6451                    Log.v(TAG, "    IntentFilter:");
6452                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6453                }
6454                if (!intent.debugCheck()) {
6455                    Log.w(TAG, "==> For Activity " + a.info.name);
6456                }
6457                addFilter(intent);
6458            }
6459        }
6460
6461        public final void removeActivity(PackageParser.Activity a, String type) {
6462            mActivities.remove(a.getComponentName());
6463            if (DEBUG_SHOW_INFO) {
6464                Log.v(TAG, "  " + type + " "
6465                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6466                                : a.info.name) + ":");
6467                Log.v(TAG, "    Class=" + a.info.name);
6468            }
6469            final int NI = a.intents.size();
6470            for (int j=0; j<NI; j++) {
6471                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6472                if (DEBUG_SHOW_INFO) {
6473                    Log.v(TAG, "    IntentFilter:");
6474                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6475                }
6476                removeFilter(intent);
6477            }
6478        }
6479
6480        @Override
6481        protected boolean allowFilterResult(
6482                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6483            ActivityInfo filterAi = filter.activity.info;
6484            for (int i=dest.size()-1; i>=0; i--) {
6485                ActivityInfo destAi = dest.get(i).activityInfo;
6486                if (destAi.name == filterAi.name
6487                        && destAi.packageName == filterAi.packageName) {
6488                    return false;
6489                }
6490            }
6491            return true;
6492        }
6493
6494        @Override
6495        protected ActivityIntentInfo[] newArray(int size) {
6496            return new ActivityIntentInfo[size];
6497        }
6498
6499        @Override
6500        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6501            if (!sUserManager.exists(userId)) return true;
6502            PackageParser.Package p = filter.activity.owner;
6503            if (p != null) {
6504                PackageSetting ps = (PackageSetting)p.mExtras;
6505                if (ps != null) {
6506                    // System apps are never considered stopped for purposes of
6507                    // filtering, because there may be no way for the user to
6508                    // actually re-launch them.
6509                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6510                            && ps.getStopped(userId);
6511                }
6512            }
6513            return false;
6514        }
6515
6516        @Override
6517        protected boolean isPackageForFilter(String packageName,
6518                PackageParser.ActivityIntentInfo info) {
6519            return packageName.equals(info.activity.owner.packageName);
6520        }
6521
6522        @Override
6523        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6524                int match, int userId) {
6525            if (!sUserManager.exists(userId)) return null;
6526            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6527                return null;
6528            }
6529            final PackageParser.Activity activity = info.activity;
6530            if (mSafeMode && (activity.info.applicationInfo.flags
6531                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6532                return null;
6533            }
6534            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6535            if (ps == null) {
6536                return null;
6537            }
6538            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6539                    ps.readUserState(userId), userId);
6540            if (ai == null) {
6541                return null;
6542            }
6543            final ResolveInfo res = new ResolveInfo();
6544            res.activityInfo = ai;
6545            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6546                res.filter = info;
6547            }
6548            res.priority = info.getPriority();
6549            res.preferredOrder = activity.owner.mPreferredOrder;
6550            //System.out.println("Result: " + res.activityInfo.className +
6551            //                   " = " + res.priority);
6552            res.match = match;
6553            res.isDefault = info.hasDefault;
6554            res.labelRes = info.labelRes;
6555            res.nonLocalizedLabel = info.nonLocalizedLabel;
6556            res.icon = info.icon;
6557            res.system = isSystemApp(res.activityInfo.applicationInfo);
6558            return res;
6559        }
6560
6561        @Override
6562        protected void sortResults(List<ResolveInfo> results) {
6563            Collections.sort(results, mResolvePrioritySorter);
6564        }
6565
6566        @Override
6567        protected void dumpFilter(PrintWriter out, String prefix,
6568                PackageParser.ActivityIntentInfo filter) {
6569            out.print(prefix); out.print(
6570                    Integer.toHexString(System.identityHashCode(filter.activity)));
6571                    out.print(' ');
6572                    filter.activity.printComponentShortName(out);
6573                    out.print(" filter ");
6574                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6575        }
6576
6577//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6578//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6579//            final List<ResolveInfo> retList = Lists.newArrayList();
6580//            while (i.hasNext()) {
6581//                final ResolveInfo resolveInfo = i.next();
6582//                if (isEnabledLP(resolveInfo.activityInfo)) {
6583//                    retList.add(resolveInfo);
6584//                }
6585//            }
6586//            return retList;
6587//        }
6588
6589        // Keys are String (activity class name), values are Activity.
6590        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6591                = new HashMap<ComponentName, PackageParser.Activity>();
6592        private int mFlags;
6593    }
6594
6595    private final class ServiceIntentResolver
6596            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6598                boolean defaultOnly, int userId) {
6599            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6600            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6601        }
6602
6603        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6604                int userId) {
6605            if (!sUserManager.exists(userId)) return null;
6606            mFlags = flags;
6607            return super.queryIntent(intent, resolvedType,
6608                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6609        }
6610
6611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6612                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6613            if (!sUserManager.exists(userId)) return null;
6614            if (packageServices == null) {
6615                return null;
6616            }
6617            mFlags = flags;
6618            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6619            final int N = packageServices.size();
6620            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6621                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6622
6623            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6624            for (int i = 0; i < N; ++i) {
6625                intentFilters = packageServices.get(i).intents;
6626                if (intentFilters != null && intentFilters.size() > 0) {
6627                    PackageParser.ServiceIntentInfo[] array =
6628                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6629                    intentFilters.toArray(array);
6630                    listCut.add(array);
6631                }
6632            }
6633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6634        }
6635
6636        public final void addService(PackageParser.Service s) {
6637            mServices.put(s.getComponentName(), s);
6638            if (DEBUG_SHOW_INFO) {
6639                Log.v(TAG, "  "
6640                        + (s.info.nonLocalizedLabel != null
6641                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6642                Log.v(TAG, "    Class=" + s.info.name);
6643            }
6644            final int NI = s.intents.size();
6645            int j;
6646            for (j=0; j<NI; j++) {
6647                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6648                if (DEBUG_SHOW_INFO) {
6649                    Log.v(TAG, "    IntentFilter:");
6650                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6651                }
6652                if (!intent.debugCheck()) {
6653                    Log.w(TAG, "==> For Service " + s.info.name);
6654                }
6655                addFilter(intent);
6656            }
6657        }
6658
6659        public final void removeService(PackageParser.Service s) {
6660            mServices.remove(s.getComponentName());
6661            if (DEBUG_SHOW_INFO) {
6662                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6663                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6664                Log.v(TAG, "    Class=" + s.info.name);
6665            }
6666            final int NI = s.intents.size();
6667            int j;
6668            for (j=0; j<NI; j++) {
6669                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6670                if (DEBUG_SHOW_INFO) {
6671                    Log.v(TAG, "    IntentFilter:");
6672                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6673                }
6674                removeFilter(intent);
6675            }
6676        }
6677
6678        @Override
6679        protected boolean allowFilterResult(
6680                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6681            ServiceInfo filterSi = filter.service.info;
6682            for (int i=dest.size()-1; i>=0; i--) {
6683                ServiceInfo destAi = dest.get(i).serviceInfo;
6684                if (destAi.name == filterSi.name
6685                        && destAi.packageName == filterSi.packageName) {
6686                    return false;
6687                }
6688            }
6689            return true;
6690        }
6691
6692        @Override
6693        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6694            return new PackageParser.ServiceIntentInfo[size];
6695        }
6696
6697        @Override
6698        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6699            if (!sUserManager.exists(userId)) return true;
6700            PackageParser.Package p = filter.service.owner;
6701            if (p != null) {
6702                PackageSetting ps = (PackageSetting)p.mExtras;
6703                if (ps != null) {
6704                    // System apps are never considered stopped for purposes of
6705                    // filtering, because there may be no way for the user to
6706                    // actually re-launch them.
6707                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6708                            && ps.getStopped(userId);
6709                }
6710            }
6711            return false;
6712        }
6713
6714        @Override
6715        protected boolean isPackageForFilter(String packageName,
6716                PackageParser.ServiceIntentInfo info) {
6717            return packageName.equals(info.service.owner.packageName);
6718        }
6719
6720        @Override
6721        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6722                int match, int userId) {
6723            if (!sUserManager.exists(userId)) return null;
6724            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6725            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6726                return null;
6727            }
6728            final PackageParser.Service service = info.service;
6729            if (mSafeMode && (service.info.applicationInfo.flags
6730                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6731                return null;
6732            }
6733            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6734            if (ps == null) {
6735                return null;
6736            }
6737            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6738                    ps.readUserState(userId), userId);
6739            if (si == null) {
6740                return null;
6741            }
6742            final ResolveInfo res = new ResolveInfo();
6743            res.serviceInfo = si;
6744            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6745                res.filter = filter;
6746            }
6747            res.priority = info.getPriority();
6748            res.preferredOrder = service.owner.mPreferredOrder;
6749            //System.out.println("Result: " + res.activityInfo.className +
6750            //                   " = " + res.priority);
6751            res.match = match;
6752            res.isDefault = info.hasDefault;
6753            res.labelRes = info.labelRes;
6754            res.nonLocalizedLabel = info.nonLocalizedLabel;
6755            res.icon = info.icon;
6756            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6757            return res;
6758        }
6759
6760        @Override
6761        protected void sortResults(List<ResolveInfo> results) {
6762            Collections.sort(results, mResolvePrioritySorter);
6763        }
6764
6765        @Override
6766        protected void dumpFilter(PrintWriter out, String prefix,
6767                PackageParser.ServiceIntentInfo filter) {
6768            out.print(prefix); out.print(
6769                    Integer.toHexString(System.identityHashCode(filter.service)));
6770                    out.print(' ');
6771                    filter.service.printComponentShortName(out);
6772                    out.print(" filter ");
6773                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6774        }
6775
6776//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6777//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6778//            final List<ResolveInfo> retList = Lists.newArrayList();
6779//            while (i.hasNext()) {
6780//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6781//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6782//                    retList.add(resolveInfo);
6783//                }
6784//            }
6785//            return retList;
6786//        }
6787
6788        // Keys are String (activity class name), values are Activity.
6789        private final HashMap<ComponentName, PackageParser.Service> mServices
6790                = new HashMap<ComponentName, PackageParser.Service>();
6791        private int mFlags;
6792    };
6793
6794    private final class ProviderIntentResolver
6795            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6796        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6797                boolean defaultOnly, int userId) {
6798            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6799            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6800        }
6801
6802        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6803                int userId) {
6804            if (!sUserManager.exists(userId))
6805                return null;
6806            mFlags = flags;
6807            return super.queryIntent(intent, resolvedType,
6808                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6809        }
6810
6811        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6812                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6813            if (!sUserManager.exists(userId))
6814                return null;
6815            if (packageProviders == null) {
6816                return null;
6817            }
6818            mFlags = flags;
6819            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6820            final int N = packageProviders.size();
6821            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6822                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6823
6824            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6825            for (int i = 0; i < N; ++i) {
6826                intentFilters = packageProviders.get(i).intents;
6827                if (intentFilters != null && intentFilters.size() > 0) {
6828                    PackageParser.ProviderIntentInfo[] array =
6829                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6830                    intentFilters.toArray(array);
6831                    listCut.add(array);
6832                }
6833            }
6834            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6835        }
6836
6837        public final void addProvider(PackageParser.Provider p) {
6838            mProviders.put(p.getComponentName(), p);
6839            if (DEBUG_SHOW_INFO) {
6840                Log.v(TAG, "  "
6841                        + (p.info.nonLocalizedLabel != null
6842                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6843                Log.v(TAG, "    Class=" + p.info.name);
6844            }
6845            final int NI = p.intents.size();
6846            int j;
6847            for (j = 0; j < NI; j++) {
6848                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6849                if (DEBUG_SHOW_INFO) {
6850                    Log.v(TAG, "    IntentFilter:");
6851                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6852                }
6853                if (!intent.debugCheck()) {
6854                    Log.w(TAG, "==> For Provider " + p.info.name);
6855                }
6856                addFilter(intent);
6857            }
6858        }
6859
6860        public final void removeProvider(PackageParser.Provider p) {
6861            mProviders.remove(p.getComponentName());
6862            if (DEBUG_SHOW_INFO) {
6863                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6864                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6865                Log.v(TAG, "    Class=" + p.info.name);
6866            }
6867            final int NI = p.intents.size();
6868            int j;
6869            for (j = 0; j < NI; j++) {
6870                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6871                if (DEBUG_SHOW_INFO) {
6872                    Log.v(TAG, "    IntentFilter:");
6873                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6874                }
6875                removeFilter(intent);
6876            }
6877        }
6878
6879        @Override
6880        protected boolean allowFilterResult(
6881                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6882            ProviderInfo filterPi = filter.provider.info;
6883            for (int i = dest.size() - 1; i >= 0; i--) {
6884                ProviderInfo destPi = dest.get(i).providerInfo;
6885                if (destPi.name == filterPi.name
6886                        && destPi.packageName == filterPi.packageName) {
6887                    return false;
6888                }
6889            }
6890            return true;
6891        }
6892
6893        @Override
6894        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6895            return new PackageParser.ProviderIntentInfo[size];
6896        }
6897
6898        @Override
6899        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6900            if (!sUserManager.exists(userId))
6901                return true;
6902            PackageParser.Package p = filter.provider.owner;
6903            if (p != null) {
6904                PackageSetting ps = (PackageSetting) p.mExtras;
6905                if (ps != null) {
6906                    // System apps are never considered stopped for purposes of
6907                    // filtering, because there may be no way for the user to
6908                    // actually re-launch them.
6909                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6910                            && ps.getStopped(userId);
6911                }
6912            }
6913            return false;
6914        }
6915
6916        @Override
6917        protected boolean isPackageForFilter(String packageName,
6918                PackageParser.ProviderIntentInfo info) {
6919            return packageName.equals(info.provider.owner.packageName);
6920        }
6921
6922        @Override
6923        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6924                int match, int userId) {
6925            if (!sUserManager.exists(userId))
6926                return null;
6927            final PackageParser.ProviderIntentInfo info = filter;
6928            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6929                return null;
6930            }
6931            final PackageParser.Provider provider = info.provider;
6932            if (mSafeMode && (provider.info.applicationInfo.flags
6933                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6934                return null;
6935            }
6936            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6937            if (ps == null) {
6938                return null;
6939            }
6940            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6941                    ps.readUserState(userId), userId);
6942            if (pi == null) {
6943                return null;
6944            }
6945            final ResolveInfo res = new ResolveInfo();
6946            res.providerInfo = pi;
6947            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6948                res.filter = filter;
6949            }
6950            res.priority = info.getPriority();
6951            res.preferredOrder = provider.owner.mPreferredOrder;
6952            res.match = match;
6953            res.isDefault = info.hasDefault;
6954            res.labelRes = info.labelRes;
6955            res.nonLocalizedLabel = info.nonLocalizedLabel;
6956            res.icon = info.icon;
6957            res.system = isSystemApp(res.providerInfo.applicationInfo);
6958            return res;
6959        }
6960
6961        @Override
6962        protected void sortResults(List<ResolveInfo> results) {
6963            Collections.sort(results, mResolvePrioritySorter);
6964        }
6965
6966        @Override
6967        protected void dumpFilter(PrintWriter out, String prefix,
6968                PackageParser.ProviderIntentInfo filter) {
6969            out.print(prefix);
6970            out.print(
6971                    Integer.toHexString(System.identityHashCode(filter.provider)));
6972            out.print(' ');
6973            filter.provider.printComponentShortName(out);
6974            out.print(" filter ");
6975            out.println(Integer.toHexString(System.identityHashCode(filter)));
6976        }
6977
6978        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6979                = new HashMap<ComponentName, PackageParser.Provider>();
6980        private int mFlags;
6981    };
6982
6983    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6984            new Comparator<ResolveInfo>() {
6985        public int compare(ResolveInfo r1, ResolveInfo r2) {
6986            int v1 = r1.priority;
6987            int v2 = r2.priority;
6988            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6989            if (v1 != v2) {
6990                return (v1 > v2) ? -1 : 1;
6991            }
6992            v1 = r1.preferredOrder;
6993            v2 = r2.preferredOrder;
6994            if (v1 != v2) {
6995                return (v1 > v2) ? -1 : 1;
6996            }
6997            if (r1.isDefault != r2.isDefault) {
6998                return r1.isDefault ? -1 : 1;
6999            }
7000            v1 = r1.match;
7001            v2 = r2.match;
7002            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7003            if (v1 != v2) {
7004                return (v1 > v2) ? -1 : 1;
7005            }
7006            if (r1.system != r2.system) {
7007                return r1.system ? -1 : 1;
7008            }
7009            return 0;
7010        }
7011    };
7012
7013    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7014            new Comparator<ProviderInfo>() {
7015        public int compare(ProviderInfo p1, ProviderInfo p2) {
7016            final int v1 = p1.initOrder;
7017            final int v2 = p2.initOrder;
7018            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7019        }
7020    };
7021
7022    static final void sendPackageBroadcast(String action, String pkg,
7023            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7024            int[] userIds) {
7025        IActivityManager am = ActivityManagerNative.getDefault();
7026        if (am != null) {
7027            try {
7028                if (userIds == null) {
7029                    userIds = am.getRunningUserIds();
7030                }
7031                for (int id : userIds) {
7032                    final Intent intent = new Intent(action,
7033                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7034                    if (extras != null) {
7035                        intent.putExtras(extras);
7036                    }
7037                    if (targetPkg != null) {
7038                        intent.setPackage(targetPkg);
7039                    }
7040                    // Modify the UID when posting to other users
7041                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7042                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7043                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7044                        intent.putExtra(Intent.EXTRA_UID, uid);
7045                    }
7046                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7047                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7048                    if (DEBUG_BROADCASTS) {
7049                        RuntimeException here = new RuntimeException("here");
7050                        here.fillInStackTrace();
7051                        Slog.d(TAG, "Sending to user " + id + ": "
7052                                + intent.toShortString(false, true, false, false)
7053                                + " " + intent.getExtras(), here);
7054                    }
7055                    am.broadcastIntent(null, intent, null, finishedReceiver,
7056                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7057                            finishedReceiver != null, false, id);
7058                }
7059            } catch (RemoteException ex) {
7060            }
7061        }
7062    }
7063
7064    /**
7065     * Check if the external storage media is available. This is true if there
7066     * is a mounted external storage medium or if the external storage is
7067     * emulated.
7068     */
7069    private boolean isExternalMediaAvailable() {
7070        return mMediaMounted || Environment.isExternalStorageEmulated();
7071    }
7072
7073    @Override
7074    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7075        // writer
7076        synchronized (mPackages) {
7077            if (!isExternalMediaAvailable()) {
7078                // If the external storage is no longer mounted at this point,
7079                // the caller may not have been able to delete all of this
7080                // packages files and can not delete any more.  Bail.
7081                return null;
7082            }
7083            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7084            if (lastPackage != null) {
7085                pkgs.remove(lastPackage);
7086            }
7087            if (pkgs.size() > 0) {
7088                return pkgs.get(0);
7089            }
7090        }
7091        return null;
7092    }
7093
7094    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7095        if (false) {
7096            RuntimeException here = new RuntimeException("here");
7097            here.fillInStackTrace();
7098            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7099                    + " andCode=" + andCode, here);
7100        }
7101        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7102                userId, andCode ? 1 : 0, packageName));
7103    }
7104
7105    void startCleaningPackages() {
7106        // reader
7107        synchronized (mPackages) {
7108            if (!isExternalMediaAvailable()) {
7109                return;
7110            }
7111            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7112                return;
7113            }
7114        }
7115        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7116        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7117        IActivityManager am = ActivityManagerNative.getDefault();
7118        if (am != null) {
7119            try {
7120                am.startService(null, intent, null, UserHandle.USER_OWNER);
7121            } catch (RemoteException e) {
7122            }
7123        }
7124    }
7125
7126    private final class AppDirObserver extends FileObserver {
7127        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7128            super(path, mask);
7129            mRootDir = path;
7130            mIsRom = isrom;
7131            mIsPrivileged = isPrivileged;
7132        }
7133
7134        public void onEvent(int event, String path) {
7135            String removedPackage = null;
7136            int removedAppId = -1;
7137            int[] removedUsers = null;
7138            String addedPackage = null;
7139            int addedAppId = -1;
7140            int[] addedUsers = null;
7141
7142            // TODO post a message to the handler to obtain serial ordering
7143            synchronized (mInstallLock) {
7144                String fullPathStr = null;
7145                File fullPath = null;
7146                if (path != null) {
7147                    fullPath = new File(mRootDir, path);
7148                    fullPathStr = fullPath.getPath();
7149                }
7150
7151                if (DEBUG_APP_DIR_OBSERVER)
7152                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7153
7154                if (!isPackageFilename(path)) {
7155                    if (DEBUG_APP_DIR_OBSERVER)
7156                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7157                    return;
7158                }
7159
7160                // Ignore packages that are being installed or
7161                // have just been installed.
7162                if (ignoreCodePath(fullPathStr)) {
7163                    return;
7164                }
7165                PackageParser.Package p = null;
7166                PackageSetting ps = null;
7167                // reader
7168                synchronized (mPackages) {
7169                    p = mAppDirs.get(fullPathStr);
7170                    if (p != null) {
7171                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7172                        if (ps != null) {
7173                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7174                        } else {
7175                            removedUsers = sUserManager.getUserIds();
7176                        }
7177                    }
7178                    addedUsers = sUserManager.getUserIds();
7179                }
7180                if ((event&REMOVE_EVENTS) != 0) {
7181                    if (ps != null) {
7182                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7183                        removePackageLI(ps, true);
7184                        removedPackage = ps.name;
7185                        removedAppId = ps.appId;
7186                    }
7187                }
7188
7189                if ((event&ADD_EVENTS) != 0) {
7190                    if (p == null) {
7191                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7192                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7193                        if (mIsRom) {
7194                            flags |= PackageParser.PARSE_IS_SYSTEM
7195                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7196                            if (mIsPrivileged) {
7197                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7198                            }
7199                        }
7200                        p = scanPackageLI(fullPath, flags,
7201                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7202                                System.currentTimeMillis(), UserHandle.ALL, null);
7203                        if (p != null) {
7204                            /*
7205                             * TODO this seems dangerous as the package may have
7206                             * changed since we last acquired the mPackages
7207                             * lock.
7208                             */
7209                            // writer
7210                            synchronized (mPackages) {
7211                                updatePermissionsLPw(p.packageName, p,
7212                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7213                            }
7214                            addedPackage = p.applicationInfo.packageName;
7215                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7216                        }
7217                    }
7218                }
7219
7220                // reader
7221                synchronized (mPackages) {
7222                    mSettings.writeLPr();
7223                }
7224            }
7225
7226            if (removedPackage != null) {
7227                Bundle extras = new Bundle(1);
7228                extras.putInt(Intent.EXTRA_UID, removedAppId);
7229                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7230                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7231                        extras, null, null, removedUsers);
7232            }
7233            if (addedPackage != null) {
7234                Bundle extras = new Bundle(1);
7235                extras.putInt(Intent.EXTRA_UID, addedAppId);
7236                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7237                        extras, null, null, addedUsers);
7238            }
7239        }
7240
7241        private final String mRootDir;
7242        private final boolean mIsRom;
7243        private final boolean mIsPrivileged;
7244    }
7245
7246    /* Called when a downloaded package installation has been confirmed by the user */
7247    public void installPackage(
7248            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7249        installPackage(packageURI, observer, flags, null);
7250    }
7251
7252    /* Called when a downloaded package installation has been confirmed by the user */
7253    @Override
7254    public void installPackage(
7255            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7256            final String installerPackageName) {
7257        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
7258                null, null);
7259    }
7260
7261    @Override
7262    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7263            int flags, String installerPackageName, Uri verificationURI,
7264            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7265        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7266                VerificationParams.NO_UID, manifestDigest);
7267        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
7268                installerPackageName, verificationParams, encryptionParams);
7269    }
7270
7271    @Override
7272    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7273            IPackageInstallObserver observer, int flags, String installerPackageName,
7274            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7275        installPackageWithVerificationEncryptionAndAbiOverride(packageURI, observer, flags,
7276                installerPackageName, verificationParams, encryptionParams, null);
7277    }
7278
7279    @Override
7280    public void installPackageWithVerificationEncryptionAndAbiOverride(Uri packageURI,
7281            IPackageInstallObserver observer, int flags, String installerPackageName,
7282            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7283            String packageAbiOverride) {
7284        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7285                null);
7286
7287        final int uid = Binder.getCallingUid();
7288        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7289            try {
7290                observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7291            } catch (RemoteException re) {
7292            }
7293            return;
7294        }
7295
7296        UserHandle user;
7297        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7298            user = UserHandle.ALL;
7299        } else {
7300            user = new UserHandle(UserHandle.getUserId(uid));
7301        }
7302
7303        final int filteredFlags;
7304
7305        if (uid == Process.SHELL_UID || uid == 0) {
7306            if (DEBUG_INSTALL) {
7307                Slog.v(TAG, "Install from ADB");
7308            }
7309            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7310        } else {
7311            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7312        }
7313
7314        verificationParams.setInstallerUid(uid);
7315
7316        final Message msg = mHandler.obtainMessage(INIT_COPY);
7317        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
7318                verificationParams, encryptionParams, user,
7319                packageAbiOverride);
7320        mHandler.sendMessage(msg);
7321    }
7322
7323    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7324        Bundle extras = new Bundle(1);
7325        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7326
7327        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7328                packageName, extras, null, null, new int[] {userId});
7329        try {
7330            IActivityManager am = ActivityManagerNative.getDefault();
7331            final boolean isSystem =
7332                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7333            if (isSystem && am.isUserRunning(userId, false)) {
7334                // The just-installed/enabled app is bundled on the system, so presumed
7335                // to be able to run automatically without needing an explicit launch.
7336                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7337                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7338                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7339                        .setPackage(packageName);
7340                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7341                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7342            }
7343        } catch (RemoteException e) {
7344            // shouldn't happen
7345            Slog.w(TAG, "Unable to bootstrap installed package", e);
7346        }
7347    }
7348
7349    @Override
7350    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7351            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.enforceCallingOrSelfPermission(
7357                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7358                    "setApplicationBlockedSetting for user " + userId);
7359        }
7360
7361        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7362            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7363            return false;
7364        }
7365
7366        long callingId = Binder.clearCallingIdentity();
7367        try {
7368            boolean sendAdded = false;
7369            boolean sendRemoved = false;
7370            // writer
7371            synchronized (mPackages) {
7372                pkgSetting = mSettings.mPackages.get(packageName);
7373                if (pkgSetting == null) {
7374                    return false;
7375                }
7376                if (pkgSetting.getBlocked(userId) != blocked) {
7377                    pkgSetting.setBlocked(blocked, userId);
7378                    mSettings.writePackageRestrictionsLPr(userId);
7379                    if (blocked) {
7380                        sendRemoved = true;
7381                    } else {
7382                        sendAdded = true;
7383                    }
7384                }
7385            }
7386            if (sendAdded) {
7387                sendPackageAddedForUser(packageName, pkgSetting, userId);
7388                return true;
7389            }
7390            if (sendRemoved) {
7391                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7392                        "blocking pkg");
7393                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7394            }
7395        } finally {
7396            Binder.restoreCallingIdentity(callingId);
7397        }
7398        return false;
7399    }
7400
7401    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7402            int userId) {
7403        final PackageRemovedInfo info = new PackageRemovedInfo();
7404        info.removedPackage = packageName;
7405        info.removedUsers = new int[] {userId};
7406        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7407        info.sendBroadcast(false, false, false);
7408    }
7409
7410    /**
7411     * Returns true if application is not found or there was an error. Otherwise it returns
7412     * the blocked state of the package for the given user.
7413     */
7414    @Override
7415    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7416        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7417        PackageSetting pkgSetting;
7418        final int uid = Binder.getCallingUid();
7419        if (UserHandle.getUserId(uid) != userId) {
7420            mContext.enforceCallingPermission(
7421                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7422                    "getApplicationBlocked for user " + userId);
7423        }
7424        long callingId = Binder.clearCallingIdentity();
7425        try {
7426            // writer
7427            synchronized (mPackages) {
7428                pkgSetting = mSettings.mPackages.get(packageName);
7429                if (pkgSetting == null) {
7430                    return true;
7431                }
7432                return pkgSetting.getBlocked(userId);
7433            }
7434        } finally {
7435            Binder.restoreCallingIdentity(callingId);
7436        }
7437    }
7438
7439    /**
7440     * @hide
7441     */
7442    @Override
7443    public int installExistingPackageAsUser(String packageName, int userId) {
7444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7445                null);
7446        PackageSetting pkgSetting;
7447        final int uid = Binder.getCallingUid();
7448        if (UserHandle.getUserId(uid) != userId) {
7449            mContext.enforceCallingPermission(
7450                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7451                    "installExistingPackage for user " + userId);
7452        }
7453        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7454            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7455        }
7456
7457        long callingId = Binder.clearCallingIdentity();
7458        try {
7459            boolean sendAdded = false;
7460            Bundle extras = new Bundle(1);
7461
7462            // writer
7463            synchronized (mPackages) {
7464                pkgSetting = mSettings.mPackages.get(packageName);
7465                if (pkgSetting == null) {
7466                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7467                }
7468                if (!pkgSetting.getInstalled(userId)) {
7469                    pkgSetting.setInstalled(true, userId);
7470                    pkgSetting.setBlocked(false, userId);
7471                    mSettings.writePackageRestrictionsLPr(userId);
7472                    sendAdded = true;
7473                }
7474            }
7475
7476            if (sendAdded) {
7477                sendPackageAddedForUser(packageName, pkgSetting, userId);
7478            }
7479        } finally {
7480            Binder.restoreCallingIdentity(callingId);
7481        }
7482
7483        return PackageManager.INSTALL_SUCCEEDED;
7484    }
7485
7486    private boolean isUserRestricted(int userId, String restrictionKey) {
7487        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7488        if (restrictions.getBoolean(restrictionKey, false)) {
7489            Log.w(TAG, "User is restricted: " + restrictionKey);
7490            return true;
7491        }
7492        return false;
7493    }
7494
7495    @Override
7496    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7497        mContext.enforceCallingOrSelfPermission(
7498                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7499                "Only package verification agents can verify applications");
7500
7501        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7502        final PackageVerificationResponse response = new PackageVerificationResponse(
7503                verificationCode, Binder.getCallingUid());
7504        msg.arg1 = id;
7505        msg.obj = response;
7506        mHandler.sendMessage(msg);
7507    }
7508
7509    @Override
7510    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7511            long millisecondsToDelay) {
7512        mContext.enforceCallingOrSelfPermission(
7513                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7514                "Only package verification agents can extend verification timeouts");
7515
7516        final PackageVerificationState state = mPendingVerification.get(id);
7517        final PackageVerificationResponse response = new PackageVerificationResponse(
7518                verificationCodeAtTimeout, Binder.getCallingUid());
7519
7520        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7521            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7522        }
7523        if (millisecondsToDelay < 0) {
7524            millisecondsToDelay = 0;
7525        }
7526        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7527                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7528            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7529        }
7530
7531        if ((state != null) && !state.timeoutExtended()) {
7532            state.extendTimeout();
7533
7534            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7535            msg.arg1 = id;
7536            msg.obj = response;
7537            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7538        }
7539    }
7540
7541    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7542            int verificationCode, UserHandle user) {
7543        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7544        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7545        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7546        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7547        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7548
7549        mContext.sendBroadcastAsUser(intent, user,
7550                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7551    }
7552
7553    private ComponentName matchComponentForVerifier(String packageName,
7554            List<ResolveInfo> receivers) {
7555        ActivityInfo targetReceiver = null;
7556
7557        final int NR = receivers.size();
7558        for (int i = 0; i < NR; i++) {
7559            final ResolveInfo info = receivers.get(i);
7560            if (info.activityInfo == null) {
7561                continue;
7562            }
7563
7564            if (packageName.equals(info.activityInfo.packageName)) {
7565                targetReceiver = info.activityInfo;
7566                break;
7567            }
7568        }
7569
7570        if (targetReceiver == null) {
7571            return null;
7572        }
7573
7574        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7575    }
7576
7577    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7578            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7579        if (pkgInfo.verifiers.length == 0) {
7580            return null;
7581        }
7582
7583        final int N = pkgInfo.verifiers.length;
7584        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7585        for (int i = 0; i < N; i++) {
7586            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7587
7588            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7589                    receivers);
7590            if (comp == null) {
7591                continue;
7592            }
7593
7594            final int verifierUid = getUidForVerifier(verifierInfo);
7595            if (verifierUid == -1) {
7596                continue;
7597            }
7598
7599            if (DEBUG_VERIFY) {
7600                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7601                        + " with the correct signature");
7602            }
7603            sufficientVerifiers.add(comp);
7604            verificationState.addSufficientVerifier(verifierUid);
7605        }
7606
7607        return sufficientVerifiers;
7608    }
7609
7610    private int getUidForVerifier(VerifierInfo verifierInfo) {
7611        synchronized (mPackages) {
7612            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7613            if (pkg == null) {
7614                return -1;
7615            } else if (pkg.mSignatures.length != 1) {
7616                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7617                        + " has more than one signature; ignoring");
7618                return -1;
7619            }
7620
7621            /*
7622             * If the public key of the package's signature does not match
7623             * our expected public key, then this is a different package and
7624             * we should skip.
7625             */
7626
7627            final byte[] expectedPublicKey;
7628            try {
7629                final Signature verifierSig = pkg.mSignatures[0];
7630                final PublicKey publicKey = verifierSig.getPublicKey();
7631                expectedPublicKey = publicKey.getEncoded();
7632            } catch (CertificateException e) {
7633                return -1;
7634            }
7635
7636            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7637
7638            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7639                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7640                        + " does not have the expected public key; ignoring");
7641                return -1;
7642            }
7643
7644            return pkg.applicationInfo.uid;
7645        }
7646    }
7647
7648    @Override
7649    public void finishPackageInstall(int token) {
7650        enforceSystemOrRoot("Only the system is allowed to finish installs");
7651
7652        if (DEBUG_INSTALL) {
7653            Slog.v(TAG, "BM finishing package install for " + token);
7654        }
7655
7656        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7657        mHandler.sendMessage(msg);
7658    }
7659
7660    /**
7661     * Get the verification agent timeout.
7662     *
7663     * @return verification timeout in milliseconds
7664     */
7665    private long getVerificationTimeout() {
7666        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7667                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7668                DEFAULT_VERIFICATION_TIMEOUT);
7669    }
7670
7671    /**
7672     * Get the default verification agent response code.
7673     *
7674     * @return default verification response code
7675     */
7676    private int getDefaultVerificationResponse() {
7677        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7678                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7679                DEFAULT_VERIFICATION_RESPONSE);
7680    }
7681
7682    /**
7683     * Check whether or not package verification has been enabled.
7684     *
7685     * @return true if verification should be performed
7686     */
7687    private boolean isVerificationEnabled(int flags) {
7688        if (!DEFAULT_VERIFY_ENABLE) {
7689            return false;
7690        }
7691
7692        // Check if installing from ADB
7693        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7694            // Do not run verification in a test harness environment
7695            if (ActivityManager.isRunningInTestHarness()) {
7696                return false;
7697            }
7698            // Check if the developer does not want package verification for ADB installs
7699            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7700                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7701                return false;
7702            }
7703        }
7704
7705        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7706                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7707    }
7708
7709    /**
7710     * Get the "allow unknown sources" setting.
7711     *
7712     * @return the current "allow unknown sources" setting
7713     */
7714    private int getUnknownSourcesSettings() {
7715        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7716                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7717                -1);
7718    }
7719
7720    @Override
7721    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7722        final int uid = Binder.getCallingUid();
7723        // writer
7724        synchronized (mPackages) {
7725            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7726            if (targetPackageSetting == null) {
7727                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7728            }
7729
7730            PackageSetting installerPackageSetting;
7731            if (installerPackageName != null) {
7732                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7733                if (installerPackageSetting == null) {
7734                    throw new IllegalArgumentException("Unknown installer package: "
7735                            + installerPackageName);
7736                }
7737            } else {
7738                installerPackageSetting = null;
7739            }
7740
7741            Signature[] callerSignature;
7742            Object obj = mSettings.getUserIdLPr(uid);
7743            if (obj != null) {
7744                if (obj instanceof SharedUserSetting) {
7745                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7746                } else if (obj instanceof PackageSetting) {
7747                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7748                } else {
7749                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7750                }
7751            } else {
7752                throw new SecurityException("Unknown calling uid " + uid);
7753            }
7754
7755            // Verify: can't set installerPackageName to a package that is
7756            // not signed with the same cert as the caller.
7757            if (installerPackageSetting != null) {
7758                if (compareSignatures(callerSignature,
7759                        installerPackageSetting.signatures.mSignatures)
7760                        != PackageManager.SIGNATURE_MATCH) {
7761                    throw new SecurityException(
7762                            "Caller does not have same cert as new installer package "
7763                            + installerPackageName);
7764                }
7765            }
7766
7767            // Verify: if target already has an installer package, it must
7768            // be signed with the same cert as the caller.
7769            if (targetPackageSetting.installerPackageName != null) {
7770                PackageSetting setting = mSettings.mPackages.get(
7771                        targetPackageSetting.installerPackageName);
7772                // If the currently set package isn't valid, then it's always
7773                // okay to change it.
7774                if (setting != null) {
7775                    if (compareSignatures(callerSignature,
7776                            setting.signatures.mSignatures)
7777                            != PackageManager.SIGNATURE_MATCH) {
7778                        throw new SecurityException(
7779                                "Caller does not have same cert as old installer package "
7780                                + targetPackageSetting.installerPackageName);
7781                    }
7782                }
7783            }
7784
7785            // Okay!
7786            targetPackageSetting.installerPackageName = installerPackageName;
7787            scheduleWriteSettingsLocked();
7788        }
7789    }
7790
7791    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7792        // Queue up an async operation since the package installation may take a little while.
7793        mHandler.post(new Runnable() {
7794            public void run() {
7795                mHandler.removeCallbacks(this);
7796                 // Result object to be returned
7797                PackageInstalledInfo res = new PackageInstalledInfo();
7798                res.returnCode = currentStatus;
7799                res.uid = -1;
7800                res.pkg = null;
7801                res.removedInfo = new PackageRemovedInfo();
7802                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7803                    args.doPreInstall(res.returnCode);
7804                    synchronized (mInstallLock) {
7805                        installPackageLI(args, true, res);
7806                    }
7807                    args.doPostInstall(res.returnCode, res.uid);
7808                }
7809
7810                // A restore should be performed at this point if (a) the install
7811                // succeeded, (b) the operation is not an update, and (c) the new
7812                // package has a backupAgent defined.
7813                final boolean update = res.removedInfo.removedPackage != null;
7814                boolean doRestore = (!update
7815                        && res.pkg != null
7816                        && res.pkg.applicationInfo.backupAgentName != null);
7817
7818                // Set up the post-install work request bookkeeping.  This will be used
7819                // and cleaned up by the post-install event handling regardless of whether
7820                // there's a restore pass performed.  Token values are >= 1.
7821                int token;
7822                if (mNextInstallToken < 0) mNextInstallToken = 1;
7823                token = mNextInstallToken++;
7824
7825                PostInstallData data = new PostInstallData(args, res);
7826                mRunningInstalls.put(token, data);
7827                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7828
7829                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7830                    // Pass responsibility to the Backup Manager.  It will perform a
7831                    // restore if appropriate, then pass responsibility back to the
7832                    // Package Manager to run the post-install observer callbacks
7833                    // and broadcasts.
7834                    IBackupManager bm = IBackupManager.Stub.asInterface(
7835                            ServiceManager.getService(Context.BACKUP_SERVICE));
7836                    if (bm != null) {
7837                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7838                                + " to BM for possible restore");
7839                        try {
7840                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7841                        } catch (RemoteException e) {
7842                            // can't happen; the backup manager is local
7843                        } catch (Exception e) {
7844                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7845                            doRestore = false;
7846                        }
7847                    } else {
7848                        Slog.e(TAG, "Backup Manager not found!");
7849                        doRestore = false;
7850                    }
7851                }
7852
7853                if (!doRestore) {
7854                    // No restore possible, or the Backup Manager was mysteriously not
7855                    // available -- just fire the post-install work request directly.
7856                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7857                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7858                    mHandler.sendMessage(msg);
7859                }
7860            }
7861        });
7862    }
7863
7864    private abstract class HandlerParams {
7865        private static final int MAX_RETRIES = 4;
7866
7867        /**
7868         * Number of times startCopy() has been attempted and had a non-fatal
7869         * error.
7870         */
7871        private int mRetries = 0;
7872
7873        /** User handle for the user requesting the information or installation. */
7874        private final UserHandle mUser;
7875
7876        HandlerParams(UserHandle user) {
7877            mUser = user;
7878        }
7879
7880        UserHandle getUser() {
7881            return mUser;
7882        }
7883
7884        final boolean startCopy() {
7885            boolean res;
7886            try {
7887                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7888
7889                if (++mRetries > MAX_RETRIES) {
7890                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7891                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7892                    handleServiceError();
7893                    return false;
7894                } else {
7895                    handleStartCopy();
7896                    res = true;
7897                }
7898            } catch (RemoteException e) {
7899                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7900                mHandler.sendEmptyMessage(MCS_RECONNECT);
7901                res = false;
7902            }
7903            handleReturnCode();
7904            return res;
7905        }
7906
7907        final void serviceError() {
7908            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7909            handleServiceError();
7910            handleReturnCode();
7911        }
7912
7913        abstract void handleStartCopy() throws RemoteException;
7914        abstract void handleServiceError();
7915        abstract void handleReturnCode();
7916    }
7917
7918    class MeasureParams extends HandlerParams {
7919        private final PackageStats mStats;
7920        private boolean mSuccess;
7921
7922        private final IPackageStatsObserver mObserver;
7923
7924        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7925            super(new UserHandle(stats.userHandle));
7926            mObserver = observer;
7927            mStats = stats;
7928        }
7929
7930        @Override
7931        public String toString() {
7932            return "MeasureParams{"
7933                + Integer.toHexString(System.identityHashCode(this))
7934                + " " + mStats.packageName + "}";
7935        }
7936
7937        @Override
7938        void handleStartCopy() throws RemoteException {
7939            synchronized (mInstallLock) {
7940                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7941            }
7942
7943            final boolean mounted;
7944            if (Environment.isExternalStorageEmulated()) {
7945                mounted = true;
7946            } else {
7947                final String status = Environment.getExternalStorageState();
7948                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7949                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7950            }
7951
7952            if (mounted) {
7953                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7954
7955                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7956                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7957
7958                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7959                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7960
7961                // Always subtract cache size, since it's a subdirectory
7962                mStats.externalDataSize -= mStats.externalCacheSize;
7963
7964                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7965                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7966
7967                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7968                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7969            }
7970        }
7971
7972        @Override
7973        void handleReturnCode() {
7974            if (mObserver != null) {
7975                try {
7976                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7977                } catch (RemoteException e) {
7978                    Slog.i(TAG, "Observer no longer exists.");
7979                }
7980            }
7981        }
7982
7983        @Override
7984        void handleServiceError() {
7985            Slog.e(TAG, "Could not measure application " + mStats.packageName
7986                            + " external storage");
7987        }
7988    }
7989
7990    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7991            throws RemoteException {
7992        long result = 0;
7993        for (File path : paths) {
7994            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7995        }
7996        return result;
7997    }
7998
7999    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8000        for (File path : paths) {
8001            try {
8002                mcs.clearDirectory(path.getAbsolutePath());
8003            } catch (RemoteException e) {
8004            }
8005        }
8006    }
8007
8008    class InstallParams extends HandlerParams {
8009        final IPackageInstallObserver observer;
8010        int flags;
8011
8012        private final Uri mPackageURI;
8013        final String installerPackageName;
8014        final VerificationParams verificationParams;
8015        private InstallArgs mArgs;
8016        private int mRet;
8017        private File mTempPackage;
8018        final ContainerEncryptionParams encryptionParams;
8019        final String packageAbiOverride;
8020        final String packageInstructionSetOverride;
8021
8022        InstallParams(Uri packageURI,
8023                IPackageInstallObserver observer, int flags,
8024                String installerPackageName, VerificationParams verificationParams,
8025                ContainerEncryptionParams encryptionParams, UserHandle user,
8026                String packageAbiOverride) {
8027            super(user);
8028            this.mPackageURI = packageURI;
8029            this.flags = flags;
8030            this.observer = observer;
8031            this.installerPackageName = installerPackageName;
8032            this.verificationParams = verificationParams;
8033            this.encryptionParams = encryptionParams;
8034            this.packageAbiOverride = packageAbiOverride;
8035            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8036                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8037        }
8038
8039        @Override
8040        public String toString() {
8041            return "InstallParams{"
8042                + Integer.toHexString(System.identityHashCode(this))
8043                + " " + mPackageURI + "}";
8044        }
8045
8046        public ManifestDigest getManifestDigest() {
8047            if (verificationParams == null) {
8048                return null;
8049            }
8050            return verificationParams.getManifestDigest();
8051        }
8052
8053        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8054            String packageName = pkgLite.packageName;
8055            int installLocation = pkgLite.installLocation;
8056            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8057            // reader
8058            synchronized (mPackages) {
8059                PackageParser.Package pkg = mPackages.get(packageName);
8060                if (pkg != null) {
8061                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8062                        // Check for downgrading.
8063                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8064                            if (pkgLite.versionCode < pkg.mVersionCode) {
8065                                Slog.w(TAG, "Can't install update of " + packageName
8066                                        + " update version " + pkgLite.versionCode
8067                                        + " is older than installed version "
8068                                        + pkg.mVersionCode);
8069                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8070                            }
8071                        }
8072                        // Check for updated system application.
8073                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8074                            if (onSd) {
8075                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8076                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8077                            }
8078                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8079                        } else {
8080                            if (onSd) {
8081                                // Install flag overrides everything.
8082                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8083                            }
8084                            // If current upgrade specifies particular preference
8085                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8086                                // Application explicitly specified internal.
8087                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8088                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8089                                // App explictly prefers external. Let policy decide
8090                            } else {
8091                                // Prefer previous location
8092                                if (isExternal(pkg)) {
8093                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8094                                }
8095                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8096                            }
8097                        }
8098                    } else {
8099                        // Invalid install. Return error code
8100                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8101                    }
8102                }
8103            }
8104            // All the special cases have been taken care of.
8105            // Return result based on recommended install location.
8106            if (onSd) {
8107                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8108            }
8109            return pkgLite.recommendedInstallLocation;
8110        }
8111
8112        private long getMemoryLowThreshold() {
8113            final DeviceStorageMonitorInternal
8114                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8115            if (dsm == null) {
8116                return 0L;
8117            }
8118            return dsm.getMemoryLowThreshold();
8119        }
8120
8121        /*
8122         * Invoke remote method to get package information and install
8123         * location values. Override install location based on default
8124         * policy if needed and then create install arguments based
8125         * on the install location.
8126         */
8127        public void handleStartCopy() throws RemoteException {
8128            int ret = PackageManager.INSTALL_SUCCEEDED;
8129            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8130            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8131            PackageInfoLite pkgLite = null;
8132
8133            if (onInt && onSd) {
8134                // Check if both bits are set.
8135                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8136                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8137            } else {
8138                final long lowThreshold = getMemoryLowThreshold();
8139                if (lowThreshold == 0L) {
8140                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8141                }
8142
8143                try {
8144                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8145                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8146
8147                    final File packageFile;
8148                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8149                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8150                        if (mTempPackage != null) {
8151                            ParcelFileDescriptor out;
8152                            try {
8153                                out = ParcelFileDescriptor.open(mTempPackage,
8154                                        ParcelFileDescriptor.MODE_READ_WRITE);
8155                            } catch (FileNotFoundException e) {
8156                                out = null;
8157                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8158                            }
8159
8160                            // Make a temporary file for decryption.
8161                            ret = mContainerService
8162                                    .copyResource(mPackageURI, encryptionParams, out);
8163                            IoUtils.closeQuietly(out);
8164
8165                            packageFile = mTempPackage;
8166
8167                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8168                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8169                                            | FileUtils.S_IROTH,
8170                                    -1, -1);
8171                        } else {
8172                            packageFile = null;
8173                        }
8174                    } else {
8175                        packageFile = new File(mPackageURI.getPath());
8176                    }
8177
8178                    if (packageFile != null) {
8179                        // Remote call to find out default install location
8180                        final String packageFilePath = packageFile.getAbsolutePath();
8181                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8182                                lowThreshold, packageAbiOverride);
8183
8184                        /*
8185                         * If we have too little free space, try to free cache
8186                         * before giving up.
8187                         */
8188                        if (pkgLite.recommendedInstallLocation
8189                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8190                            final long size = mContainerService.calculateInstalledSize(
8191                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8192                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8193                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8194                                        flags, lowThreshold, packageAbiOverride);
8195                            }
8196                            /*
8197                             * The cache free must have deleted the file we
8198                             * downloaded to install.
8199                             *
8200                             * TODO: fix the "freeCache" call to not delete
8201                             *       the file we care about.
8202                             */
8203                            if (pkgLite.recommendedInstallLocation
8204                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8205                                pkgLite.recommendedInstallLocation
8206                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8207                            }
8208                        }
8209                    }
8210                } finally {
8211                    mContext.revokeUriPermission(mPackageURI,
8212                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8213                }
8214            }
8215
8216            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8217                int loc = pkgLite.recommendedInstallLocation;
8218                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8219                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8220                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8221                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8222                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8223                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8224                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8225                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8226                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8227                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8228                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8229                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8230                } else {
8231                    // Override with defaults if needed.
8232                    loc = installLocationPolicy(pkgLite, flags);
8233                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8234                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8235                    } else if (!onSd && !onInt) {
8236                        // Override install location with flags
8237                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8238                            // Set the flag to install on external media.
8239                            flags |= PackageManager.INSTALL_EXTERNAL;
8240                            flags &= ~PackageManager.INSTALL_INTERNAL;
8241                        } else {
8242                            // Make sure the flag for installing on external
8243                            // media is unset
8244                            flags |= PackageManager.INSTALL_INTERNAL;
8245                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8246                        }
8247                    }
8248                }
8249            }
8250
8251            final InstallArgs args = createInstallArgs(this);
8252            mArgs = args;
8253
8254            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8255                 /*
8256                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8257                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8258                 */
8259                int userIdentifier = getUser().getIdentifier();
8260                if (userIdentifier == UserHandle.USER_ALL
8261                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8262                    userIdentifier = UserHandle.USER_OWNER;
8263                }
8264
8265                /*
8266                 * Determine if we have any installed package verifiers. If we
8267                 * do, then we'll defer to them to verify the packages.
8268                 */
8269                final int requiredUid = mRequiredVerifierPackage == null ? -1
8270                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8271                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8272                    final Intent verification = new Intent(
8273                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8274                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8275                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8276
8277                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8278                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8279                            0 /* TODO: Which userId? */);
8280
8281                    if (DEBUG_VERIFY) {
8282                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8283                                + verification.toString() + " with " + pkgLite.verifiers.length
8284                                + " optional verifiers");
8285                    }
8286
8287                    final int verificationId = mPendingVerificationToken++;
8288
8289                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8290
8291                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8292                            installerPackageName);
8293
8294                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8295
8296                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8297                            pkgLite.packageName);
8298
8299                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8300                            pkgLite.versionCode);
8301
8302                    if (verificationParams != null) {
8303                        if (verificationParams.getVerificationURI() != null) {
8304                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8305                                 verificationParams.getVerificationURI());
8306                        }
8307                        if (verificationParams.getOriginatingURI() != null) {
8308                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8309                                  verificationParams.getOriginatingURI());
8310                        }
8311                        if (verificationParams.getReferrer() != null) {
8312                            verification.putExtra(Intent.EXTRA_REFERRER,
8313                                  verificationParams.getReferrer());
8314                        }
8315                        if (verificationParams.getOriginatingUid() >= 0) {
8316                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8317                                  verificationParams.getOriginatingUid());
8318                        }
8319                        if (verificationParams.getInstallerUid() >= 0) {
8320                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8321                                  verificationParams.getInstallerUid());
8322                        }
8323                    }
8324
8325                    final PackageVerificationState verificationState = new PackageVerificationState(
8326                            requiredUid, args);
8327
8328                    mPendingVerification.append(verificationId, verificationState);
8329
8330                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8331                            receivers, verificationState);
8332
8333                    /*
8334                     * If any sufficient verifiers were listed in the package
8335                     * manifest, attempt to ask them.
8336                     */
8337                    if (sufficientVerifiers != null) {
8338                        final int N = sufficientVerifiers.size();
8339                        if (N == 0) {
8340                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8341                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8342                        } else {
8343                            for (int i = 0; i < N; i++) {
8344                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8345
8346                                final Intent sufficientIntent = new Intent(verification);
8347                                sufficientIntent.setComponent(verifierComponent);
8348
8349                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8350                            }
8351                        }
8352                    }
8353
8354                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8355                            mRequiredVerifierPackage, receivers);
8356                    if (ret == PackageManager.INSTALL_SUCCEEDED
8357                            && mRequiredVerifierPackage != null) {
8358                        /*
8359                         * Send the intent to the required verification agent,
8360                         * but only start the verification timeout after the
8361                         * target BroadcastReceivers have run.
8362                         */
8363                        verification.setComponent(requiredVerifierComponent);
8364                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8365                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8366                                new BroadcastReceiver() {
8367                                    @Override
8368                                    public void onReceive(Context context, Intent intent) {
8369                                        final Message msg = mHandler
8370                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8371                                        msg.arg1 = verificationId;
8372                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8373                                    }
8374                                }, null, 0, null, null);
8375
8376                        /*
8377                         * We don't want the copy to proceed until verification
8378                         * succeeds, so null out this field.
8379                         */
8380                        mArgs = null;
8381                    }
8382                } else {
8383                    /*
8384                     * No package verification is enabled, so immediately start
8385                     * the remote call to initiate copy using temporary file.
8386                     */
8387                    ret = args.copyApk(mContainerService, true);
8388                }
8389            }
8390
8391            mRet = ret;
8392        }
8393
8394        @Override
8395        void handleReturnCode() {
8396            // If mArgs is null, then MCS couldn't be reached. When it
8397            // reconnects, it will try again to install. At that point, this
8398            // will succeed.
8399            if (mArgs != null) {
8400                processPendingInstall(mArgs, mRet);
8401
8402                if (mTempPackage != null) {
8403                    if (!mTempPackage.delete()) {
8404                        Slog.w(TAG, "Couldn't delete temporary file: " +
8405                                mTempPackage.getAbsolutePath());
8406                    }
8407                }
8408            }
8409        }
8410
8411        @Override
8412        void handleServiceError() {
8413            mArgs = createInstallArgs(this);
8414            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8415        }
8416
8417        public boolean isForwardLocked() {
8418            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8419        }
8420
8421        public Uri getPackageUri() {
8422            if (mTempPackage != null) {
8423                return Uri.fromFile(mTempPackage);
8424            } else {
8425                return mPackageURI;
8426            }
8427        }
8428    }
8429
8430    /*
8431     * Utility class used in movePackage api.
8432     * srcArgs and targetArgs are not set for invalid flags and make
8433     * sure to do null checks when invoking methods on them.
8434     * We probably want to return ErrorPrams for both failed installs
8435     * and moves.
8436     */
8437    class MoveParams extends HandlerParams {
8438        final IPackageMoveObserver observer;
8439        final int flags;
8440        final String packageName;
8441        final InstallArgs srcArgs;
8442        final InstallArgs targetArgs;
8443        int uid;
8444        int mRet;
8445
8446        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8447                String packageName, String dataDir, String instructionSet,
8448                int uid, UserHandle user) {
8449            super(user);
8450            this.srcArgs = srcArgs;
8451            this.observer = observer;
8452            this.flags = flags;
8453            this.packageName = packageName;
8454            this.uid = uid;
8455            if (srcArgs != null) {
8456                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8457                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8458            } else {
8459                targetArgs = null;
8460            }
8461        }
8462
8463        @Override
8464        public String toString() {
8465            return "MoveParams{"
8466                + Integer.toHexString(System.identityHashCode(this))
8467                + " " + packageName + "}";
8468        }
8469
8470        public void handleStartCopy() throws RemoteException {
8471            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8472            // Check for storage space on target medium
8473            if (!targetArgs.checkFreeStorage(mContainerService)) {
8474                Log.w(TAG, "Insufficient storage to install");
8475                return;
8476            }
8477
8478            mRet = srcArgs.doPreCopy();
8479            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8480                return;
8481            }
8482
8483            mRet = targetArgs.copyApk(mContainerService, false);
8484            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8485                srcArgs.doPostCopy(uid);
8486                return;
8487            }
8488
8489            mRet = srcArgs.doPostCopy(uid);
8490            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8491                return;
8492            }
8493
8494            mRet = targetArgs.doPreInstall(mRet);
8495            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8496                return;
8497            }
8498
8499            if (DEBUG_SD_INSTALL) {
8500                StringBuilder builder = new StringBuilder();
8501                if (srcArgs != null) {
8502                    builder.append("src: ");
8503                    builder.append(srcArgs.getCodePath());
8504                }
8505                if (targetArgs != null) {
8506                    builder.append(" target : ");
8507                    builder.append(targetArgs.getCodePath());
8508                }
8509                Log.i(TAG, builder.toString());
8510            }
8511        }
8512
8513        @Override
8514        void handleReturnCode() {
8515            targetArgs.doPostInstall(mRet, uid);
8516            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8517            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8518                currentStatus = PackageManager.MOVE_SUCCEEDED;
8519            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8520                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8521            }
8522            processPendingMove(this, currentStatus);
8523        }
8524
8525        @Override
8526        void handleServiceError() {
8527            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8528        }
8529    }
8530
8531    /**
8532     * Used during creation of InstallArgs
8533     *
8534     * @param flags package installation flags
8535     * @return true if should be installed on external storage
8536     */
8537    private static boolean installOnSd(int flags) {
8538        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8539            return false;
8540        }
8541        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8542            return true;
8543        }
8544        return false;
8545    }
8546
8547    /**
8548     * Used during creation of InstallArgs
8549     *
8550     * @param flags package installation flags
8551     * @return true if should be installed as forward locked
8552     */
8553    private static boolean installForwardLocked(int flags) {
8554        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8555    }
8556
8557    private InstallArgs createInstallArgs(InstallParams params) {
8558        if (installOnSd(params.flags) || params.isForwardLocked()) {
8559            return new AsecInstallArgs(params);
8560        } else {
8561            return new FileInstallArgs(params);
8562        }
8563    }
8564
8565    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8566            String nativeLibraryPath, String instructionSet) {
8567        final boolean isInAsec;
8568        if (installOnSd(flags)) {
8569            /* Apps on SD card are always in ASEC containers. */
8570            isInAsec = true;
8571        } else if (installForwardLocked(flags)
8572                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8573            /*
8574             * Forward-locked apps are only in ASEC containers if they're the
8575             * new style
8576             */
8577            isInAsec = true;
8578        } else {
8579            isInAsec = false;
8580        }
8581
8582        if (isInAsec) {
8583            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8584                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8585        } else {
8586            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8587                    instructionSet);
8588        }
8589    }
8590
8591    // Used by package mover
8592    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8593            String instructionSet) {
8594        if (installOnSd(flags) || installForwardLocked(flags)) {
8595            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8596                    + AsecInstallArgs.RES_FILE_NAME);
8597            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8598                    installForwardLocked(flags));
8599        } else {
8600            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8601        }
8602    }
8603
8604    static abstract class InstallArgs {
8605        final IPackageInstallObserver observer;
8606        // Always refers to PackageManager flags only
8607        final int flags;
8608        final Uri packageURI;
8609        final String installerPackageName;
8610        final ManifestDigest manifestDigest;
8611        final UserHandle user;
8612        final String instructionSet;
8613        final String abiOverride;
8614
8615        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
8616                String installerPackageName, ManifestDigest manifestDigest,
8617                UserHandle user, String instructionSet, String abiOverride) {
8618            this.packageURI = packageURI;
8619            this.flags = flags;
8620            this.observer = observer;
8621            this.installerPackageName = installerPackageName;
8622            this.manifestDigest = manifestDigest;
8623            this.user = user;
8624            this.instructionSet = instructionSet;
8625            this.abiOverride = abiOverride;
8626        }
8627
8628        abstract void createCopyFile();
8629        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8630        abstract int doPreInstall(int status);
8631        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8632
8633        abstract int doPostInstall(int status, int uid);
8634        abstract String getCodePath();
8635        abstract String getResourcePath();
8636        abstract String getNativeLibraryPath();
8637        // Need installer lock especially for dex file removal.
8638        abstract void cleanUpResourcesLI();
8639        abstract boolean doPostDeleteLI(boolean delete);
8640        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8641
8642        /**
8643         * Called before the source arguments are copied. This is used mostly
8644         * for MoveParams when it needs to read the source file to put it in the
8645         * destination.
8646         */
8647        int doPreCopy() {
8648            return PackageManager.INSTALL_SUCCEEDED;
8649        }
8650
8651        /**
8652         * Called after the source arguments are copied. This is used mostly for
8653         * MoveParams when it needs to read the source file to put it in the
8654         * destination.
8655         *
8656         * @return
8657         */
8658        int doPostCopy(int uid) {
8659            return PackageManager.INSTALL_SUCCEEDED;
8660        }
8661
8662        protected boolean isFwdLocked() {
8663            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8664        }
8665
8666        UserHandle getUser() {
8667            return user;
8668        }
8669    }
8670
8671    class FileInstallArgs extends InstallArgs {
8672        File installDir;
8673        String codeFileName;
8674        String resourceFileName;
8675        String libraryPath;
8676        boolean created = false;
8677
8678        FileInstallArgs(InstallParams params) {
8679            super(params.getPackageUri(), params.observer, params.flags,
8680                    params.installerPackageName, params.getManifestDigest(),
8681                    params.getUser(), params.packageInstructionSetOverride,
8682                    params.packageAbiOverride);
8683        }
8684
8685        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8686                String instructionSet) {
8687            super(null, null, 0, null, null, null, instructionSet, null);
8688            File codeFile = new File(fullCodePath);
8689            installDir = codeFile.getParentFile();
8690            codeFileName = fullCodePath;
8691            resourceFileName = fullResourcePath;
8692            libraryPath = nativeLibraryPath;
8693        }
8694
8695        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8696            super(packageURI, null, 0, null, null, null, instructionSet, null);
8697            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8698            String apkName = getNextCodePath(null, pkgName, ".apk");
8699            codeFileName = new File(installDir, apkName + ".apk").getPath();
8700            resourceFileName = getResourcePathFromCodePath();
8701            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8702        }
8703
8704        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8705            final long lowThreshold;
8706
8707            final DeviceStorageMonitorInternal
8708                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8709            if (dsm == null) {
8710                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8711                lowThreshold = 0L;
8712            } else {
8713                if (dsm.isMemoryLow()) {
8714                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8715                    return false;
8716                }
8717
8718                lowThreshold = dsm.getMemoryLowThreshold();
8719            }
8720
8721            try {
8722                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8723                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8724                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8725            } finally {
8726                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8727            }
8728        }
8729
8730        String getCodePath() {
8731            return codeFileName;
8732        }
8733
8734        void createCopyFile() {
8735            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8736            codeFileName = createTempPackageFile(installDir).getPath();
8737            resourceFileName = getResourcePathFromCodePath();
8738            libraryPath = getLibraryPathFromCodePath();
8739            created = true;
8740        }
8741
8742        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8743            if (temp) {
8744                // Generate temp file name
8745                createCopyFile();
8746            }
8747            // Get a ParcelFileDescriptor to write to the output file
8748            File codeFile = new File(codeFileName);
8749            if (!created) {
8750                try {
8751                    codeFile.createNewFile();
8752                    // Set permissions
8753                    if (!setPermissions()) {
8754                        // Failed setting permissions.
8755                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8756                    }
8757                } catch (IOException e) {
8758                   Slog.w(TAG, "Failed to create file " + codeFile);
8759                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8760                }
8761            }
8762            ParcelFileDescriptor out = null;
8763            try {
8764                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8765            } catch (FileNotFoundException e) {
8766                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8767                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8768            }
8769            // Copy the resource now
8770            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8771            try {
8772                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8773                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8774                ret = imcs.copyResource(packageURI, null, out);
8775            } finally {
8776                IoUtils.closeQuietly(out);
8777                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8778            }
8779
8780            if (isFwdLocked()) {
8781                final File destResourceFile = new File(getResourcePath());
8782
8783                // Copy the public files
8784                try {
8785                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8786                } catch (IOException e) {
8787                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8788                            + " forward-locked app.");
8789                    destResourceFile.delete();
8790                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8791                }
8792            }
8793
8794            final File nativeLibraryFile = new File(getNativeLibraryPath());
8795            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8796            if (nativeLibraryFile.exists()) {
8797                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8798                nativeLibraryFile.delete();
8799            }
8800
8801            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
8802            String[] abiList = (abiOverride != null) ?
8803                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
8804            try {
8805                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
8806                        abiOverride == null &&
8807                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8808                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8809                }
8810
8811                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
8812                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8813                    return copyRet;
8814                }
8815            } catch (IOException e) {
8816                Slog.e(TAG, "Copying native libraries failed", e);
8817                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8818            } finally {
8819                handle.close();
8820            }
8821
8822            return ret;
8823        }
8824
8825        int doPreInstall(int status) {
8826            if (status != PackageManager.INSTALL_SUCCEEDED) {
8827                cleanUp();
8828            }
8829            return status;
8830        }
8831
8832        boolean doRename(int status, final String pkgName, String oldCodePath) {
8833            if (status != PackageManager.INSTALL_SUCCEEDED) {
8834                cleanUp();
8835                return false;
8836            } else {
8837                final File oldCodeFile = new File(getCodePath());
8838                final File oldResourceFile = new File(getResourcePath());
8839                final File oldLibraryFile = new File(getNativeLibraryPath());
8840
8841                // Rename APK file based on packageName
8842                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8843                final File newCodeFile = new File(installDir, apkName + ".apk");
8844                if (!oldCodeFile.renameTo(newCodeFile)) {
8845                    return false;
8846                }
8847                codeFileName = newCodeFile.getPath();
8848
8849                // Rename public resource file if it's forward-locked.
8850                final File newResFile = new File(getResourcePathFromCodePath());
8851                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8852                    return false;
8853                }
8854                resourceFileName = newResFile.getPath();
8855
8856                // Rename library path
8857                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8858                if (newLibraryFile.exists()) {
8859                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8860                    newLibraryFile.delete();
8861                }
8862                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8863                    Slog.e(TAG, "Cannot rename native library directory "
8864                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8865                    return false;
8866                }
8867                libraryPath = newLibraryFile.getPath();
8868
8869                // Attempt to set permissions
8870                if (!setPermissions()) {
8871                    return false;
8872                }
8873
8874                if (!SELinux.restorecon(newCodeFile)) {
8875                    return false;
8876                }
8877
8878                return true;
8879            }
8880        }
8881
8882        int doPostInstall(int status, int uid) {
8883            if (status != PackageManager.INSTALL_SUCCEEDED) {
8884                cleanUp();
8885            }
8886            return status;
8887        }
8888
8889        String getResourcePath() {
8890            return resourceFileName;
8891        }
8892
8893        private String getResourcePathFromCodePath() {
8894            final String codePath = getCodePath();
8895            if (isFwdLocked()) {
8896                final StringBuilder sb = new StringBuilder();
8897
8898                sb.append(mAppInstallDir.getPath());
8899                sb.append('/');
8900                sb.append(getApkName(codePath));
8901                sb.append(".zip");
8902
8903                /*
8904                 * If our APK is a temporary file, mark the resource as a
8905                 * temporary file as well so it can be cleaned up after
8906                 * catastrophic failure.
8907                 */
8908                if (codePath.endsWith(".tmp")) {
8909                    sb.append(".tmp");
8910                }
8911
8912                return sb.toString();
8913            } else {
8914                return codePath;
8915            }
8916        }
8917
8918        private String getLibraryPathFromCodePath() {
8919            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8920        }
8921
8922        @Override
8923        String getNativeLibraryPath() {
8924            if (libraryPath == null) {
8925                libraryPath = getLibraryPathFromCodePath();
8926            }
8927            return libraryPath;
8928        }
8929
8930        private boolean cleanUp() {
8931            boolean ret = true;
8932            String sourceDir = getCodePath();
8933            String publicSourceDir = getResourcePath();
8934            if (sourceDir != null) {
8935                File sourceFile = new File(sourceDir);
8936                if (!sourceFile.exists()) {
8937                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8938                    ret = false;
8939                }
8940                // Delete application's code and resources
8941                sourceFile.delete();
8942            }
8943            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8944                final File publicSourceFile = new File(publicSourceDir);
8945                if (!publicSourceFile.exists()) {
8946                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8947                }
8948                if (publicSourceFile.exists()) {
8949                    publicSourceFile.delete();
8950                }
8951            }
8952
8953            if (libraryPath != null) {
8954                File nativeLibraryFile = new File(libraryPath);
8955                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8956                if (!nativeLibraryFile.delete()) {
8957                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8958                }
8959            }
8960
8961            return ret;
8962        }
8963
8964        void cleanUpResourcesLI() {
8965            String sourceDir = getCodePath();
8966            if (cleanUp()) {
8967                if (instructionSet == null) {
8968                    throw new IllegalStateException("instructionSet == null");
8969                }
8970                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
8971                if (retCode < 0) {
8972                    Slog.w(TAG, "Couldn't remove dex file for package: "
8973                            +  " at location "
8974                            + sourceDir + ", retcode=" + retCode);
8975                    // we don't consider this to be a failure of the core package deletion
8976                }
8977            }
8978        }
8979
8980        private boolean setPermissions() {
8981            // TODO Do this in a more elegant way later on. for now just a hack
8982            if (!isFwdLocked()) {
8983                final int filePermissions =
8984                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8985                    |FileUtils.S_IROTH;
8986                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8987                if (retCode != 0) {
8988                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8989                            getCodePath()
8990                            + ". The return code was: " + retCode);
8991                    // TODO Define new internal error
8992                    return false;
8993                }
8994                return true;
8995            }
8996            return true;
8997        }
8998
8999        boolean doPostDeleteLI(boolean delete) {
9000            // XXX err, shouldn't we respect the delete flag?
9001            cleanUpResourcesLI();
9002            return true;
9003        }
9004    }
9005
9006    private boolean isAsecExternal(String cid) {
9007        final String asecPath = PackageHelper.getSdFilesystem(cid);
9008        return !asecPath.startsWith(mAsecInternalPath);
9009    }
9010
9011    /**
9012     * Extract the MountService "container ID" from the full code path of an
9013     * .apk.
9014     */
9015    static String cidFromCodePath(String fullCodePath) {
9016        int eidx = fullCodePath.lastIndexOf("/");
9017        String subStr1 = fullCodePath.substring(0, eidx);
9018        int sidx = subStr1.lastIndexOf("/");
9019        return subStr1.substring(sidx+1, eidx);
9020    }
9021
9022    class AsecInstallArgs extends InstallArgs {
9023        static final String RES_FILE_NAME = "pkg.apk";
9024        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9025
9026        String cid;
9027        String packagePath;
9028        String resourcePath;
9029        String libraryPath;
9030
9031        AsecInstallArgs(InstallParams params) {
9032            super(params.getPackageUri(), params.observer, params.flags,
9033                    params.installerPackageName, params.getManifestDigest(),
9034                    params.getUser(), params.packageInstructionSetOverride,
9035                    params.packageAbiOverride);
9036        }
9037
9038        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9039                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9040            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9041                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9042                    null, null, null, instructionSet, null);
9043            // Extract cid from fullCodePath
9044            int eidx = fullCodePath.lastIndexOf("/");
9045            String subStr1 = fullCodePath.substring(0, eidx);
9046            int sidx = subStr1.lastIndexOf("/");
9047            cid = subStr1.substring(sidx+1, eidx);
9048            setCachePath(subStr1);
9049        }
9050
9051        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9052            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9053                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9054                    null, null, null, instructionSet, null);
9055            this.cid = cid;
9056            setCachePath(PackageHelper.getSdDir(cid));
9057        }
9058
9059        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9060                boolean isExternal, boolean isForwardLocked) {
9061            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9062                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9063                    null, null, null, instructionSet, null);
9064            this.cid = cid;
9065        }
9066
9067        void createCopyFile() {
9068            cid = getTempContainerId();
9069        }
9070
9071        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9072            try {
9073                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9074                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9075                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9076            } finally {
9077                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9078            }
9079        }
9080
9081        private final boolean isExternal() {
9082            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9083        }
9084
9085        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9086            if (temp) {
9087                createCopyFile();
9088            } else {
9089                /*
9090                 * Pre-emptively destroy the container since it's destroyed if
9091                 * copying fails due to it existing anyway.
9092                 */
9093                PackageHelper.destroySdDir(cid);
9094            }
9095
9096            final String newCachePath;
9097            try {
9098                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9099                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9100                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9101                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9102                        abiOverride);
9103            } finally {
9104                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9105            }
9106
9107            if (newCachePath != null) {
9108                setCachePath(newCachePath);
9109                return PackageManager.INSTALL_SUCCEEDED;
9110            } else {
9111                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9112            }
9113        }
9114
9115        @Override
9116        String getCodePath() {
9117            return packagePath;
9118        }
9119
9120        @Override
9121        String getResourcePath() {
9122            return resourcePath;
9123        }
9124
9125        @Override
9126        String getNativeLibraryPath() {
9127            return libraryPath;
9128        }
9129
9130        int doPreInstall(int status) {
9131            if (status != PackageManager.INSTALL_SUCCEEDED) {
9132                // Destroy container
9133                PackageHelper.destroySdDir(cid);
9134            } else {
9135                boolean mounted = PackageHelper.isContainerMounted(cid);
9136                if (!mounted) {
9137                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9138                            Process.SYSTEM_UID);
9139                    if (newCachePath != null) {
9140                        setCachePath(newCachePath);
9141                    } else {
9142                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9143                    }
9144                }
9145            }
9146            return status;
9147        }
9148
9149        boolean doRename(int status, final String pkgName,
9150                String oldCodePath) {
9151            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9152            String newCachePath = null;
9153            if (PackageHelper.isContainerMounted(cid)) {
9154                // Unmount the container
9155                if (!PackageHelper.unMountSdDir(cid)) {
9156                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9157                    return false;
9158                }
9159            }
9160            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9161                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9162                        " which might be stale. Will try to clean up.");
9163                // Clean up the stale container and proceed to recreate.
9164                if (!PackageHelper.destroySdDir(newCacheId)) {
9165                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9166                    return false;
9167                }
9168                // Successfully cleaned up stale container. Try to rename again.
9169                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9170                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9171                            + " inspite of cleaning it up.");
9172                    return false;
9173                }
9174            }
9175            if (!PackageHelper.isContainerMounted(newCacheId)) {
9176                Slog.w(TAG, "Mounting container " + newCacheId);
9177                newCachePath = PackageHelper.mountSdDir(newCacheId,
9178                        getEncryptKey(), Process.SYSTEM_UID);
9179            } else {
9180                newCachePath = PackageHelper.getSdDir(newCacheId);
9181            }
9182            if (newCachePath == null) {
9183                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9184                return false;
9185            }
9186            Log.i(TAG, "Succesfully renamed " + cid +
9187                    " to " + newCacheId +
9188                    " at new path: " + newCachePath);
9189            cid = newCacheId;
9190            setCachePath(newCachePath);
9191            return true;
9192        }
9193
9194        private void setCachePath(String newCachePath) {
9195            File cachePath = new File(newCachePath);
9196            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9197            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9198
9199            if (isFwdLocked()) {
9200                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9201            } else {
9202                resourcePath = packagePath;
9203            }
9204        }
9205
9206        int doPostInstall(int status, int uid) {
9207            if (status != PackageManager.INSTALL_SUCCEEDED) {
9208                cleanUp();
9209            } else {
9210                final int groupOwner;
9211                final String protectedFile;
9212                if (isFwdLocked()) {
9213                    groupOwner = UserHandle.getSharedAppGid(uid);
9214                    protectedFile = RES_FILE_NAME;
9215                } else {
9216                    groupOwner = -1;
9217                    protectedFile = null;
9218                }
9219
9220                if (uid < Process.FIRST_APPLICATION_UID
9221                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9222                    Slog.e(TAG, "Failed to finalize " + cid);
9223                    PackageHelper.destroySdDir(cid);
9224                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9225                }
9226
9227                boolean mounted = PackageHelper.isContainerMounted(cid);
9228                if (!mounted) {
9229                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9230                }
9231            }
9232            return status;
9233        }
9234
9235        private void cleanUp() {
9236            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9237
9238            // Destroy secure container
9239            PackageHelper.destroySdDir(cid);
9240        }
9241
9242        void cleanUpResourcesLI() {
9243            String sourceFile = getCodePath();
9244            // Remove dex file
9245            if (instructionSet == null) {
9246                throw new IllegalStateException("instructionSet == null");
9247            }
9248            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9249            if (retCode < 0) {
9250                Slog.w(TAG, "Couldn't remove dex file for package: "
9251                        + " at location "
9252                        + sourceFile.toString() + ", retcode=" + retCode);
9253                // we don't consider this to be a failure of the core package deletion
9254            }
9255            cleanUp();
9256        }
9257
9258        boolean matchContainer(String app) {
9259            if (cid.startsWith(app)) {
9260                return true;
9261            }
9262            return false;
9263        }
9264
9265        String getPackageName() {
9266            return getAsecPackageName(cid);
9267        }
9268
9269        boolean doPostDeleteLI(boolean delete) {
9270            boolean ret = false;
9271            boolean mounted = PackageHelper.isContainerMounted(cid);
9272            if (mounted) {
9273                // Unmount first
9274                ret = PackageHelper.unMountSdDir(cid);
9275            }
9276            if (ret && delete) {
9277                cleanUpResourcesLI();
9278            }
9279            return ret;
9280        }
9281
9282        @Override
9283        int doPreCopy() {
9284            if (isFwdLocked()) {
9285                if (!PackageHelper.fixSdPermissions(cid,
9286                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9287                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9288                }
9289            }
9290
9291            return PackageManager.INSTALL_SUCCEEDED;
9292        }
9293
9294        @Override
9295        int doPostCopy(int uid) {
9296            if (isFwdLocked()) {
9297                if (uid < Process.FIRST_APPLICATION_UID
9298                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9299                                RES_FILE_NAME)) {
9300                    Slog.e(TAG, "Failed to finalize " + cid);
9301                    PackageHelper.destroySdDir(cid);
9302                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9303                }
9304            }
9305
9306            return PackageManager.INSTALL_SUCCEEDED;
9307        }
9308    };
9309
9310    static String getAsecPackageName(String packageCid) {
9311        int idx = packageCid.lastIndexOf("-");
9312        if (idx == -1) {
9313            return packageCid;
9314        }
9315        return packageCid.substring(0, idx);
9316    }
9317
9318    // Utility method used to create code paths based on package name and available index.
9319    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9320        String idxStr = "";
9321        int idx = 1;
9322        // Fall back to default value of idx=1 if prefix is not
9323        // part of oldCodePath
9324        if (oldCodePath != null) {
9325            String subStr = oldCodePath;
9326            // Drop the suffix right away
9327            if (subStr.endsWith(suffix)) {
9328                subStr = subStr.substring(0, subStr.length() - suffix.length());
9329            }
9330            // If oldCodePath already contains prefix find out the
9331            // ending index to either increment or decrement.
9332            int sidx = subStr.lastIndexOf(prefix);
9333            if (sidx != -1) {
9334                subStr = subStr.substring(sidx + prefix.length());
9335                if (subStr != null) {
9336                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9337                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9338                    }
9339                    try {
9340                        idx = Integer.parseInt(subStr);
9341                        if (idx <= 1) {
9342                            idx++;
9343                        } else {
9344                            idx--;
9345                        }
9346                    } catch(NumberFormatException e) {
9347                    }
9348                }
9349            }
9350        }
9351        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9352        return prefix + idxStr;
9353    }
9354
9355    // Utility method used to ignore ADD/REMOVE events
9356    // by directory observer.
9357    private static boolean ignoreCodePath(String fullPathStr) {
9358        String apkName = getApkName(fullPathStr);
9359        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9360        if (idx != -1 && ((idx+1) < apkName.length())) {
9361            // Make sure the package ends with a numeral
9362            String version = apkName.substring(idx+1);
9363            try {
9364                Integer.parseInt(version);
9365                return true;
9366            } catch (NumberFormatException e) {}
9367        }
9368        return false;
9369    }
9370
9371    // Utility method that returns the relative package path with respect
9372    // to the installation directory. Like say for /data/data/com.test-1.apk
9373    // string com.test-1 is returned.
9374    static String getApkName(String codePath) {
9375        if (codePath == null) {
9376            return null;
9377        }
9378        int sidx = codePath.lastIndexOf("/");
9379        int eidx = codePath.lastIndexOf(".");
9380        if (eidx == -1) {
9381            eidx = codePath.length();
9382        } else if (eidx == 0) {
9383            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9384            return null;
9385        }
9386        return codePath.substring(sidx+1, eidx);
9387    }
9388
9389    class PackageInstalledInfo {
9390        String name;
9391        int uid;
9392        // The set of users that originally had this package installed.
9393        int[] origUsers;
9394        // The set of users that now have this package installed.
9395        int[] newUsers;
9396        PackageParser.Package pkg;
9397        int returnCode;
9398        PackageRemovedInfo removedInfo;
9399    }
9400
9401    /*
9402     * Install a non-existing package.
9403     */
9404    private void installNewPackageLI(PackageParser.Package pkg,
9405            int parseFlags, int scanMode, UserHandle user,
9406            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9407        // Remember this for later, in case we need to rollback this install
9408        String pkgName = pkg.packageName;
9409
9410        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9411        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9412        synchronized(mPackages) {
9413            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9414                // A package with the same name is already installed, though
9415                // it has been renamed to an older name.  The package we
9416                // are trying to install should be installed as an update to
9417                // the existing one, but that has not been requested, so bail.
9418                Slog.w(TAG, "Attempt to re-install " + pkgName
9419                        + " without first uninstalling package running as "
9420                        + mSettings.mRenamedPackages.get(pkgName));
9421                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9422                return;
9423            }
9424            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9425                // Don't allow installation over an existing package with the same name.
9426                Slog.w(TAG, "Attempt to re-install " + pkgName
9427                        + " without first uninstalling.");
9428                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9429                return;
9430            }
9431        }
9432        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9433        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9434                System.currentTimeMillis(), user, abiOverride);
9435        if (newPackage == null) {
9436            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9437            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9438                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9439            }
9440        } else {
9441            updateSettingsLI(newPackage,
9442                    installerPackageName,
9443                    null, null,
9444                    res);
9445            // delete the partially installed application. the data directory will have to be
9446            // restored if it was already existing
9447            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9448                // remove package from internal structures.  Note that we want deletePackageX to
9449                // delete the package data and cache directories that it created in
9450                // scanPackageLocked, unless those directories existed before we even tried to
9451                // install.
9452                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9453                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9454                                res.removedInfo, true);
9455            }
9456        }
9457    }
9458
9459    private void replacePackageLI(PackageParser.Package pkg,
9460            int parseFlags, int scanMode, UserHandle user,
9461            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9462
9463        PackageParser.Package oldPackage;
9464        String pkgName = pkg.packageName;
9465        int[] allUsers;
9466        boolean[] perUserInstalled;
9467
9468        // First find the old package info and check signatures
9469        synchronized(mPackages) {
9470            oldPackage = mPackages.get(pkgName);
9471            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9472            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9473                    != PackageManager.SIGNATURE_MATCH) {
9474                Slog.w(TAG, "New package has a different signature: " + pkgName);
9475                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9476                return;
9477            }
9478
9479            // In case of rollback, remember per-user/profile install state
9480            PackageSetting ps = mSettings.mPackages.get(pkgName);
9481            allUsers = sUserManager.getUserIds();
9482            perUserInstalled = new boolean[allUsers.length];
9483            for (int i = 0; i < allUsers.length; i++) {
9484                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9485            }
9486        }
9487        boolean sysPkg = (isSystemApp(oldPackage));
9488        if (sysPkg) {
9489            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9490                    user, allUsers, perUserInstalled, installerPackageName, res,
9491                    abiOverride);
9492        } else {
9493            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9494                    user, allUsers, perUserInstalled, installerPackageName, res,
9495                    abiOverride);
9496        }
9497    }
9498
9499    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9500            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9501            int[] allUsers, boolean[] perUserInstalled,
9502            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9503        PackageParser.Package newPackage = null;
9504        String pkgName = deletedPackage.packageName;
9505        boolean deletedPkg = true;
9506        boolean updatedSettings = false;
9507
9508        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9509                + deletedPackage);
9510        long origUpdateTime;
9511        if (pkg.mExtras != null) {
9512            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9513        } else {
9514            origUpdateTime = 0;
9515        }
9516
9517        // First delete the existing package while retaining the data directory
9518        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9519                res.removedInfo, true)) {
9520            // If the existing package wasn't successfully deleted
9521            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9522            deletedPkg = false;
9523        } else {
9524            // Successfully deleted the old package. Now proceed with re-installation
9525            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9526            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9527                    System.currentTimeMillis(), user, abiOverride);
9528            if (newPackage == null) {
9529                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9530                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9531                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9532                }
9533            } else {
9534                updateSettingsLI(newPackage,
9535                        installerPackageName,
9536                        allUsers, perUserInstalled,
9537                        res);
9538                updatedSettings = true;
9539            }
9540        }
9541
9542        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9543            // remove package from internal structures.  Note that we want deletePackageX to
9544            // delete the package data and cache directories that it created in
9545            // scanPackageLocked, unless those directories existed before we even tried to
9546            // install.
9547            if(updatedSettings) {
9548                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9549                deletePackageLI(
9550                        pkgName, null, true, allUsers, perUserInstalled,
9551                        PackageManager.DELETE_KEEP_DATA,
9552                                res.removedInfo, true);
9553            }
9554            // Since we failed to install the new package we need to restore the old
9555            // package that we deleted.
9556            if (deletedPkg) {
9557                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9558                File restoreFile = new File(deletedPackage.mPath);
9559                // Parse old package
9560                boolean oldOnSd = isExternal(deletedPackage);
9561                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9562                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9563                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9564                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9565                        | SCAN_UPDATE_TIME;
9566                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9567                        origUpdateTime, null, null) == null) {
9568                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9569                    return;
9570                }
9571                // Restore of old package succeeded. Update permissions.
9572                // writer
9573                synchronized (mPackages) {
9574                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9575                            UPDATE_PERMISSIONS_ALL);
9576                    // can downgrade to reader
9577                    mSettings.writeLPr();
9578                }
9579                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9580            }
9581        }
9582    }
9583
9584    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9585            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9586            int[] allUsers, boolean[] perUserInstalled,
9587            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9588        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9589                + ", old=" + deletedPackage);
9590        PackageParser.Package newPackage = null;
9591        boolean updatedSettings = false;
9592        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9593                PackageParser.PARSE_IS_SYSTEM;
9594        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9595            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9596        }
9597        String packageName = deletedPackage.packageName;
9598        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9599        if (packageName == null) {
9600            Slog.w(TAG, "Attempt to delete null packageName.");
9601            return;
9602        }
9603        PackageParser.Package oldPkg;
9604        PackageSetting oldPkgSetting;
9605        // reader
9606        synchronized (mPackages) {
9607            oldPkg = mPackages.get(packageName);
9608            oldPkgSetting = mSettings.mPackages.get(packageName);
9609            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9610                    (oldPkgSetting == null)) {
9611                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9612                return;
9613            }
9614        }
9615
9616        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9617
9618        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9619        res.removedInfo.removedPackage = packageName;
9620        // Remove existing system package
9621        removePackageLI(oldPkgSetting, true);
9622        // writer
9623        synchronized (mPackages) {
9624            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9625                // We didn't need to disable the .apk as a current system package,
9626                // which means we are replacing another update that is already
9627                // installed.  We need to make sure to delete the older one's .apk.
9628                res.removedInfo.args = createInstallArgs(0,
9629                        deletedPackage.applicationInfo.sourceDir,
9630                        deletedPackage.applicationInfo.publicSourceDir,
9631                        deletedPackage.applicationInfo.nativeLibraryDir,
9632                        getAppInstructionSet(deletedPackage.applicationInfo));
9633            } else {
9634                res.removedInfo.args = null;
9635            }
9636        }
9637
9638        // Successfully disabled the old package. Now proceed with re-installation
9639        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9640        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9641        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
9642        if (newPackage == null) {
9643            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9644            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9645                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9646            }
9647        } else {
9648            if (newPackage.mExtras != null) {
9649                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9650                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9651                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9652            }
9653            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9654            updatedSettings = true;
9655        }
9656
9657        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9658            // Re installation failed. Restore old information
9659            // Remove new pkg information
9660            if (newPackage != null) {
9661                removeInstalledPackageLI(newPackage, true);
9662            }
9663            // Add back the old system package
9664            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
9665            // Restore the old system information in Settings
9666            synchronized(mPackages) {
9667                if (updatedSettings) {
9668                    mSettings.enableSystemPackageLPw(packageName);
9669                    mSettings.setInstallerPackageName(packageName,
9670                            oldPkgSetting.installerPackageName);
9671                }
9672                mSettings.writeLPr();
9673            }
9674        }
9675    }
9676
9677    // Utility method used to move dex files during install.
9678    private int moveDexFilesLI(PackageParser.Package newPackage) {
9679        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9680            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9681            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9682                                             instructionSet);
9683            if (retCode != 0) {
9684                /*
9685                 * Programs may be lazily run through dexopt, so the
9686                 * source may not exist. However, something seems to
9687                 * have gone wrong, so note that dexopt needs to be
9688                 * run again and remove the source file. In addition,
9689                 * remove the target to make sure there isn't a stale
9690                 * file from a previous version of the package.
9691                 */
9692                newPackage.mDexOptNeeded = true;
9693                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
9694                mInstaller.rmdex(newPackage.mPath, instructionSet);
9695            }
9696        }
9697        return PackageManager.INSTALL_SUCCEEDED;
9698    }
9699
9700    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9701            int[] allUsers, boolean[] perUserInstalled,
9702            PackageInstalledInfo res) {
9703        String pkgName = newPackage.packageName;
9704        synchronized (mPackages) {
9705            //write settings. the installStatus will be incomplete at this stage.
9706            //note that the new package setting would have already been
9707            //added to mPackages. It hasn't been persisted yet.
9708            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9709            mSettings.writeLPr();
9710        }
9711
9712        if ((res.returnCode = moveDexFilesLI(newPackage))
9713                != PackageManager.INSTALL_SUCCEEDED) {
9714            // Discontinue if moving dex files failed.
9715            return;
9716        }
9717
9718        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9719
9720        synchronized (mPackages) {
9721            updatePermissionsLPw(newPackage.packageName, newPackage,
9722                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9723                            ? UPDATE_PERMISSIONS_ALL : 0));
9724            // For system-bundled packages, we assume that installing an upgraded version
9725            // of the package implies that the user actually wants to run that new code,
9726            // so we enable the package.
9727            if (isSystemApp(newPackage)) {
9728                // NB: implicit assumption that system package upgrades apply to all users
9729                if (DEBUG_INSTALL) {
9730                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9731                }
9732                PackageSetting ps = mSettings.mPackages.get(pkgName);
9733                if (ps != null) {
9734                    if (res.origUsers != null) {
9735                        for (int userHandle : res.origUsers) {
9736                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9737                                    userHandle, installerPackageName);
9738                        }
9739                    }
9740                    // Also convey the prior install/uninstall state
9741                    if (allUsers != null && perUserInstalled != null) {
9742                        for (int i = 0; i < allUsers.length; i++) {
9743                            if (DEBUG_INSTALL) {
9744                                Slog.d(TAG, "    user " + allUsers[i]
9745                                        + " => " + perUserInstalled[i]);
9746                            }
9747                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9748                        }
9749                        // these install state changes will be persisted in the
9750                        // upcoming call to mSettings.writeLPr().
9751                    }
9752                }
9753            }
9754            res.name = pkgName;
9755            res.uid = newPackage.applicationInfo.uid;
9756            res.pkg = newPackage;
9757            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9758            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9759            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9760            //to update install status
9761            mSettings.writeLPr();
9762        }
9763    }
9764
9765    private void installPackageLI(InstallArgs args,
9766            boolean newInstall, PackageInstalledInfo res) {
9767        int pFlags = args.flags;
9768        String installerPackageName = args.installerPackageName;
9769        File tmpPackageFile = new File(args.getCodePath());
9770        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9771        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9772        boolean replace = false;
9773        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9774                | (newInstall ? SCAN_NEW_INSTALL : 0);
9775        // Result object to be returned
9776        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9777
9778        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9779        // Retrieve PackageSettings and parse package
9780        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9781                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9782                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9783        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9784        pp.setSeparateProcesses(mSeparateProcesses);
9785        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9786                null, mMetrics, parseFlags);
9787        if (pkg == null) {
9788            res.returnCode = pp.getParseError();
9789            return;
9790        }
9791        String pkgName = res.name = pkg.packageName;
9792        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9793            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9794                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9795                return;
9796            }
9797        }
9798        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9799            res.returnCode = pp.getParseError();
9800            return;
9801        }
9802
9803        /* If the installer passed in a manifest digest, compare it now. */
9804        if (args.manifestDigest != null) {
9805            if (DEBUG_INSTALL) {
9806                final String parsedManifest = pkg.manifestDigest == null ? "null"
9807                        : pkg.manifestDigest.toString();
9808                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9809                        + parsedManifest);
9810            }
9811
9812            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9813                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9814                return;
9815            }
9816        } else if (DEBUG_INSTALL) {
9817            final String parsedManifest = pkg.manifestDigest == null
9818                    ? "null" : pkg.manifestDigest.toString();
9819            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9820        }
9821
9822        // Get rid of all references to package scan path via parser.
9823        pp = null;
9824        String oldCodePath = null;
9825        boolean systemApp = false;
9826        synchronized (mPackages) {
9827            // Check if installing already existing package
9828            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9829                String oldName = mSettings.mRenamedPackages.get(pkgName);
9830                if (pkg.mOriginalPackages != null
9831                        && pkg.mOriginalPackages.contains(oldName)
9832                        && mPackages.containsKey(oldName)) {
9833                    // This package is derived from an original package,
9834                    // and this device has been updating from that original
9835                    // name.  We must continue using the original name, so
9836                    // rename the new package here.
9837                    pkg.setPackageName(oldName);
9838                    pkgName = pkg.packageName;
9839                    replace = true;
9840                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9841                            + oldName + " pkgName=" + pkgName);
9842                } else if (mPackages.containsKey(pkgName)) {
9843                    // This package, under its official name, already exists
9844                    // on the device; we should replace it.
9845                    replace = true;
9846                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9847                }
9848            }
9849            PackageSetting ps = mSettings.mPackages.get(pkgName);
9850            if (ps != null) {
9851                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9852                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9853                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9854                    systemApp = (ps.pkg.applicationInfo.flags &
9855                            ApplicationInfo.FLAG_SYSTEM) != 0;
9856                }
9857                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9858            }
9859        }
9860
9861        if (systemApp && onSd) {
9862            // Disable updates to system apps on sdcard
9863            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9864            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9865            return;
9866        }
9867
9868        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9869            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9870            return;
9871        }
9872        // Set application objects path explicitly after the rename
9873        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9874        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9875        if (replace) {
9876            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9877                    installerPackageName, res, args.abiOverride);
9878        } else {
9879            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9880                    installerPackageName, res, args.abiOverride);
9881        }
9882        synchronized (mPackages) {
9883            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9884            if (ps != null) {
9885                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9886            }
9887        }
9888    }
9889
9890    private static boolean isForwardLocked(PackageParser.Package pkg) {
9891        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9892    }
9893
9894
9895    private boolean isForwardLocked(PackageSetting ps) {
9896        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9897    }
9898
9899    private static boolean isExternal(PackageParser.Package pkg) {
9900        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9901    }
9902
9903    private static boolean isExternal(PackageSetting ps) {
9904        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9905    }
9906
9907    private static boolean isSystemApp(PackageParser.Package pkg) {
9908        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9909    }
9910
9911    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9912        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9913    }
9914
9915    private static boolean isSystemApp(ApplicationInfo info) {
9916        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9917    }
9918
9919    private static boolean isSystemApp(PackageSetting ps) {
9920        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9921    }
9922
9923    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9924        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9925    }
9926
9927    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9928        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9929    }
9930
9931    private int packageFlagsToInstallFlags(PackageSetting ps) {
9932        int installFlags = 0;
9933        if (isExternal(ps)) {
9934            installFlags |= PackageManager.INSTALL_EXTERNAL;
9935        }
9936        if (isForwardLocked(ps)) {
9937            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9938        }
9939        return installFlags;
9940    }
9941
9942    private void deleteTempPackageFiles() {
9943        final FilenameFilter filter = new FilenameFilter() {
9944            public boolean accept(File dir, String name) {
9945                return name.startsWith("vmdl") && name.endsWith(".tmp");
9946            }
9947        };
9948        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9949        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9950    }
9951
9952    private static final void deleteTempPackageFilesInDirectory(File directory,
9953            FilenameFilter filter) {
9954        final String[] tmpFilesList = directory.list(filter);
9955        if (tmpFilesList == null) {
9956            return;
9957        }
9958        for (int i = 0; i < tmpFilesList.length; i++) {
9959            final File tmpFile = new File(directory, tmpFilesList[i]);
9960            tmpFile.delete();
9961        }
9962    }
9963
9964    private File createTempPackageFile(File installDir) {
9965        File tmpPackageFile;
9966        try {
9967            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9968        } catch (IOException e) {
9969            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9970            return null;
9971        }
9972        try {
9973            FileUtils.setPermissions(
9974                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9975                    -1, -1);
9976            if (!SELinux.restorecon(tmpPackageFile)) {
9977                return null;
9978            }
9979        } catch (IOException e) {
9980            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9981            return null;
9982        }
9983        return tmpPackageFile;
9984    }
9985
9986    @Override
9987    public void deletePackageAsUser(final String packageName,
9988                                    final IPackageDeleteObserver observer,
9989                                    final int userId, final int flags) {
9990        mContext.enforceCallingOrSelfPermission(
9991                android.Manifest.permission.DELETE_PACKAGES, null);
9992        final int uid = Binder.getCallingUid();
9993        if (UserHandle.getUserId(uid) != userId) {
9994            mContext.enforceCallingPermission(
9995                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9996                    "deletePackage for user " + userId);
9997        }
9998        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9999            try {
10000                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10001            } catch (RemoteException re) {
10002            }
10003            return;
10004        }
10005
10006        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10007        // Queue up an async operation since the package deletion may take a little while.
10008        mHandler.post(new Runnable() {
10009            public void run() {
10010                mHandler.removeCallbacks(this);
10011                final int returnCode = deletePackageX(packageName, userId, flags);
10012                if (observer != null) {
10013                    try {
10014                        observer.packageDeleted(packageName, returnCode);
10015                    } catch (RemoteException e) {
10016                        Log.i(TAG, "Observer no longer exists.");
10017                    } //end catch
10018                } //end if
10019            } //end run
10020        });
10021    }
10022
10023    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10024        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10025                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10026        try {
10027            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10028                    || dpm.isDeviceOwner(packageName))) {
10029                return true;
10030            }
10031        } catch (RemoteException e) {
10032        }
10033        return false;
10034    }
10035
10036    /**
10037     *  This method is an internal method that could be get invoked either
10038     *  to delete an installed package or to clean up a failed installation.
10039     *  After deleting an installed package, a broadcast is sent to notify any
10040     *  listeners that the package has been installed. For cleaning up a failed
10041     *  installation, the broadcast is not necessary since the package's
10042     *  installation wouldn't have sent the initial broadcast either
10043     *  The key steps in deleting a package are
10044     *  deleting the package information in internal structures like mPackages,
10045     *  deleting the packages base directories through installd
10046     *  updating mSettings to reflect current status
10047     *  persisting settings for later use
10048     *  sending a broadcast if necessary
10049     */
10050    private int deletePackageX(String packageName, int userId, int flags) {
10051        final PackageRemovedInfo info = new PackageRemovedInfo();
10052        final boolean res;
10053
10054        if (isPackageDeviceAdmin(packageName, userId)) {
10055            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10056            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10057        }
10058
10059        boolean removedForAllUsers = false;
10060        boolean systemUpdate = false;
10061
10062        // for the uninstall-updates case and restricted profiles, remember the per-
10063        // userhandle installed state
10064        int[] allUsers;
10065        boolean[] perUserInstalled;
10066        synchronized (mPackages) {
10067            PackageSetting ps = mSettings.mPackages.get(packageName);
10068            allUsers = sUserManager.getUserIds();
10069            perUserInstalled = new boolean[allUsers.length];
10070            for (int i = 0; i < allUsers.length; i++) {
10071                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10072            }
10073        }
10074
10075        synchronized (mInstallLock) {
10076            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10077            res = deletePackageLI(packageName,
10078                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10079                            ? UserHandle.ALL : new UserHandle(userId),
10080                    true, allUsers, perUserInstalled,
10081                    flags | REMOVE_CHATTY, info, true);
10082            systemUpdate = info.isRemovedPackageSystemUpdate;
10083            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10084                removedForAllUsers = true;
10085            }
10086            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10087                    + " removedForAllUsers=" + removedForAllUsers);
10088        }
10089
10090        if (res) {
10091            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10092
10093            // If the removed package was a system update, the old system package
10094            // was re-enabled; we need to broadcast this information
10095            if (systemUpdate) {
10096                Bundle extras = new Bundle(1);
10097                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10098                        ? info.removedAppId : info.uid);
10099                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10100
10101                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10102                        extras, null, null, null);
10103                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10104                        extras, null, null, null);
10105                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10106                        null, packageName, null, null);
10107            }
10108        }
10109        // Force a gc here.
10110        Runtime.getRuntime().gc();
10111        // Delete the resources here after sending the broadcast to let
10112        // other processes clean up before deleting resources.
10113        if (info.args != null) {
10114            synchronized (mInstallLock) {
10115                info.args.doPostDeleteLI(true);
10116            }
10117        }
10118
10119        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10120    }
10121
10122    static class PackageRemovedInfo {
10123        String removedPackage;
10124        int uid = -1;
10125        int removedAppId = -1;
10126        int[] removedUsers = null;
10127        boolean isRemovedPackageSystemUpdate = false;
10128        // Clean up resources deleted packages.
10129        InstallArgs args = null;
10130
10131        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10132            Bundle extras = new Bundle(1);
10133            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10134            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10135            if (replacing) {
10136                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10137            }
10138            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10139            if (removedPackage != null) {
10140                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10141                        extras, null, null, removedUsers);
10142                if (fullRemove && !replacing) {
10143                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10144                            extras, null, null, removedUsers);
10145                }
10146            }
10147            if (removedAppId >= 0) {
10148                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10149                        removedUsers);
10150            }
10151        }
10152    }
10153
10154    /*
10155     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10156     * flag is not set, the data directory is removed as well.
10157     * make sure this flag is set for partially installed apps. If not its meaningless to
10158     * delete a partially installed application.
10159     */
10160    private void removePackageDataLI(PackageSetting ps,
10161            int[] allUserHandles, boolean[] perUserInstalled,
10162            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10163        String packageName = ps.name;
10164        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10165        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10166        // Retrieve object to delete permissions for shared user later on
10167        final PackageSetting deletedPs;
10168        // reader
10169        synchronized (mPackages) {
10170            deletedPs = mSettings.mPackages.get(packageName);
10171            if (outInfo != null) {
10172                outInfo.removedPackage = packageName;
10173                outInfo.removedUsers = deletedPs != null
10174                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10175                        : null;
10176            }
10177        }
10178        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10179            removeDataDirsLI(packageName);
10180            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10181        }
10182        // writer
10183        synchronized (mPackages) {
10184            if (deletedPs != null) {
10185                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10186                    if (outInfo != null) {
10187                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10188                    }
10189                    if (deletedPs != null) {
10190                        updatePermissionsLPw(deletedPs.name, null, 0);
10191                        if (deletedPs.sharedUser != null) {
10192                            // remove permissions associated with package
10193                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10194                        }
10195                    }
10196                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10197                }
10198                // make sure to preserve per-user disabled state if this removal was just
10199                // a downgrade of a system app to the factory package
10200                if (allUserHandles != null && perUserInstalled != null) {
10201                    if (DEBUG_REMOVE) {
10202                        Slog.d(TAG, "Propagating install state across downgrade");
10203                    }
10204                    for (int i = 0; i < allUserHandles.length; i++) {
10205                        if (DEBUG_REMOVE) {
10206                            Slog.d(TAG, "    user " + allUserHandles[i]
10207                                    + " => " + perUserInstalled[i]);
10208                        }
10209                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10210                    }
10211                }
10212            }
10213            // can downgrade to reader
10214            if (writeSettings) {
10215                // Save settings now
10216                mSettings.writeLPr();
10217            }
10218        }
10219        if (outInfo != null) {
10220            // A user ID was deleted here. Go through all users and remove it
10221            // from KeyStore.
10222            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10223        }
10224    }
10225
10226    static boolean locationIsPrivileged(File path) {
10227        try {
10228            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10229                    .getCanonicalPath();
10230            return path.getCanonicalPath().startsWith(privilegedAppDir);
10231        } catch (IOException e) {
10232            Slog.e(TAG, "Unable to access code path " + path);
10233        }
10234        return false;
10235    }
10236
10237    /*
10238     * Tries to delete system package.
10239     */
10240    private boolean deleteSystemPackageLI(PackageSetting newPs,
10241            int[] allUserHandles, boolean[] perUserInstalled,
10242            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10243        final boolean applyUserRestrictions
10244                = (allUserHandles != null) && (perUserInstalled != null);
10245        PackageSetting disabledPs = null;
10246        // Confirm if the system package has been updated
10247        // An updated system app can be deleted. This will also have to restore
10248        // the system pkg from system partition
10249        // reader
10250        synchronized (mPackages) {
10251            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10252        }
10253        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10254                + " disabledPs=" + disabledPs);
10255        if (disabledPs == null) {
10256            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10257            return false;
10258        } else if (DEBUG_REMOVE) {
10259            Slog.d(TAG, "Deleting system pkg from data partition");
10260        }
10261        if (DEBUG_REMOVE) {
10262            if (applyUserRestrictions) {
10263                Slog.d(TAG, "Remembering install states:");
10264                for (int i = 0; i < allUserHandles.length; i++) {
10265                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10266                }
10267            }
10268        }
10269        // Delete the updated package
10270        outInfo.isRemovedPackageSystemUpdate = true;
10271        if (disabledPs.versionCode < newPs.versionCode) {
10272            // Delete data for downgrades
10273            flags &= ~PackageManager.DELETE_KEEP_DATA;
10274        } else {
10275            // Preserve data by setting flag
10276            flags |= PackageManager.DELETE_KEEP_DATA;
10277        }
10278        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10279                allUserHandles, perUserInstalled, outInfo, writeSettings);
10280        if (!ret) {
10281            return false;
10282        }
10283        // writer
10284        synchronized (mPackages) {
10285            // Reinstate the old system package
10286            mSettings.enableSystemPackageLPw(newPs.name);
10287            // Remove any native libraries from the upgraded package.
10288            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10289        }
10290        // Install the system package
10291        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10292        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10293        if (locationIsPrivileged(disabledPs.codePath)) {
10294            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10295        }
10296        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10297                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10298
10299        if (newPkg == null) {
10300            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10301                    + " with error:" + mLastScanError);
10302            return false;
10303        }
10304        // writer
10305        synchronized (mPackages) {
10306            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10307            setInternalAppNativeLibraryPath(newPkg, ps);
10308            updatePermissionsLPw(newPkg.packageName, newPkg,
10309                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10310            if (applyUserRestrictions) {
10311                if (DEBUG_REMOVE) {
10312                    Slog.d(TAG, "Propagating install state across reinstall");
10313                }
10314                for (int i = 0; i < allUserHandles.length; i++) {
10315                    if (DEBUG_REMOVE) {
10316                        Slog.d(TAG, "    user " + allUserHandles[i]
10317                                + " => " + perUserInstalled[i]);
10318                    }
10319                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10320                }
10321                // Regardless of writeSettings we need to ensure that this restriction
10322                // state propagation is persisted
10323                mSettings.writeAllUsersPackageRestrictionsLPr();
10324            }
10325            // can downgrade to reader here
10326            if (writeSettings) {
10327                mSettings.writeLPr();
10328            }
10329        }
10330        return true;
10331    }
10332
10333    private boolean deleteInstalledPackageLI(PackageSetting ps,
10334            boolean deleteCodeAndResources, int flags,
10335            int[] allUserHandles, boolean[] perUserInstalled,
10336            PackageRemovedInfo outInfo, boolean writeSettings) {
10337        if (outInfo != null) {
10338            outInfo.uid = ps.appId;
10339        }
10340
10341        // Delete package data from internal structures and also remove data if flag is set
10342        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10343
10344        // Delete application code and resources
10345        if (deleteCodeAndResources && (outInfo != null)) {
10346            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10347                    ps.resourcePathString, ps.nativeLibraryPathString,
10348                    getAppInstructionSetFromSettings(ps));
10349        }
10350        return true;
10351    }
10352
10353    /*
10354     * This method handles package deletion in general
10355     */
10356    private boolean deletePackageLI(String packageName, UserHandle user,
10357            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10358            int flags, PackageRemovedInfo outInfo,
10359            boolean writeSettings) {
10360        if (packageName == null) {
10361            Slog.w(TAG, "Attempt to delete null packageName.");
10362            return false;
10363        }
10364        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10365        PackageSetting ps;
10366        boolean dataOnly = false;
10367        int removeUser = -1;
10368        int appId = -1;
10369        synchronized (mPackages) {
10370            ps = mSettings.mPackages.get(packageName);
10371            if (ps == null) {
10372                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10373                return false;
10374            }
10375            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10376                    && user.getIdentifier() != UserHandle.USER_ALL) {
10377                // The caller is asking that the package only be deleted for a single
10378                // user.  To do this, we just mark its uninstalled state and delete
10379                // its data.  If this is a system app, we only allow this to happen if
10380                // they have set the special DELETE_SYSTEM_APP which requests different
10381                // semantics than normal for uninstalling system apps.
10382                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10383                ps.setUserState(user.getIdentifier(),
10384                        COMPONENT_ENABLED_STATE_DEFAULT,
10385                        false, //installed
10386                        true,  //stopped
10387                        true,  //notLaunched
10388                        false, //blocked
10389                        null, null, null);
10390                if (!isSystemApp(ps)) {
10391                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10392                        // Other user still have this package installed, so all
10393                        // we need to do is clear this user's data and save that
10394                        // it is uninstalled.
10395                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10396                        removeUser = user.getIdentifier();
10397                        appId = ps.appId;
10398                        mSettings.writePackageRestrictionsLPr(removeUser);
10399                    } else {
10400                        // We need to set it back to 'installed' so the uninstall
10401                        // broadcasts will be sent correctly.
10402                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10403                        ps.setInstalled(true, user.getIdentifier());
10404                    }
10405                } else {
10406                    // This is a system app, so we assume that the
10407                    // other users still have this package installed, so all
10408                    // we need to do is clear this user's data and save that
10409                    // it is uninstalled.
10410                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10411                    removeUser = user.getIdentifier();
10412                    appId = ps.appId;
10413                    mSettings.writePackageRestrictionsLPr(removeUser);
10414                }
10415            }
10416        }
10417
10418        if (removeUser >= 0) {
10419            // From above, we determined that we are deleting this only
10420            // for a single user.  Continue the work here.
10421            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10422            if (outInfo != null) {
10423                outInfo.removedPackage = packageName;
10424                outInfo.removedAppId = appId;
10425                outInfo.removedUsers = new int[] {removeUser};
10426            }
10427            mInstaller.clearUserData(packageName, removeUser);
10428            removeKeystoreDataIfNeeded(removeUser, appId);
10429            schedulePackageCleaning(packageName, removeUser, false);
10430            return true;
10431        }
10432
10433        if (dataOnly) {
10434            // Delete application data first
10435            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10436            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10437            return true;
10438        }
10439
10440        boolean ret = false;
10441        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10442        if (isSystemApp(ps)) {
10443            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10444            // When an updated system application is deleted we delete the existing resources as well and
10445            // fall back to existing code in system partition
10446            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10447                    flags, outInfo, writeSettings);
10448        } else {
10449            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10450            // Kill application pre-emptively especially for apps on sd.
10451            killApplication(packageName, ps.appId, "uninstall pkg");
10452            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10453                    allUserHandles, perUserInstalled,
10454                    outInfo, writeSettings);
10455        }
10456
10457        return ret;
10458    }
10459
10460    private final class ClearStorageConnection implements ServiceConnection {
10461        IMediaContainerService mContainerService;
10462
10463        @Override
10464        public void onServiceConnected(ComponentName name, IBinder service) {
10465            synchronized (this) {
10466                mContainerService = IMediaContainerService.Stub.asInterface(service);
10467                notifyAll();
10468            }
10469        }
10470
10471        @Override
10472        public void onServiceDisconnected(ComponentName name) {
10473        }
10474    }
10475
10476    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10477        final boolean mounted;
10478        if (Environment.isExternalStorageEmulated()) {
10479            mounted = true;
10480        } else {
10481            final String status = Environment.getExternalStorageState();
10482
10483            mounted = status.equals(Environment.MEDIA_MOUNTED)
10484                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10485        }
10486
10487        if (!mounted) {
10488            return;
10489        }
10490
10491        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10492        int[] users;
10493        if (userId == UserHandle.USER_ALL) {
10494            users = sUserManager.getUserIds();
10495        } else {
10496            users = new int[] { userId };
10497        }
10498        final ClearStorageConnection conn = new ClearStorageConnection();
10499        if (mContext.bindServiceAsUser(
10500                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10501            try {
10502                for (int curUser : users) {
10503                    long timeout = SystemClock.uptimeMillis() + 5000;
10504                    synchronized (conn) {
10505                        long now = SystemClock.uptimeMillis();
10506                        while (conn.mContainerService == null && now < timeout) {
10507                            try {
10508                                conn.wait(timeout - now);
10509                            } catch (InterruptedException e) {
10510                            }
10511                        }
10512                    }
10513                    if (conn.mContainerService == null) {
10514                        return;
10515                    }
10516
10517                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10518                    clearDirectory(conn.mContainerService,
10519                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10520                    if (allData) {
10521                        clearDirectory(conn.mContainerService,
10522                                userEnv.buildExternalStorageAppDataDirs(packageName));
10523                        clearDirectory(conn.mContainerService,
10524                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10525                    }
10526                }
10527            } finally {
10528                mContext.unbindService(conn);
10529            }
10530        }
10531    }
10532
10533    @Override
10534    public void clearApplicationUserData(final String packageName,
10535            final IPackageDataObserver observer, final int userId) {
10536        mContext.enforceCallingOrSelfPermission(
10537                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10538        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10539        // Queue up an async operation since the package deletion may take a little while.
10540        mHandler.post(new Runnable() {
10541            public void run() {
10542                mHandler.removeCallbacks(this);
10543                final boolean succeeded;
10544                synchronized (mInstallLock) {
10545                    succeeded = clearApplicationUserDataLI(packageName, userId);
10546                }
10547                clearExternalStorageDataSync(packageName, userId, true);
10548                if (succeeded) {
10549                    // invoke DeviceStorageMonitor's update method to clear any notifications
10550                    DeviceStorageMonitorInternal
10551                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10552                    if (dsm != null) {
10553                        dsm.checkMemory();
10554                    }
10555                }
10556                if(observer != null) {
10557                    try {
10558                        observer.onRemoveCompleted(packageName, succeeded);
10559                    } catch (RemoteException e) {
10560                        Log.i(TAG, "Observer no longer exists.");
10561                    }
10562                } //end if observer
10563            } //end run
10564        });
10565    }
10566
10567    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10568        if (packageName == null) {
10569            Slog.w(TAG, "Attempt to delete null packageName.");
10570            return false;
10571        }
10572        PackageParser.Package p;
10573        boolean dataOnly = false;
10574        final int appId;
10575        synchronized (mPackages) {
10576            p = mPackages.get(packageName);
10577            if (p == null) {
10578                dataOnly = true;
10579                PackageSetting ps = mSettings.mPackages.get(packageName);
10580                if ((ps == null) || (ps.pkg == null)) {
10581                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10582                    return false;
10583                }
10584                p = ps.pkg;
10585            }
10586            if (!dataOnly) {
10587                // need to check this only for fully installed applications
10588                if (p == null) {
10589                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10590                    return false;
10591                }
10592                final ApplicationInfo applicationInfo = p.applicationInfo;
10593                if (applicationInfo == null) {
10594                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10595                    return false;
10596                }
10597            }
10598            if (p != null && p.applicationInfo != null) {
10599                appId = p.applicationInfo.uid;
10600            } else {
10601                appId = -1;
10602            }
10603        }
10604        int retCode = mInstaller.clearUserData(packageName, userId);
10605        if (retCode < 0) {
10606            Slog.w(TAG, "Couldn't remove cache files for package: "
10607                    + packageName);
10608            return false;
10609        }
10610        removeKeystoreDataIfNeeded(userId, appId);
10611        return true;
10612    }
10613
10614    /**
10615     * Remove entries from the keystore daemon. Will only remove it if the
10616     * {@code appId} is valid.
10617     */
10618    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10619        if (appId < 0) {
10620            return;
10621        }
10622
10623        final KeyStore keyStore = KeyStore.getInstance();
10624        if (keyStore != null) {
10625            if (userId == UserHandle.USER_ALL) {
10626                for (final int individual : sUserManager.getUserIds()) {
10627                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10628                }
10629            } else {
10630                keyStore.clearUid(UserHandle.getUid(userId, appId));
10631            }
10632        } else {
10633            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10634        }
10635    }
10636
10637    @Override
10638    public void deleteApplicationCacheFiles(final String packageName,
10639            final IPackageDataObserver observer) {
10640        mContext.enforceCallingOrSelfPermission(
10641                android.Manifest.permission.DELETE_CACHE_FILES, null);
10642        // Queue up an async operation since the package deletion may take a little while.
10643        final int userId = UserHandle.getCallingUserId();
10644        mHandler.post(new Runnable() {
10645            public void run() {
10646                mHandler.removeCallbacks(this);
10647                final boolean succeded;
10648                synchronized (mInstallLock) {
10649                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10650                }
10651                clearExternalStorageDataSync(packageName, userId, false);
10652                if(observer != null) {
10653                    try {
10654                        observer.onRemoveCompleted(packageName, succeded);
10655                    } catch (RemoteException e) {
10656                        Log.i(TAG, "Observer no longer exists.");
10657                    }
10658                } //end if observer
10659            } //end run
10660        });
10661    }
10662
10663    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10664        if (packageName == null) {
10665            Slog.w(TAG, "Attempt to delete null packageName.");
10666            return false;
10667        }
10668        PackageParser.Package p;
10669        synchronized (mPackages) {
10670            p = mPackages.get(packageName);
10671        }
10672        if (p == null) {
10673            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10674            return false;
10675        }
10676        final ApplicationInfo applicationInfo = p.applicationInfo;
10677        if (applicationInfo == null) {
10678            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10679            return false;
10680        }
10681        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10682        if (retCode < 0) {
10683            Slog.w(TAG, "Couldn't remove cache files for package: "
10684                       + packageName + " u" + userId);
10685            return false;
10686        }
10687        return true;
10688    }
10689
10690    @Override
10691    public void getPackageSizeInfo(final String packageName, int userHandle,
10692            final IPackageStatsObserver observer) {
10693        mContext.enforceCallingOrSelfPermission(
10694                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10695
10696        PackageStats stats = new PackageStats(packageName, userHandle);
10697
10698        /*
10699         * Queue up an async operation since the package measurement may take a
10700         * little while.
10701         */
10702        Message msg = mHandler.obtainMessage(INIT_COPY);
10703        msg.obj = new MeasureParams(stats, observer);
10704        mHandler.sendMessage(msg);
10705    }
10706
10707    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10708            PackageStats pStats) {
10709        if (packageName == null) {
10710            Slog.w(TAG, "Attempt to get size of null packageName.");
10711            return false;
10712        }
10713        PackageParser.Package p;
10714        boolean dataOnly = false;
10715        String libDirPath = null;
10716        String asecPath = null;
10717        PackageSetting ps = null;
10718        synchronized (mPackages) {
10719            p = mPackages.get(packageName);
10720            ps = mSettings.mPackages.get(packageName);
10721            if(p == null) {
10722                dataOnly = true;
10723                if((ps == null) || (ps.pkg == null)) {
10724                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10725                    return false;
10726                }
10727                p = ps.pkg;
10728            }
10729            if (ps != null) {
10730                libDirPath = ps.nativeLibraryPathString;
10731            }
10732            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10733                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10734                if (secureContainerId != null) {
10735                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10736                }
10737            }
10738        }
10739        String publicSrcDir = null;
10740        if(!dataOnly) {
10741            final ApplicationInfo applicationInfo = p.applicationInfo;
10742            if (applicationInfo == null) {
10743                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10744                return false;
10745            }
10746            if (isForwardLocked(p)) {
10747                publicSrcDir = applicationInfo.publicSourceDir;
10748            }
10749        }
10750        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10751                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10752                pStats);
10753        if (res < 0) {
10754            return false;
10755        }
10756
10757        // Fix-up for forward-locked applications in ASEC containers.
10758        if (!isExternal(p)) {
10759            pStats.codeSize += pStats.externalCodeSize;
10760            pStats.externalCodeSize = 0L;
10761        }
10762
10763        return true;
10764    }
10765
10766
10767    @Override
10768    public void addPackageToPreferred(String packageName) {
10769        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10770    }
10771
10772    @Override
10773    public void removePackageFromPreferred(String packageName) {
10774        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10775    }
10776
10777    @Override
10778    public List<PackageInfo> getPreferredPackages(int flags) {
10779        return new ArrayList<PackageInfo>();
10780    }
10781
10782    private int getUidTargetSdkVersionLockedLPr(int uid) {
10783        Object obj = mSettings.getUserIdLPr(uid);
10784        if (obj instanceof SharedUserSetting) {
10785            final SharedUserSetting sus = (SharedUserSetting) obj;
10786            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10787            final Iterator<PackageSetting> it = sus.packages.iterator();
10788            while (it.hasNext()) {
10789                final PackageSetting ps = it.next();
10790                if (ps.pkg != null) {
10791                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10792                    if (v < vers) vers = v;
10793                }
10794            }
10795            return vers;
10796        } else if (obj instanceof PackageSetting) {
10797            final PackageSetting ps = (PackageSetting) obj;
10798            if (ps.pkg != null) {
10799                return ps.pkg.applicationInfo.targetSdkVersion;
10800            }
10801        }
10802        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10803    }
10804
10805    @Override
10806    public void addPreferredActivity(IntentFilter filter, int match,
10807            ComponentName[] set, ComponentName activity, int userId) {
10808        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10809    }
10810
10811    private void addPreferredActivityInternal(IntentFilter filter, int match,
10812            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10813        // writer
10814        int callingUid = Binder.getCallingUid();
10815        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10816        if (filter.countActions() == 0) {
10817            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10818            return;
10819        }
10820        synchronized (mPackages) {
10821            if (mContext.checkCallingOrSelfPermission(
10822                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10823                    != PackageManager.PERMISSION_GRANTED) {
10824                if (getUidTargetSdkVersionLockedLPr(callingUid)
10825                        < Build.VERSION_CODES.FROYO) {
10826                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10827                            + callingUid);
10828                    return;
10829                }
10830                mContext.enforceCallingOrSelfPermission(
10831                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10832            }
10833
10834            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10835            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10836            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10837                    new PreferredActivity(filter, match, set, activity, always));
10838            mSettings.writePackageRestrictionsLPr(userId);
10839        }
10840    }
10841
10842    @Override
10843    public void replacePreferredActivity(IntentFilter filter, int match,
10844            ComponentName[] set, ComponentName activity) {
10845        if (filter.countActions() != 1) {
10846            throw new IllegalArgumentException(
10847                    "replacePreferredActivity expects filter to have only 1 action.");
10848        }
10849        if (filter.countDataAuthorities() != 0
10850                || filter.countDataPaths() != 0
10851                || filter.countDataSchemes() > 1
10852                || filter.countDataTypes() != 0) {
10853            throw new IllegalArgumentException(
10854                    "replacePreferredActivity expects filter to have no data authorities, " +
10855                    "paths, or types; and at most one scheme.");
10856        }
10857        synchronized (mPackages) {
10858            if (mContext.checkCallingOrSelfPermission(
10859                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10860                    != PackageManager.PERMISSION_GRANTED) {
10861                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10862                        < Build.VERSION_CODES.FROYO) {
10863                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10864                            + Binder.getCallingUid());
10865                    return;
10866                }
10867                mContext.enforceCallingOrSelfPermission(
10868                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10869            }
10870
10871            final int callingUserId = UserHandle.getCallingUserId();
10872            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10873            if (pir != null) {
10874                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10875                if (filter.countDataSchemes() == 1) {
10876                    Uri.Builder builder = new Uri.Builder();
10877                    builder.scheme(filter.getDataScheme(0));
10878                    intent.setData(builder.build());
10879                }
10880                List<PreferredActivity> matches = pir.queryIntent(
10881                        intent, null, true, callingUserId);
10882                if (DEBUG_PREFERRED) {
10883                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10884                }
10885                for (int i = 0; i < matches.size(); i++) {
10886                    PreferredActivity pa = matches.get(i);
10887                    if (DEBUG_PREFERRED) {
10888                        Slog.i(TAG, "Removing preferred activity "
10889                                + pa.mPref.mComponent + ":");
10890                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10891                    }
10892                    pir.removeFilter(pa);
10893                }
10894            }
10895            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10896        }
10897    }
10898
10899    @Override
10900    public void clearPackagePreferredActivities(String packageName) {
10901        final int uid = Binder.getCallingUid();
10902        // writer
10903        synchronized (mPackages) {
10904            PackageParser.Package pkg = mPackages.get(packageName);
10905            if (pkg == null || pkg.applicationInfo.uid != uid) {
10906                if (mContext.checkCallingOrSelfPermission(
10907                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10908                        != PackageManager.PERMISSION_GRANTED) {
10909                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10910                            < Build.VERSION_CODES.FROYO) {
10911                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10912                                + Binder.getCallingUid());
10913                        return;
10914                    }
10915                    mContext.enforceCallingOrSelfPermission(
10916                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10917                }
10918            }
10919
10920            int user = UserHandle.getCallingUserId();
10921            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10922                mSettings.writePackageRestrictionsLPr(user);
10923                scheduleWriteSettingsLocked();
10924            }
10925        }
10926    }
10927
10928    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10929    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10930        ArrayList<PreferredActivity> removed = null;
10931        boolean changed = false;
10932        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10933            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10934            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10935            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10936                continue;
10937            }
10938            Iterator<PreferredActivity> it = pir.filterIterator();
10939            while (it.hasNext()) {
10940                PreferredActivity pa = it.next();
10941                // Mark entry for removal only if it matches the package name
10942                // and the entry is of type "always".
10943                if (packageName == null ||
10944                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10945                                && pa.mPref.mAlways)) {
10946                    if (removed == null) {
10947                        removed = new ArrayList<PreferredActivity>();
10948                    }
10949                    removed.add(pa);
10950                }
10951            }
10952            if (removed != null) {
10953                for (int j=0; j<removed.size(); j++) {
10954                    PreferredActivity pa = removed.get(j);
10955                    pir.removeFilter(pa);
10956                }
10957                changed = true;
10958            }
10959        }
10960        return changed;
10961    }
10962
10963    @Override
10964    public void resetPreferredActivities(int userId) {
10965        mContext.enforceCallingOrSelfPermission(
10966                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10967        // writer
10968        synchronized (mPackages) {
10969            int user = UserHandle.getCallingUserId();
10970            clearPackagePreferredActivitiesLPw(null, user);
10971            mSettings.readDefaultPreferredAppsLPw(this, user);
10972            mSettings.writePackageRestrictionsLPr(user);
10973            scheduleWriteSettingsLocked();
10974        }
10975    }
10976
10977    @Override
10978    public int getPreferredActivities(List<IntentFilter> outFilters,
10979            List<ComponentName> outActivities, String packageName) {
10980
10981        int num = 0;
10982        final int userId = UserHandle.getCallingUserId();
10983        // reader
10984        synchronized (mPackages) {
10985            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10986            if (pir != null) {
10987                final Iterator<PreferredActivity> it = pir.filterIterator();
10988                while (it.hasNext()) {
10989                    final PreferredActivity pa = it.next();
10990                    if (packageName == null
10991                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10992                                    && pa.mPref.mAlways)) {
10993                        if (outFilters != null) {
10994                            outFilters.add(new IntentFilter(pa));
10995                        }
10996                        if (outActivities != null) {
10997                            outActivities.add(pa.mPref.mComponent);
10998                        }
10999                    }
11000                }
11001            }
11002        }
11003
11004        return num;
11005    }
11006
11007    @Override
11008    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11009        Intent intent = new Intent(Intent.ACTION_MAIN);
11010        intent.addCategory(Intent.CATEGORY_HOME);
11011
11012        final int callingUserId = UserHandle.getCallingUserId();
11013        List<ResolveInfo> list = queryIntentActivities(intent, null,
11014                PackageManager.GET_META_DATA, callingUserId);
11015        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11016                true, false, false, callingUserId);
11017
11018        allHomeCandidates.clear();
11019        if (list != null) {
11020            for (ResolveInfo ri : list) {
11021                allHomeCandidates.add(ri);
11022            }
11023        }
11024        return (preferred == null || preferred.activityInfo == null)
11025                ? null
11026                : new ComponentName(preferred.activityInfo.packageName,
11027                        preferred.activityInfo.name);
11028    }
11029
11030    @Override
11031    public void setApplicationEnabledSetting(String appPackageName,
11032            int newState, int flags, int userId, String callingPackage) {
11033        if (!sUserManager.exists(userId)) return;
11034        if (callingPackage == null) {
11035            callingPackage = Integer.toString(Binder.getCallingUid());
11036        }
11037        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11038    }
11039
11040    @Override
11041    public void setComponentEnabledSetting(ComponentName componentName,
11042            int newState, int flags, int userId) {
11043        if (!sUserManager.exists(userId)) return;
11044        setEnabledSetting(componentName.getPackageName(),
11045                componentName.getClassName(), newState, flags, userId, null);
11046    }
11047
11048    private void setEnabledSetting(final String packageName, String className, int newState,
11049            final int flags, int userId, String callingPackage) {
11050        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11051              || newState == COMPONENT_ENABLED_STATE_ENABLED
11052              || newState == COMPONENT_ENABLED_STATE_DISABLED
11053              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11054              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11055            throw new IllegalArgumentException("Invalid new component state: "
11056                    + newState);
11057        }
11058        PackageSetting pkgSetting;
11059        final int uid = Binder.getCallingUid();
11060        final int permission = mContext.checkCallingOrSelfPermission(
11061                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11062        enforceCrossUserPermission(uid, userId, false, "set enabled");
11063        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11064        boolean sendNow = false;
11065        boolean isApp = (className == null);
11066        String componentName = isApp ? packageName : className;
11067        int packageUid = -1;
11068        ArrayList<String> components;
11069
11070        // writer
11071        synchronized (mPackages) {
11072            pkgSetting = mSettings.mPackages.get(packageName);
11073            if (pkgSetting == null) {
11074                if (className == null) {
11075                    throw new IllegalArgumentException(
11076                            "Unknown package: " + packageName);
11077                }
11078                throw new IllegalArgumentException(
11079                        "Unknown component: " + packageName
11080                        + "/" + className);
11081            }
11082            // Allow root and verify that userId is not being specified by a different user
11083            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11084                throw new SecurityException(
11085                        "Permission Denial: attempt to change component state from pid="
11086                        + Binder.getCallingPid()
11087                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11088            }
11089            if (className == null) {
11090                // We're dealing with an application/package level state change
11091                if (pkgSetting.getEnabled(userId) == newState) {
11092                    // Nothing to do
11093                    return;
11094                }
11095                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11096                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11097                    // Don't care about who enables an app.
11098                    callingPackage = null;
11099                }
11100                pkgSetting.setEnabled(newState, userId, callingPackage);
11101                // pkgSetting.pkg.mSetEnabled = newState;
11102            } else {
11103                // We're dealing with a component level state change
11104                // First, verify that this is a valid class name.
11105                PackageParser.Package pkg = pkgSetting.pkg;
11106                if (pkg == null || !pkg.hasComponentClassName(className)) {
11107                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11108                        throw new IllegalArgumentException("Component class " + className
11109                                + " does not exist in " + packageName);
11110                    } else {
11111                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11112                                + className + " does not exist in " + packageName);
11113                    }
11114                }
11115                switch (newState) {
11116                case COMPONENT_ENABLED_STATE_ENABLED:
11117                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11118                        return;
11119                    }
11120                    break;
11121                case COMPONENT_ENABLED_STATE_DISABLED:
11122                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11123                        return;
11124                    }
11125                    break;
11126                case COMPONENT_ENABLED_STATE_DEFAULT:
11127                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11128                        return;
11129                    }
11130                    break;
11131                default:
11132                    Slog.e(TAG, "Invalid new component state: " + newState);
11133                    return;
11134                }
11135            }
11136            mSettings.writePackageRestrictionsLPr(userId);
11137            components = mPendingBroadcasts.get(userId, packageName);
11138            final boolean newPackage = components == null;
11139            if (newPackage) {
11140                components = new ArrayList<String>();
11141            }
11142            if (!components.contains(componentName)) {
11143                components.add(componentName);
11144            }
11145            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11146                sendNow = true;
11147                // Purge entry from pending broadcast list if another one exists already
11148                // since we are sending one right away.
11149                mPendingBroadcasts.remove(userId, packageName);
11150            } else {
11151                if (newPackage) {
11152                    mPendingBroadcasts.put(userId, packageName, components);
11153                }
11154                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11155                    // Schedule a message
11156                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11157                }
11158            }
11159        }
11160
11161        long callingId = Binder.clearCallingIdentity();
11162        try {
11163            if (sendNow) {
11164                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11165                sendPackageChangedBroadcast(packageName,
11166                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11167            }
11168        } finally {
11169            Binder.restoreCallingIdentity(callingId);
11170        }
11171    }
11172
11173    private void sendPackageChangedBroadcast(String packageName,
11174            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11175        if (DEBUG_INSTALL)
11176            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11177                    + componentNames);
11178        Bundle extras = new Bundle(4);
11179        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11180        String nameList[] = new String[componentNames.size()];
11181        componentNames.toArray(nameList);
11182        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11183        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11184        extras.putInt(Intent.EXTRA_UID, packageUid);
11185        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11186                new int[] {UserHandle.getUserId(packageUid)});
11187    }
11188
11189    @Override
11190    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11191        if (!sUserManager.exists(userId)) return;
11192        final int uid = Binder.getCallingUid();
11193        final int permission = mContext.checkCallingOrSelfPermission(
11194                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11195        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11196        enforceCrossUserPermission(uid, userId, true, "stop package");
11197        // writer
11198        synchronized (mPackages) {
11199            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11200                    uid, userId)) {
11201                scheduleWritePackageRestrictionsLocked(userId);
11202            }
11203        }
11204    }
11205
11206    @Override
11207    public String getInstallerPackageName(String packageName) {
11208        // reader
11209        synchronized (mPackages) {
11210            return mSettings.getInstallerPackageNameLPr(packageName);
11211        }
11212    }
11213
11214    @Override
11215    public int getApplicationEnabledSetting(String packageName, int userId) {
11216        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11217        int uid = Binder.getCallingUid();
11218        enforceCrossUserPermission(uid, userId, false, "get enabled");
11219        // reader
11220        synchronized (mPackages) {
11221            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11222        }
11223    }
11224
11225    @Override
11226    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11227        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11228        int uid = Binder.getCallingUid();
11229        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11230        // reader
11231        synchronized (mPackages) {
11232            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11233        }
11234    }
11235
11236    @Override
11237    public void enterSafeMode() {
11238        enforceSystemOrRoot("Only the system can request entering safe mode");
11239
11240        if (!mSystemReady) {
11241            mSafeMode = true;
11242        }
11243    }
11244
11245    @Override
11246    public void systemReady() {
11247        mSystemReady = true;
11248
11249        // Read the compatibilty setting when the system is ready.
11250        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11251                mContext.getContentResolver(),
11252                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11253        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11254        if (DEBUG_SETTINGS) {
11255            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11256        }
11257
11258        synchronized (mPackages) {
11259            // Verify that all of the preferred activity components actually
11260            // exist.  It is possible for applications to be updated and at
11261            // that point remove a previously declared activity component that
11262            // had been set as a preferred activity.  We try to clean this up
11263            // the next time we encounter that preferred activity, but it is
11264            // possible for the user flow to never be able to return to that
11265            // situation so here we do a sanity check to make sure we haven't
11266            // left any junk around.
11267            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11268            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11269                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11270                removed.clear();
11271                for (PreferredActivity pa : pir.filterSet()) {
11272                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11273                        removed.add(pa);
11274                    }
11275                }
11276                if (removed.size() > 0) {
11277                    for (int j=0; j<removed.size(); j++) {
11278                        PreferredActivity pa = removed.get(i);
11279                        Slog.w(TAG, "Removing dangling preferred activity: "
11280                                + pa.mPref.mComponent);
11281                        pir.removeFilter(pa);
11282                    }
11283                    mSettings.writePackageRestrictionsLPr(
11284                            mSettings.mPreferredActivities.keyAt(i));
11285                }
11286            }
11287        }
11288        sUserManager.systemReady();
11289    }
11290
11291    @Override
11292    public boolean isSafeMode() {
11293        return mSafeMode;
11294    }
11295
11296    @Override
11297    public boolean hasSystemUidErrors() {
11298        return mHasSystemUidErrors;
11299    }
11300
11301    static String arrayToString(int[] array) {
11302        StringBuffer buf = new StringBuffer(128);
11303        buf.append('[');
11304        if (array != null) {
11305            for (int i=0; i<array.length; i++) {
11306                if (i > 0) buf.append(", ");
11307                buf.append(array[i]);
11308            }
11309        }
11310        buf.append(']');
11311        return buf.toString();
11312    }
11313
11314    static class DumpState {
11315        public static final int DUMP_LIBS = 1 << 0;
11316
11317        public static final int DUMP_FEATURES = 1 << 1;
11318
11319        public static final int DUMP_RESOLVERS = 1 << 2;
11320
11321        public static final int DUMP_PERMISSIONS = 1 << 3;
11322
11323        public static final int DUMP_PACKAGES = 1 << 4;
11324
11325        public static final int DUMP_SHARED_USERS = 1 << 5;
11326
11327        public static final int DUMP_MESSAGES = 1 << 6;
11328
11329        public static final int DUMP_PROVIDERS = 1 << 7;
11330
11331        public static final int DUMP_VERIFIERS = 1 << 8;
11332
11333        public static final int DUMP_PREFERRED = 1 << 9;
11334
11335        public static final int DUMP_PREFERRED_XML = 1 << 10;
11336
11337        public static final int DUMP_KEYSETS = 1 << 11;
11338
11339        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11340
11341        private int mTypes;
11342
11343        private int mOptions;
11344
11345        private boolean mTitlePrinted;
11346
11347        private SharedUserSetting mSharedUser;
11348
11349        public boolean isDumping(int type) {
11350            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11351                return true;
11352            }
11353
11354            return (mTypes & type) != 0;
11355        }
11356
11357        public void setDump(int type) {
11358            mTypes |= type;
11359        }
11360
11361        public boolean isOptionEnabled(int option) {
11362            return (mOptions & option) != 0;
11363        }
11364
11365        public void setOptionEnabled(int option) {
11366            mOptions |= option;
11367        }
11368
11369        public boolean onTitlePrinted() {
11370            final boolean printed = mTitlePrinted;
11371            mTitlePrinted = true;
11372            return printed;
11373        }
11374
11375        public boolean getTitlePrinted() {
11376            return mTitlePrinted;
11377        }
11378
11379        public void setTitlePrinted(boolean enabled) {
11380            mTitlePrinted = enabled;
11381        }
11382
11383        public SharedUserSetting getSharedUser() {
11384            return mSharedUser;
11385        }
11386
11387        public void setSharedUser(SharedUserSetting user) {
11388            mSharedUser = user;
11389        }
11390    }
11391
11392    @Override
11393    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11394        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11395                != PackageManager.PERMISSION_GRANTED) {
11396            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11397                    + Binder.getCallingPid()
11398                    + ", uid=" + Binder.getCallingUid()
11399                    + " without permission "
11400                    + android.Manifest.permission.DUMP);
11401            return;
11402        }
11403
11404        DumpState dumpState = new DumpState();
11405        boolean fullPreferred = false;
11406        boolean checkin = false;
11407
11408        String packageName = null;
11409
11410        int opti = 0;
11411        while (opti < args.length) {
11412            String opt = args[opti];
11413            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11414                break;
11415            }
11416            opti++;
11417            if ("-a".equals(opt)) {
11418                // Right now we only know how to print all.
11419            } else if ("-h".equals(opt)) {
11420                pw.println("Package manager dump options:");
11421                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11422                pw.println("    --checkin: dump for a checkin");
11423                pw.println("    -f: print details of intent filters");
11424                pw.println("    -h: print this help");
11425                pw.println("  cmd may be one of:");
11426                pw.println("    l[ibraries]: list known shared libraries");
11427                pw.println("    f[ibraries]: list device features");
11428                pw.println("    r[esolvers]: dump intent resolvers");
11429                pw.println("    perm[issions]: dump permissions");
11430                pw.println("    pref[erred]: print preferred package settings");
11431                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11432                pw.println("    prov[iders]: dump content providers");
11433                pw.println("    p[ackages]: dump installed packages");
11434                pw.println("    s[hared-users]: dump shared user IDs");
11435                pw.println("    m[essages]: print collected runtime messages");
11436                pw.println("    v[erifiers]: print package verifier info");
11437                pw.println("    <package.name>: info about given package");
11438                pw.println("    k[eysets]: print known keysets");
11439                return;
11440            } else if ("--checkin".equals(opt)) {
11441                checkin = true;
11442            } else if ("-f".equals(opt)) {
11443                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11444            } else {
11445                pw.println("Unknown argument: " + opt + "; use -h for help");
11446            }
11447        }
11448
11449        // Is the caller requesting to dump a particular piece of data?
11450        if (opti < args.length) {
11451            String cmd = args[opti];
11452            opti++;
11453            // Is this a package name?
11454            if ("android".equals(cmd) || cmd.contains(".")) {
11455                packageName = cmd;
11456                // When dumping a single package, we always dump all of its
11457                // filter information since the amount of data will be reasonable.
11458                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11459            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11460                dumpState.setDump(DumpState.DUMP_LIBS);
11461            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11462                dumpState.setDump(DumpState.DUMP_FEATURES);
11463            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11464                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11465            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11466                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11467            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11468                dumpState.setDump(DumpState.DUMP_PREFERRED);
11469            } else if ("preferred-xml".equals(cmd)) {
11470                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11471                if (opti < args.length && "--full".equals(args[opti])) {
11472                    fullPreferred = true;
11473                    opti++;
11474                }
11475            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11476                dumpState.setDump(DumpState.DUMP_PACKAGES);
11477            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11478                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11479            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11480                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11481            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11482                dumpState.setDump(DumpState.DUMP_MESSAGES);
11483            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11484                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11485            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11486                dumpState.setDump(DumpState.DUMP_KEYSETS);
11487            }
11488        }
11489
11490        if (checkin) {
11491            pw.println("vers,1");
11492        }
11493
11494        // reader
11495        synchronized (mPackages) {
11496            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11497                if (!checkin) {
11498                    if (dumpState.onTitlePrinted())
11499                        pw.println();
11500                    pw.println("Verifiers:");
11501                    pw.print("  Required: ");
11502                    pw.print(mRequiredVerifierPackage);
11503                    pw.print(" (uid=");
11504                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11505                    pw.println(")");
11506                } else if (mRequiredVerifierPackage != null) {
11507                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11508                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11509                }
11510            }
11511
11512            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11513                boolean printedHeader = false;
11514                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11515                while (it.hasNext()) {
11516                    String name = it.next();
11517                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11518                    if (!checkin) {
11519                        if (!printedHeader) {
11520                            if (dumpState.onTitlePrinted())
11521                                pw.println();
11522                            pw.println("Libraries:");
11523                            printedHeader = true;
11524                        }
11525                        pw.print("  ");
11526                    } else {
11527                        pw.print("lib,");
11528                    }
11529                    pw.print(name);
11530                    if (!checkin) {
11531                        pw.print(" -> ");
11532                    }
11533                    if (ent.path != null) {
11534                        if (!checkin) {
11535                            pw.print("(jar) ");
11536                            pw.print(ent.path);
11537                        } else {
11538                            pw.print(",jar,");
11539                            pw.print(ent.path);
11540                        }
11541                    } else {
11542                        if (!checkin) {
11543                            pw.print("(apk) ");
11544                            pw.print(ent.apk);
11545                        } else {
11546                            pw.print(",apk,");
11547                            pw.print(ent.apk);
11548                        }
11549                    }
11550                    pw.println();
11551                }
11552            }
11553
11554            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11555                if (dumpState.onTitlePrinted())
11556                    pw.println();
11557                if (!checkin) {
11558                    pw.println("Features:");
11559                }
11560                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11561                while (it.hasNext()) {
11562                    String name = it.next();
11563                    if (!checkin) {
11564                        pw.print("  ");
11565                    } else {
11566                        pw.print("feat,");
11567                    }
11568                    pw.println(name);
11569                }
11570            }
11571
11572            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11573                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11574                        : "Activity Resolver Table:", "  ", packageName,
11575                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11576                    dumpState.setTitlePrinted(true);
11577                }
11578                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11579                        : "Receiver Resolver Table:", "  ", packageName,
11580                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11581                    dumpState.setTitlePrinted(true);
11582                }
11583                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11584                        : "Service Resolver Table:", "  ", packageName,
11585                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11586                    dumpState.setTitlePrinted(true);
11587                }
11588                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11589                        : "Provider Resolver Table:", "  ", packageName,
11590                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11591                    dumpState.setTitlePrinted(true);
11592                }
11593            }
11594
11595            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11596                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11597                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11598                    int user = mSettings.mPreferredActivities.keyAt(i);
11599                    if (pir.dump(pw,
11600                            dumpState.getTitlePrinted()
11601                                ? "\nPreferred Activities User " + user + ":"
11602                                : "Preferred Activities User " + user + ":", "  ",
11603                            packageName, true)) {
11604                        dumpState.setTitlePrinted(true);
11605                    }
11606                }
11607            }
11608
11609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11610                pw.flush();
11611                FileOutputStream fout = new FileOutputStream(fd);
11612                BufferedOutputStream str = new BufferedOutputStream(fout);
11613                XmlSerializer serializer = new FastXmlSerializer();
11614                try {
11615                    serializer.setOutput(str, "utf-8");
11616                    serializer.startDocument(null, true);
11617                    serializer.setFeature(
11618                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11619                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11620                    serializer.endDocument();
11621                    serializer.flush();
11622                } catch (IllegalArgumentException e) {
11623                    pw.println("Failed writing: " + e);
11624                } catch (IllegalStateException e) {
11625                    pw.println("Failed writing: " + e);
11626                } catch (IOException e) {
11627                    pw.println("Failed writing: " + e);
11628                }
11629            }
11630
11631            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11632                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11633            }
11634
11635            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11636                boolean printedSomething = false;
11637                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11638                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11639                        continue;
11640                    }
11641                    if (!printedSomething) {
11642                        if (dumpState.onTitlePrinted())
11643                            pw.println();
11644                        pw.println("Registered ContentProviders:");
11645                        printedSomething = true;
11646                    }
11647                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11648                    pw.print("    "); pw.println(p.toString());
11649                }
11650                printedSomething = false;
11651                for (Map.Entry<String, PackageParser.Provider> entry :
11652                        mProvidersByAuthority.entrySet()) {
11653                    PackageParser.Provider p = entry.getValue();
11654                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11655                        continue;
11656                    }
11657                    if (!printedSomething) {
11658                        if (dumpState.onTitlePrinted())
11659                            pw.println();
11660                        pw.println("ContentProvider Authorities:");
11661                        printedSomething = true;
11662                    }
11663                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11664                    pw.print("    "); pw.println(p.toString());
11665                    if (p.info != null && p.info.applicationInfo != null) {
11666                        final String appInfo = p.info.applicationInfo.toString();
11667                        pw.print("      applicationInfo="); pw.println(appInfo);
11668                    }
11669                }
11670            }
11671
11672            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11673                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11674            }
11675
11676            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11677                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11678            }
11679
11680            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11681                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11682            }
11683
11684            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11685                if (dumpState.onTitlePrinted())
11686                    pw.println();
11687                mSettings.dumpReadMessagesLPr(pw, dumpState);
11688
11689                pw.println();
11690                pw.println("Package warning messages:");
11691                final File fname = getSettingsProblemFile();
11692                FileInputStream in = null;
11693                try {
11694                    in = new FileInputStream(fname);
11695                    final int avail = in.available();
11696                    final byte[] data = new byte[avail];
11697                    in.read(data);
11698                    pw.print(new String(data));
11699                } catch (FileNotFoundException e) {
11700                } catch (IOException e) {
11701                } finally {
11702                    if (in != null) {
11703                        try {
11704                            in.close();
11705                        } catch (IOException e) {
11706                        }
11707                    }
11708                }
11709            }
11710        }
11711    }
11712
11713    // ------- apps on sdcard specific code -------
11714    static final boolean DEBUG_SD_INSTALL = false;
11715
11716    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11717
11718    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11719
11720    private boolean mMediaMounted = false;
11721
11722    private String getEncryptKey() {
11723        try {
11724            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11725                    SD_ENCRYPTION_KEYSTORE_NAME);
11726            if (sdEncKey == null) {
11727                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11728                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11729                if (sdEncKey == null) {
11730                    Slog.e(TAG, "Failed to create encryption keys");
11731                    return null;
11732                }
11733            }
11734            return sdEncKey;
11735        } catch (NoSuchAlgorithmException nsae) {
11736            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11737            return null;
11738        } catch (IOException ioe) {
11739            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11740            return null;
11741        }
11742
11743    }
11744
11745    /* package */static String getTempContainerId() {
11746        int tmpIdx = 1;
11747        String list[] = PackageHelper.getSecureContainerList();
11748        if (list != null) {
11749            for (final String name : list) {
11750                // Ignore null and non-temporary container entries
11751                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11752                    continue;
11753                }
11754
11755                String subStr = name.substring(mTempContainerPrefix.length());
11756                try {
11757                    int cid = Integer.parseInt(subStr);
11758                    if (cid >= tmpIdx) {
11759                        tmpIdx = cid + 1;
11760                    }
11761                } catch (NumberFormatException e) {
11762                }
11763            }
11764        }
11765        return mTempContainerPrefix + tmpIdx;
11766    }
11767
11768    /*
11769     * Update media status on PackageManager.
11770     */
11771    @Override
11772    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11773        int callingUid = Binder.getCallingUid();
11774        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11775            throw new SecurityException("Media status can only be updated by the system");
11776        }
11777        // reader; this apparently protects mMediaMounted, but should probably
11778        // be a different lock in that case.
11779        synchronized (mPackages) {
11780            Log.i(TAG, "Updating external media status from "
11781                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11782                    + (mediaStatus ? "mounted" : "unmounted"));
11783            if (DEBUG_SD_INSTALL)
11784                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11785                        + ", mMediaMounted=" + mMediaMounted);
11786            if (mediaStatus == mMediaMounted) {
11787                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11788                        : 0, -1);
11789                mHandler.sendMessage(msg);
11790                return;
11791            }
11792            mMediaMounted = mediaStatus;
11793        }
11794        // Queue up an async operation since the package installation may take a
11795        // little while.
11796        mHandler.post(new Runnable() {
11797            public void run() {
11798                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11799            }
11800        });
11801    }
11802
11803    /**
11804     * Called by MountService when the initial ASECs to scan are available.
11805     * Should block until all the ASEC containers are finished being scanned.
11806     */
11807    public void scanAvailableAsecs() {
11808        updateExternalMediaStatusInner(true, false, false);
11809        if (mShouldRestoreconData) {
11810            SELinuxMMAC.setRestoreconDone();
11811            mShouldRestoreconData = false;
11812        }
11813    }
11814
11815    /*
11816     * Collect information of applications on external media, map them against
11817     * existing containers and update information based on current mount status.
11818     * Please note that we always have to report status if reportStatus has been
11819     * set to true especially when unloading packages.
11820     */
11821    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11822            boolean externalStorage) {
11823        // Collection of uids
11824        int uidArr[] = null;
11825        // Collection of stale containers
11826        HashSet<String> removeCids = new HashSet<String>();
11827        // Collection of packages on external media with valid containers.
11828        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11829        // Get list of secure containers.
11830        final String list[] = PackageHelper.getSecureContainerList();
11831        if (list == null || list.length == 0) {
11832            Log.i(TAG, "No secure containers on sdcard");
11833        } else {
11834            // Process list of secure containers and categorize them
11835            // as active or stale based on their package internal state.
11836            int uidList[] = new int[list.length];
11837            int num = 0;
11838            // reader
11839            synchronized (mPackages) {
11840                for (String cid : list) {
11841                    if (DEBUG_SD_INSTALL)
11842                        Log.i(TAG, "Processing container " + cid);
11843                    String pkgName = getAsecPackageName(cid);
11844                    if (pkgName == null) {
11845                        if (DEBUG_SD_INSTALL)
11846                            Log.i(TAG, "Container : " + cid + " stale");
11847                        removeCids.add(cid);
11848                        continue;
11849                    }
11850                    if (DEBUG_SD_INSTALL)
11851                        Log.i(TAG, "Looking for pkg : " + pkgName);
11852
11853                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11854                    if (ps == null) {
11855                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11856                        removeCids.add(cid);
11857                        continue;
11858                    }
11859
11860                    /*
11861                     * Skip packages that are not external if we're unmounting
11862                     * external storage.
11863                     */
11864                    if (externalStorage && !isMounted && !isExternal(ps)) {
11865                        continue;
11866                    }
11867
11868                    final AsecInstallArgs args = new AsecInstallArgs(cid,
11869                            getAppInstructionSetFromSettings(ps),
11870                            isForwardLocked(ps));
11871                    // The package status is changed only if the code path
11872                    // matches between settings and the container id.
11873                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11874                        if (DEBUG_SD_INSTALL) {
11875                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11876                                    + " at code path: " + ps.codePathString);
11877                        }
11878
11879                        // We do have a valid package installed on sdcard
11880                        processCids.put(args, ps.codePathString);
11881                        final int uid = ps.appId;
11882                        if (uid != -1) {
11883                            uidList[num++] = uid;
11884                        }
11885                    } else {
11886                        Log.i(TAG, "Deleting stale container for " + cid);
11887                        removeCids.add(cid);
11888                    }
11889                }
11890            }
11891
11892            if (num > 0) {
11893                // Sort uid list
11894                Arrays.sort(uidList, 0, num);
11895                // Throw away duplicates
11896                uidArr = new int[num];
11897                uidArr[0] = uidList[0];
11898                int di = 0;
11899                for (int i = 1; i < num; i++) {
11900                    if (uidList[i - 1] != uidList[i]) {
11901                        uidArr[di++] = uidList[i];
11902                    }
11903                }
11904            }
11905        }
11906        // Process packages with valid entries.
11907        if (isMounted) {
11908            if (DEBUG_SD_INSTALL)
11909                Log.i(TAG, "Loading packages");
11910            loadMediaPackages(processCids, uidArr, removeCids);
11911            startCleaningPackages();
11912        } else {
11913            if (DEBUG_SD_INSTALL)
11914                Log.i(TAG, "Unloading packages");
11915            unloadMediaPackages(processCids, uidArr, reportStatus);
11916        }
11917    }
11918
11919   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11920           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11921        int size = pkgList.size();
11922        if (size > 0) {
11923            // Send broadcasts here
11924            Bundle extras = new Bundle();
11925            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11926                    .toArray(new String[size]));
11927            if (uidArr != null) {
11928                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11929            }
11930            if (replacing) {
11931                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11932            }
11933            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11934                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11935            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11936        }
11937    }
11938
11939   /*
11940     * Look at potentially valid container ids from processCids If package
11941     * information doesn't match the one on record or package scanning fails,
11942     * the cid is added to list of removeCids. We currently don't delete stale
11943     * containers.
11944     */
11945   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11946            HashSet<String> removeCids) {
11947        ArrayList<String> pkgList = new ArrayList<String>();
11948        Set<AsecInstallArgs> keys = processCids.keySet();
11949        boolean doGc = false;
11950        for (AsecInstallArgs args : keys) {
11951            String codePath = processCids.get(args);
11952            if (DEBUG_SD_INSTALL)
11953                Log.i(TAG, "Loading container : " + args.cid);
11954            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11955            try {
11956                // Make sure there are no container errors first.
11957                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11958                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11959                            + " when installing from sdcard");
11960                    continue;
11961                }
11962                // Check code path here.
11963                if (codePath == null || !codePath.equals(args.getCodePath())) {
11964                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11965                            + " does not match one in settings " + codePath);
11966                    continue;
11967                }
11968                // Parse package
11969                int parseFlags = mDefParseFlags;
11970                if (args.isExternal()) {
11971                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11972                }
11973                if (args.isFwdLocked()) {
11974                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11975                }
11976
11977                doGc = true;
11978                synchronized (mInstallLock) {
11979                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11980                            0, 0, null, null);
11981                    // Scan the package
11982                    if (pkg != null) {
11983                        /*
11984                         * TODO why is the lock being held? doPostInstall is
11985                         * called in other places without the lock. This needs
11986                         * to be straightened out.
11987                         */
11988                        // writer
11989                        synchronized (mPackages) {
11990                            retCode = PackageManager.INSTALL_SUCCEEDED;
11991                            pkgList.add(pkg.packageName);
11992                            // Post process args
11993                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11994                                    pkg.applicationInfo.uid);
11995                        }
11996                    } else {
11997                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11998                    }
11999                }
12000
12001            } finally {
12002                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12003                    // Don't destroy container here. Wait till gc clears things
12004                    // up.
12005                    removeCids.add(args.cid);
12006                }
12007            }
12008        }
12009        // writer
12010        synchronized (mPackages) {
12011            // If the platform SDK has changed since the last time we booted,
12012            // we need to re-grant app permission to catch any new ones that
12013            // appear. This is really a hack, and means that apps can in some
12014            // cases get permissions that the user didn't initially explicitly
12015            // allow... it would be nice to have some better way to handle
12016            // this situation.
12017            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12018            if (regrantPermissions)
12019                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12020                        + mSdkVersion + "; regranting permissions for external storage");
12021            mSettings.mExternalSdkPlatform = mSdkVersion;
12022
12023            // Make sure group IDs have been assigned, and any permission
12024            // changes in other apps are accounted for
12025            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12026                    | (regrantPermissions
12027                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12028                            : 0));
12029            // can downgrade to reader
12030            // Persist settings
12031            mSettings.writeLPr();
12032        }
12033        // Send a broadcast to let everyone know we are done processing
12034        if (pkgList.size() > 0) {
12035            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12036        }
12037        // Force gc to avoid any stale parser references that we might have.
12038        if (doGc) {
12039            Runtime.getRuntime().gc();
12040        }
12041        // List stale containers and destroy stale temporary containers.
12042        if (removeCids != null) {
12043            for (String cid : removeCids) {
12044                if (cid.startsWith(mTempContainerPrefix)) {
12045                    Log.i(TAG, "Destroying stale temporary container " + cid);
12046                    PackageHelper.destroySdDir(cid);
12047                } else {
12048                    Log.w(TAG, "Container " + cid + " is stale");
12049               }
12050           }
12051        }
12052    }
12053
12054   /*
12055     * Utility method to unload a list of specified containers
12056     */
12057    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12058        // Just unmount all valid containers.
12059        for (AsecInstallArgs arg : cidArgs) {
12060            synchronized (mInstallLock) {
12061                arg.doPostDeleteLI(false);
12062           }
12063       }
12064   }
12065
12066    /*
12067     * Unload packages mounted on external media. This involves deleting package
12068     * data from internal structures, sending broadcasts about diabled packages,
12069     * gc'ing to free up references, unmounting all secure containers
12070     * corresponding to packages on external media, and posting a
12071     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12072     * that we always have to post this message if status has been requested no
12073     * matter what.
12074     */
12075    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12076            final boolean reportStatus) {
12077        if (DEBUG_SD_INSTALL)
12078            Log.i(TAG, "unloading media packages");
12079        ArrayList<String> pkgList = new ArrayList<String>();
12080        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12081        final Set<AsecInstallArgs> keys = processCids.keySet();
12082        for (AsecInstallArgs args : keys) {
12083            String pkgName = args.getPackageName();
12084            if (DEBUG_SD_INSTALL)
12085                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12086            // Delete package internally
12087            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12088            synchronized (mInstallLock) {
12089                boolean res = deletePackageLI(pkgName, null, false, null, null,
12090                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12091                if (res) {
12092                    pkgList.add(pkgName);
12093                } else {
12094                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12095                    failedList.add(args);
12096                }
12097            }
12098        }
12099
12100        // reader
12101        synchronized (mPackages) {
12102            // We didn't update the settings after removing each package;
12103            // write them now for all packages.
12104            mSettings.writeLPr();
12105        }
12106
12107        // We have to absolutely send UPDATED_MEDIA_STATUS only
12108        // after confirming that all the receivers processed the ordered
12109        // broadcast when packages get disabled, force a gc to clean things up.
12110        // and unload all the containers.
12111        if (pkgList.size() > 0) {
12112            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12113                    new IIntentReceiver.Stub() {
12114                public void performReceive(Intent intent, int resultCode, String data,
12115                        Bundle extras, boolean ordered, boolean sticky,
12116                        int sendingUser) throws RemoteException {
12117                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12118                            reportStatus ? 1 : 0, 1, keys);
12119                    mHandler.sendMessage(msg);
12120                }
12121            });
12122        } else {
12123            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12124                    keys);
12125            mHandler.sendMessage(msg);
12126        }
12127    }
12128
12129    /** Binder call */
12130    @Override
12131    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12132            final int flags) {
12133        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12134        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12135        int returnCode = PackageManager.MOVE_SUCCEEDED;
12136        int currFlags = 0;
12137        int newFlags = 0;
12138        // reader
12139        synchronized (mPackages) {
12140            PackageParser.Package pkg = mPackages.get(packageName);
12141            if (pkg == null) {
12142                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12143            } else {
12144                // Disable moving fwd locked apps and system packages
12145                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12146                    Slog.w(TAG, "Cannot move system application");
12147                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12148                } else if (pkg.mOperationPending) {
12149                    Slog.w(TAG, "Attempt to move package which has pending operations");
12150                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12151                } else {
12152                    // Find install location first
12153                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12154                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12155                        Slog.w(TAG, "Ambigous flags specified for move location.");
12156                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12157                    } else {
12158                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12159                                : PackageManager.INSTALL_INTERNAL;
12160                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12161                                : PackageManager.INSTALL_INTERNAL;
12162
12163                        if (newFlags == currFlags) {
12164                            Slog.w(TAG, "No move required. Trying to move to same location");
12165                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12166                        } else {
12167                            if (isForwardLocked(pkg)) {
12168                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12169                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12170                            }
12171                        }
12172                    }
12173                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12174                        pkg.mOperationPending = true;
12175                    }
12176                }
12177            }
12178
12179            /*
12180             * TODO this next block probably shouldn't be inside the lock. We
12181             * can't guarantee these won't change after this is fired off
12182             * anyway.
12183             */
12184            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12185                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12186                        null, -1, user),
12187                        returnCode);
12188            } else {
12189                Message msg = mHandler.obtainMessage(INIT_COPY);
12190                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12191                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12192                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12193                        instructionSet);
12194                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12195                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12196                msg.obj = mp;
12197                mHandler.sendMessage(msg);
12198            }
12199        }
12200    }
12201
12202    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12203        // Queue up an async operation since the package deletion may take a
12204        // little while.
12205        mHandler.post(new Runnable() {
12206            public void run() {
12207                // TODO fix this; this does nothing.
12208                mHandler.removeCallbacks(this);
12209                int returnCode = currentStatus;
12210                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12211                    int uidArr[] = null;
12212                    ArrayList<String> pkgList = null;
12213                    synchronized (mPackages) {
12214                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12215                        if (pkg == null) {
12216                            Slog.w(TAG, " Package " + mp.packageName
12217                                    + " doesn't exist. Aborting move");
12218                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12219                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12220                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12221                                    + mp.srcArgs.getCodePath() + " to "
12222                                    + pkg.applicationInfo.sourceDir
12223                                    + " Aborting move and returning error");
12224                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12225                        } else {
12226                            uidArr = new int[] {
12227                                pkg.applicationInfo.uid
12228                            };
12229                            pkgList = new ArrayList<String>();
12230                            pkgList.add(mp.packageName);
12231                        }
12232                    }
12233                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12234                        // Send resources unavailable broadcast
12235                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12236                        // Update package code and resource paths
12237                        synchronized (mInstallLock) {
12238                            synchronized (mPackages) {
12239                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12240                                // Recheck for package again.
12241                                if (pkg == null) {
12242                                    Slog.w(TAG, " Package " + mp.packageName
12243                                            + " doesn't exist. Aborting move");
12244                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12245                                } else if (!mp.srcArgs.getCodePath().equals(
12246                                        pkg.applicationInfo.sourceDir)) {
12247                                    Slog.w(TAG, "Package " + mp.packageName
12248                                            + " code path changed from " + mp.srcArgs.getCodePath()
12249                                            + " to " + pkg.applicationInfo.sourceDir
12250                                            + " Aborting move and returning error");
12251                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12252                                } else {
12253                                    final String oldCodePath = pkg.mPath;
12254                                    final String newCodePath = mp.targetArgs.getCodePath();
12255                                    final String newResPath = mp.targetArgs.getResourcePath();
12256                                    final String newNativePath = mp.targetArgs
12257                                            .getNativeLibraryPath();
12258
12259                                    final File newNativeDir = new File(newNativePath);
12260
12261                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12262                                        // NOTE: We do not report any errors from the APK scan and library
12263                                        // copy at this point.
12264                                        NativeLibraryHelper.ApkHandle handle =
12265                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12266                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12267                                                handle, Build.SUPPORTED_ABIS);
12268                                        if (abi >= 0) {
12269                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12270                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12271                                        }
12272                                        handle.close();
12273                                    }
12274                                    final int[] users = sUserManager.getUserIds();
12275                                    for (int user : users) {
12276                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12277                                                newNativePath, user) < 0) {
12278                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12279                                        }
12280                                    }
12281
12282                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12283                                        pkg.mPath = newCodePath;
12284                                        // Move dex files around
12285                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12286                                            // Moving of dex files failed. Set
12287                                            // error code and abort move.
12288                                            pkg.mPath = pkg.mScanPath;
12289                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12290                                        }
12291                                    }
12292
12293                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12294                                        pkg.mScanPath = newCodePath;
12295                                        pkg.applicationInfo.sourceDir = newCodePath;
12296                                        pkg.applicationInfo.publicSourceDir = newResPath;
12297                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12298                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12299                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12300                                        ps.codePathString = ps.codePath.getPath();
12301                                        ps.resourcePath = new File(
12302                                                pkg.applicationInfo.publicSourceDir);
12303                                        ps.resourcePathString = ps.resourcePath.getPath();
12304                                        ps.nativeLibraryPathString = newNativePath;
12305                                        // Set the application info flag
12306                                        // correctly.
12307                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12308                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12309                                        } else {
12310                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12311                                        }
12312                                        ps.setFlags(pkg.applicationInfo.flags);
12313                                        mAppDirs.remove(oldCodePath);
12314                                        mAppDirs.put(newCodePath, pkg);
12315                                        // Persist settings
12316                                        mSettings.writeLPr();
12317                                    }
12318                                }
12319                            }
12320                        }
12321                        // Send resources available broadcast
12322                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12323                    }
12324                }
12325                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12326                    // Clean up failed installation
12327                    if (mp.targetArgs != null) {
12328                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12329                                -1);
12330                    }
12331                } else {
12332                    // Force a gc to clear things up.
12333                    Runtime.getRuntime().gc();
12334                    // Delete older code
12335                    synchronized (mInstallLock) {
12336                        mp.srcArgs.doPostDeleteLI(true);
12337                    }
12338                }
12339
12340                // Allow more operations on this file if we didn't fail because
12341                // an operation was already pending for this package.
12342                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12343                    synchronized (mPackages) {
12344                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12345                        if (pkg != null) {
12346                            pkg.mOperationPending = false;
12347                       }
12348                   }
12349                }
12350
12351                IPackageMoveObserver observer = mp.observer;
12352                if (observer != null) {
12353                    try {
12354                        observer.packageMoved(mp.packageName, returnCode);
12355                    } catch (RemoteException e) {
12356                        Log.i(TAG, "Observer no longer exists.");
12357                    }
12358                }
12359            }
12360        });
12361    }
12362
12363    @Override
12364    public boolean setInstallLocation(int loc) {
12365        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12366                null);
12367        if (getInstallLocation() == loc) {
12368            return true;
12369        }
12370        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12371                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12372            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12373                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12374            return true;
12375        }
12376        return false;
12377   }
12378
12379    @Override
12380    public int getInstallLocation() {
12381        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12382                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12383                PackageHelper.APP_INSTALL_AUTO);
12384    }
12385
12386    /** Called by UserManagerService */
12387    void cleanUpUserLILPw(int userHandle) {
12388        mDirtyUsers.remove(userHandle);
12389        mSettings.removeUserLPr(userHandle);
12390        mPendingBroadcasts.remove(userHandle);
12391        if (mInstaller != null) {
12392            // Technically, we shouldn't be doing this with the package lock
12393            // held.  However, this is very rare, and there is already so much
12394            // other disk I/O going on, that we'll let it slide for now.
12395            mInstaller.removeUserDataDirs(userHandle);
12396        }
12397    }
12398
12399    /** Called by UserManagerService */
12400    void createNewUserLILPw(int userHandle, File path) {
12401        if (mInstaller != null) {
12402            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12403        }
12404    }
12405
12406    @Override
12407    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12408        mContext.enforceCallingOrSelfPermission(
12409                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12410                "Only package verification agents can read the verifier device identity");
12411
12412        synchronized (mPackages) {
12413            return mSettings.getVerifierDeviceIdentityLPw();
12414        }
12415    }
12416
12417    @Override
12418    public void setPermissionEnforced(String permission, boolean enforced) {
12419        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12420        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12421            synchronized (mPackages) {
12422                if (mSettings.mReadExternalStorageEnforced == null
12423                        || mSettings.mReadExternalStorageEnforced != enforced) {
12424                    mSettings.mReadExternalStorageEnforced = enforced;
12425                    mSettings.writeLPr();
12426                }
12427            }
12428            // kill any non-foreground processes so we restart them and
12429            // grant/revoke the GID.
12430            final IActivityManager am = ActivityManagerNative.getDefault();
12431            if (am != null) {
12432                final long token = Binder.clearCallingIdentity();
12433                try {
12434                    am.killProcessesBelowForeground("setPermissionEnforcement");
12435                } catch (RemoteException e) {
12436                } finally {
12437                    Binder.restoreCallingIdentity(token);
12438                }
12439            }
12440        } else {
12441            throw new IllegalArgumentException("No selective enforcement for " + permission);
12442        }
12443    }
12444
12445    @Override
12446    @Deprecated
12447    public boolean isPermissionEnforced(String permission) {
12448        return true;
12449    }
12450
12451    @Override
12452    public boolean isStorageLow() {
12453        final long token = Binder.clearCallingIdentity();
12454        try {
12455            final DeviceStorageMonitorInternal
12456                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12457            if (dsm != null) {
12458                return dsm.isMemoryLow();
12459            } else {
12460                return false;
12461            }
12462        } finally {
12463            Binder.restoreCallingIdentity(token);
12464        }
12465    }
12466}
12467