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