PackageManagerService.java revision d38aed81420d7d992f65ef2efb5f69c1900fc61d
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.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.PackageHelper;
44import com.android.internal.util.FastPrintWriter;
45import com.android.internal.util.FastXmlSerializer;
46import com.android.internal.util.XmlUtils;
47import com.android.server.EventLogTags;
48import com.android.server.IntentResolver;
49import com.android.server.LocalServices;
50import com.android.server.ServiceThread;
51import com.android.server.Watchdog;
52import com.android.server.pm.Settings.DatabaseVersion;
53import com.android.server.storage.DeviceStorageMonitorInternal;
54import com.android.server.storage.DeviceStorageMonitorInternal;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
59
60import android.app.ActivityManager;
61import android.app.ActivityManagerNative;
62import android.app.IActivityManager;
63import android.app.PackageInstallObserver;
64import android.app.admin.IDevicePolicyManager;
65import android.app.backup.IBackupManager;
66import android.content.BroadcastReceiver;
67import android.content.ComponentName;
68import android.content.Context;
69import android.content.IIntentReceiver;
70import android.content.Intent;
71import android.content.IntentFilter;
72import android.content.IntentSender;
73import android.content.IntentSender.SendIntentException;
74import android.content.ServiceConnection;
75import android.content.pm.ActivityInfo;
76import android.content.pm.ApplicationInfo;
77import android.content.pm.ContainerEncryptionParams;
78import android.content.pm.FeatureInfo;
79import android.content.pm.IPackageDataObserver;
80import android.content.pm.IPackageDeleteObserver;
81import android.content.pm.IPackageInstallObserver;
82import android.content.pm.IPackageInstallObserver2;
83import android.content.pm.IPackageInstaller;
84import android.content.pm.IPackageManager;
85import android.content.pm.IPackageMoveObserver;
86import android.content.pm.IPackageStatsObserver;
87import android.content.pm.InstrumentationInfo;
88import android.content.pm.ManifestDigest;
89import android.content.pm.PackageCleanItem;
90import android.content.pm.PackageInfo;
91import android.content.pm.PackageInfoLite;
92import android.content.pm.PackageInstallerParams;
93import android.content.pm.PackageManager;
94import android.content.pm.PackageParser.ActivityIntentInfo;
95import android.content.pm.PackageParser;
96import android.content.pm.PackageStats;
97import android.content.pm.PackageUserState;
98import android.content.pm.ParceledListSlice;
99import android.content.pm.PermissionGroupInfo;
100import android.content.pm.PermissionInfo;
101import android.content.pm.ProviderInfo;
102import android.content.pm.ResolveInfo;
103import android.content.pm.ServiceInfo;
104import android.content.pm.Signature;
105import android.content.pm.VerificationParams;
106import android.content.pm.VerifierDeviceIdentity;
107import android.content.pm.VerifierInfo;
108import android.content.res.Resources;
109import android.hardware.display.DisplayManager;
110import android.net.Uri;
111import android.os.Binder;
112import android.os.Build;
113import android.os.Bundle;
114import android.os.Environment;
115import android.os.Environment.UserEnvironment;
116import android.os.FileObserver;
117import android.os.FileUtils;
118import android.os.Handler;
119import android.os.IBinder;
120import android.os.Looper;
121import android.os.Message;
122import android.os.Parcel;
123import android.os.ParcelFileDescriptor;
124import android.os.Process;
125import android.os.RemoteException;
126import android.os.SELinux;
127import android.os.ServiceManager;
128import android.os.SystemClock;
129import android.os.SystemProperties;
130import android.os.UserHandle;
131import android.os.UserManager;
132import android.security.KeyStore;
133import android.security.SystemKeyStore;
134import android.system.ErrnoException;
135import android.system.Os;
136import android.system.StructStat;
137import android.text.TextUtils;
138import android.util.AtomicFile;
139import android.util.DisplayMetrics;
140import android.util.EventLog;
141import android.util.Log;
142import android.util.LogPrinter;
143import android.util.PrintStreamPrinter;
144import android.util.Slog;
145import android.util.SparseArray;
146import android.util.Xml;
147import android.view.Display;
148
149import java.io.BufferedInputStream;
150import java.io.BufferedOutputStream;
151import java.io.File;
152import java.io.FileDescriptor;
153import java.io.FileInputStream;
154import java.io.FileNotFoundException;
155import java.io.FileOutputStream;
156import java.io.FileReader;
157import java.io.FilenameFilter;
158import java.io.IOException;
159import java.io.InputStream;
160import java.io.PrintWriter;
161import java.nio.charset.StandardCharsets;
162import java.security.NoSuchAlgorithmException;
163import java.security.PublicKey;
164import java.security.cert.CertificateEncodingException;
165import java.security.cert.CertificateException;
166import java.text.SimpleDateFormat;
167import java.util.ArrayList;
168import java.util.Arrays;
169import java.util.Collection;
170import java.util.Collections;
171import java.util.Comparator;
172import java.util.Date;
173import java.util.HashMap;
174import java.util.HashSet;
175import java.util.Iterator;
176import java.util.List;
177import java.util.Map;
178import java.util.Set;
179import java.util.concurrent.atomic.AtomicBoolean;
180import java.util.concurrent.atomic.AtomicLong;
181
182import dalvik.system.DexFile;
183import dalvik.system.StaleDexCacheError;
184import dalvik.system.VMRuntime;
185
186import libcore.io.IoUtils;
187
188/**
189 * Keep track of all those .apks everywhere.
190 *
191 * This is very central to the platform's security; please run the unit
192 * tests whenever making modifications here:
193 *
194mmm frameworks/base/tests/AndroidTests
195adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
196adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
197 *
198 * {@hide}
199 */
200public class PackageManagerService extends IPackageManager.Stub {
201    static final String TAG = "PackageManager";
202    static final boolean DEBUG_SETTINGS = false;
203    static final boolean DEBUG_PREFERRED = false;
204    static final boolean DEBUG_UPGRADE = false;
205    private static final boolean DEBUG_INSTALL = false;
206    private static final boolean DEBUG_REMOVE = false;
207    private static final boolean DEBUG_BROADCASTS = false;
208    private static final boolean DEBUG_SHOW_INFO = false;
209    private static final boolean DEBUG_PACKAGE_INFO = false;
210    private static final boolean DEBUG_INTENT_MATCHING = false;
211    private static final boolean DEBUG_PACKAGE_SCANNING = false;
212    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
213    private static final boolean DEBUG_VERIFY = false;
214    private static final boolean DEBUG_DEXOPT = false;
215
216    private static final int RADIO_UID = Process.PHONE_UID;
217    private static final int LOG_UID = Process.LOG_UID;
218    private static final int NFC_UID = Process.NFC_UID;
219    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
220    private static final int SHELL_UID = Process.SHELL_UID;
221
222    // Cap the size of permission trees that 3rd party apps can define
223    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
224
225    private static final int REMOVE_EVENTS =
226        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
227    private static final int ADD_EVENTS =
228        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
229
230    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
231    // Suffix used during package installation when copying/moving
232    // package apks to install directory.
233    private static final String INSTALL_PACKAGE_SUFFIX = "-";
234
235    static final int SCAN_MONITOR = 1<<0;
236    static final int SCAN_NO_DEX = 1<<1;
237    static final int SCAN_FORCE_DEX = 1<<2;
238    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
239    static final int SCAN_NEW_INSTALL = 1<<4;
240    static final int SCAN_NO_PATHS = 1<<5;
241    static final int SCAN_UPDATE_TIME = 1<<6;
242    static final int SCAN_DEFER_DEX = 1<<7;
243    static final int SCAN_BOOTING = 1<<8;
244    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
245    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
246
247    static final int REMOVE_CHATTY = 1<<16;
248
249    /**
250     * Timeout (in milliseconds) after which the watchdog should declare that
251     * our handler thread is wedged.  The usual default for such things is one
252     * minute but we sometimes do very lengthy I/O operations on this thread,
253     * such as installing multi-gigabyte applications, so ours needs to be longer.
254     */
255    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
256
257    /**
258     * Whether verification is enabled by default.
259     */
260    private static final boolean DEFAULT_VERIFY_ENABLE = true;
261
262    /**
263     * The default maximum time to wait for the verification agent to return in
264     * milliseconds.
265     */
266    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
267
268    /**
269     * The default response for package verification timeout.
270     *
271     * This can be either PackageManager.VERIFICATION_ALLOW or
272     * PackageManager.VERIFICATION_REJECT.
273     */
274    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
275
276    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
277
278    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
279            DEFAULT_CONTAINER_PACKAGE,
280            "com.android.defcontainer.DefaultContainerService");
281
282    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
283
284    private static final String LIB_DIR_NAME = "lib";
285    private static final String LIB64_DIR_NAME = "lib64";
286
287    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
288
289    static final String mTempContainerPrefix = "smdl2tmp";
290
291    private static String sPreferredInstructionSet;
292
293    final ServiceThread mHandlerThread;
294
295    private static final String IDMAP_PREFIX = "/data/resource-cache/";
296    private static final String IDMAP_SUFFIX = "@idmap";
297
298    final PackageHandler mHandler;
299
300    final int mSdkVersion = Build.VERSION.SDK_INT;
301
302    final Context mContext;
303    final boolean mFactoryTest;
304    final boolean mOnlyCore;
305    final DisplayMetrics mMetrics;
306    final int mDefParseFlags;
307    final String[] mSeparateProcesses;
308
309    // This is where all application persistent data goes.
310    final File mAppDataDir;
311
312    // This is where all application persistent data goes for secondary users.
313    final File mUserAppDataDir;
314
315    /** The location for ASEC container files on internal storage. */
316    final String mAsecInternalPath;
317
318    // This is the object monitoring the framework dir.
319    final FileObserver mFrameworkInstallObserver;
320
321    // This is the object monitoring the system app dir.
322    final FileObserver mSystemInstallObserver;
323
324    // This is the object monitoring the privileged system app dir.
325    final FileObserver mPrivilegedInstallObserver;
326
327    // This is the object monitoring the vendor app dir.
328    final FileObserver mVendorInstallObserver;
329
330    // This is the object monitoring the vendor overlay package dir.
331    final FileObserver mVendorOverlayInstallObserver;
332
333    // This is the object monitoring the OEM app dir.
334    final FileObserver mOemInstallObserver;
335
336    // This is the object monitoring mAppInstallDir.
337    final FileObserver mAppInstallObserver;
338
339    // This is the object monitoring mDrmAppPrivateInstallDir.
340    final FileObserver mDrmAppInstallObserver;
341
342    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
343    // LOCK HELD.  Can be called with mInstallLock held.
344    final Installer mInstaller;
345
346    final File mAppInstallDir;
347
348    /**
349     * Directory to which applications installed internally have native
350     * libraries copied.
351     */
352    private File mAppLibInstallDir;
353
354    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
355    // apps.
356    final File mDrmAppPrivateInstallDir;
357
358    final File mAppStagingDir;
359
360    // ----------------------------------------------------------------
361
362    // Lock for state used when installing and doing other long running
363    // operations.  Methods that must be called with this lock held have
364    // the suffix "LI".
365    final Object mInstallLock = new Object();
366
367    // These are the directories in the 3rd party applications installed dir
368    // that we have currently loaded packages from.  Keys are the application's
369    // installed zip file (absolute codePath), and values are Package.
370    final HashMap<String, PackageParser.Package> mAppDirs =
371            new HashMap<String, PackageParser.Package>();
372
373    // Information for the parser to write more useful error messages.
374    int mLastScanError;
375
376    // ----------------------------------------------------------------
377
378    // Keys are String (package name), values are Package.  This also serves
379    // as the lock for the global state.  Methods that must be called with
380    // this lock held have the prefix "LP".
381    final HashMap<String, PackageParser.Package> mPackages =
382            new HashMap<String, PackageParser.Package>();
383
384    // Tracks available target package names -> overlay package paths.
385    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
386        new HashMap<String, HashMap<String, PackageParser.Package>>();
387
388    final Settings mSettings;
389    boolean mRestoredSettings;
390
391    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
392    int[] mGlobalGids;
393
394    // These are the built-in uid -> permission mappings that were read from the
395    // etc/permissions.xml file.
396    final SparseArray<HashSet<String>> mSystemPermissions =
397            new SparseArray<HashSet<String>>();
398
399    static final class SharedLibraryEntry {
400        final String path;
401        final String apk;
402
403        SharedLibraryEntry(String _path, String _apk) {
404            path = _path;
405            apk = _apk;
406        }
407    }
408
409    // These are the built-in shared libraries that were read from the
410    // etc/permissions.xml file.
411    final HashMap<String, SharedLibraryEntry> mSharedLibraries
412            = new HashMap<String, SharedLibraryEntry>();
413
414    // Temporary for building the final shared libraries for an .apk.
415    String[] mTmpSharedLibraries = null;
416
417    // These are the features this devices supports that were read from the
418    // etc/permissions.xml file.
419    final HashMap<String, FeatureInfo> mAvailableFeatures =
420            new HashMap<String, FeatureInfo>();
421
422    // If mac_permissions.xml was found for seinfo labeling.
423    boolean mFoundPolicyFile;
424
425    // If a recursive restorecon of /data/data/<pkg> is needed.
426    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
427
428    // All available activities, for your resolving pleasure.
429    final ActivityIntentResolver mActivities =
430            new ActivityIntentResolver();
431
432    // All available receivers, for your resolving pleasure.
433    final ActivityIntentResolver mReceivers =
434            new ActivityIntentResolver();
435
436    // All available services, for your resolving pleasure.
437    final ServiceIntentResolver mServices = new ServiceIntentResolver();
438
439    // All available providers, for your resolving pleasure.
440    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
441
442    // Mapping from provider base names (first directory in content URI codePath)
443    // to the provider information.
444    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
445            new HashMap<String, PackageParser.Provider>();
446
447    // Mapping from instrumentation class names to info about them.
448    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
449            new HashMap<ComponentName, PackageParser.Instrumentation>();
450
451    // Mapping from permission names to info about them.
452    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
453            new HashMap<String, PackageParser.PermissionGroup>();
454
455    // Packages whose data we have transfered into another package, thus
456    // should no longer exist.
457    final HashSet<String> mTransferedPackages = new HashSet<String>();
458
459    // Broadcast actions that are only available to the system.
460    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
461
462    /** List of packages waiting for verification. */
463    final SparseArray<PackageVerificationState> mPendingVerification
464            = new SparseArray<PackageVerificationState>();
465
466    final PackageInstallerService mInstallerService;
467
468    HashSet<PackageParser.Package> mDeferredDexOpt = null;
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    boolean mSystemReady;
474    boolean mSafeMode;
475    boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new HashMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsFirstBoot = false;
625
626        boolean isFirstBoot() {
627            return mIsFirstBoot;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsFirstBoot = true;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                args.observer.packageInstalled(res.name, res.returnCode);
1081                            } catch (RemoteException e) {
1082                                Slog.i(TAG, "Observer no longer exists.");
1083                            }
1084                        }
1085                        if (args.observer2 != null) {
1086                            try {
1087                                Bundle extras = extrasForInstallResult(res);
1088                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1089                            } catch (RemoteException e) {
1090                                Slog.i(TAG, "Observer no longer exists.");
1091                            }
1092                        }
1093                    } else {
1094                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1095                    }
1096                } break;
1097                case UPDATED_MEDIA_STATUS: {
1098                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1099                    boolean reportStatus = msg.arg1 == 1;
1100                    boolean doGc = msg.arg2 == 1;
1101                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1102                    if (doGc) {
1103                        // Force a gc to clear up stale containers.
1104                        Runtime.getRuntime().gc();
1105                    }
1106                    if (msg.obj != null) {
1107                        @SuppressWarnings("unchecked")
1108                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1109                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1110                        // Unload containers
1111                        unloadAllContainers(args);
1112                    }
1113                    if (reportStatus) {
1114                        try {
1115                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1116                            PackageHelper.getMountService().finishMediaUpdate();
1117                        } catch (RemoteException e) {
1118                            Log.e(TAG, "MountService not running?");
1119                        }
1120                    }
1121                } break;
1122                case WRITE_SETTINGS: {
1123                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124                    synchronized (mPackages) {
1125                        removeMessages(WRITE_SETTINGS);
1126                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1127                        mSettings.writeLPr();
1128                        mDirtyUsers.clear();
1129                    }
1130                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131                } break;
1132                case WRITE_PACKAGE_RESTRICTIONS: {
1133                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134                    synchronized (mPackages) {
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        for (int userId : mDirtyUsers) {
1137                            mSettings.writePackageRestrictionsLPr(userId);
1138                        }
1139                        mDirtyUsers.clear();
1140                    }
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142                } break;
1143                case CHECK_PENDING_VERIFICATION: {
1144                    final int verificationId = msg.arg1;
1145                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1146
1147                    if ((state != null) && !state.timeoutExtended()) {
1148                        final InstallArgs args = state.getInstallArgs();
1149                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of "
1156                                    + args.packageURI.toString());
1157                            state.setVerifierResponse(Binder.getCallingUid(),
1158                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1159                            broadcastPackageVerified(verificationId, args.packageURI,
1160                                    PackageManager.VERIFICATION_ALLOW,
1161                                    state.getInstallArgs().getUser());
1162                            try {
1163                                ret = args.copyApk(mContainerService, true);
1164                            } catch (RemoteException e) {
1165                                Slog.e(TAG, "Could not contact the ContainerService");
1166                            }
1167                        } else {
1168                            broadcastPackageVerified(verificationId, args.packageURI,
1169                                    PackageManager.VERIFICATION_REJECT,
1170                                    state.getInstallArgs().getUser());
1171                        }
1172
1173                        processPendingInstall(args, ret);
1174                        mHandler.sendEmptyMessage(MCS_UNBIND);
1175                    }
1176                    break;
1177                }
1178                case PACKAGE_VERIFIED: {
1179                    final int verificationId = msg.arg1;
1180
1181                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1182                    if (state == null) {
1183                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1184                        break;
1185                    }
1186
1187                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1188
1189                    state.setVerifierResponse(response.callerUid, response.code);
1190
1191                    if (state.isVerificationComplete()) {
1192                        mPendingVerification.remove(verificationId);
1193
1194                        final InstallArgs args = state.getInstallArgs();
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, args.packageURI,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final IPackageManager main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mMetrics = new DisplayMetrics();
1299        mSettings = new Settings(context);
1300        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1301                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1302        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1303                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1304        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1305                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312
1313        String separateProcesses = SystemProperties.get("debug.separate_processes");
1314        if (separateProcesses != null && separateProcesses.length() > 0) {
1315            if ("*".equals(separateProcesses)) {
1316                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1317                mSeparateProcesses = null;
1318                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1319            } else {
1320                mDefParseFlags = 0;
1321                mSeparateProcesses = separateProcesses.split(",");
1322                Slog.w(TAG, "Running with debug.separate_processes: "
1323                        + separateProcesses);
1324            }
1325        } else {
1326            mDefParseFlags = 0;
1327            mSeparateProcesses = null;
1328        }
1329
1330        mInstaller = installer;
1331
1332        getDefaultDisplayMetrics(context, mMetrics);
1333
1334        synchronized (mInstallLock) {
1335        // writer
1336        synchronized (mPackages) {
1337            mHandlerThread = new ServiceThread(TAG,
1338                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1339            mHandlerThread.start();
1340            mHandler = new PackageHandler(mHandlerThread.getLooper());
1341            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1342
1343            File dataDir = Environment.getDataDirectory();
1344            mAppDataDir = new File(dataDir, "data");
1345            mAppInstallDir = new File(dataDir, "app");
1346            mAppLibInstallDir = new File(dataDir, "app-lib");
1347            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1348            mUserAppDataDir = new File(dataDir, "user");
1349            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1350            mAppStagingDir = new File(dataDir, "app-staging");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Read permissions and features from system
1356            readPermissions(Environment.buildPath(
1357                    Environment.getRootDirectory(), "etc", "permissions"), false);
1358            // Only read features from OEM
1359            readPermissions(Environment.buildPath(
1360                    Environment.getOemDirectory(), "etc", "permissions"), true);
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            String bootClassPath = System.getProperty("java.boot.class.path");
1393            if (bootClassPath != null) {
1394                String[] paths = splitString(bootClassPath, ':');
1395                for (int i=0; i<paths.length; i++) {
1396                    alreadyDexOpted.add(paths[i]);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            boolean didDexOptLibraryOrTool = false;
1403
1404            final List<String> instructionSets = getAllInstructionSets();
1405
1406            /**
1407             * Ensure all external libraries have had dexopt run on them.
1408             */
1409            if (mSharedLibraries.size() > 0) {
1410                // NOTE: For now, we're compiling these system "shared libraries"
1411                // (and framework jars) into all available architectures. It's possible
1412                // to compile them only when we come across an app that uses them (there's
1413                // already logic for that in scanPackageLI) but that adds some complexity.
1414                for (String instructionSet : instructionSets) {
1415                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1416                        final String lib = libEntry.path;
1417                        if (lib == null) {
1418                            continue;
1419                        }
1420
1421                        try {
1422                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1423                                alreadyDexOpted.add(lib);
1424
1425                                // The list of "shared libraries" we have at this point is
1426                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1427                                didDexOptLibraryOrTool = true;
1428                            }
1429                        } catch (FileNotFoundException e) {
1430                            Slog.w(TAG, "Library not found: " + lib);
1431                        } catch (IOException e) {
1432                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1433                                    + e.getMessage());
1434                        }
1435                    }
1436                }
1437            }
1438
1439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1440
1441            // Gross hack for now: we know this file doesn't contain any
1442            // code, so don't dexopt it to avoid the resulting log spew.
1443            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1444
1445            // Gross hack for now: we know this file is only part of
1446            // the boot class path for art, so don't dexopt it to
1447            // avoid the resulting log spew.
1448            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1449
1450            /**
1451             * And there are a number of commands implemented in Java, which
1452             * we currently need to do the dexopt on so that they can be
1453             * run from a non-root shell.
1454             */
1455            String[] frameworkFiles = frameworkDir.list();
1456            if (frameworkFiles != null) {
1457                // TODO: We could compile these only for the most preferred ABI. We should
1458                // first double check that the dex files for these commands are not referenced
1459                // by other system apps.
1460                for (String instructionSet : instructionSets) {
1461                    for (int i=0; i<frameworkFiles.length; i++) {
1462                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1463                        String path = libPath.getPath();
1464                        // Skip the file if we already did it.
1465                        if (alreadyDexOpted.contains(path)) {
1466                            continue;
1467                        }
1468                        // Skip the file if it is not a type we want to dexopt.
1469                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1470                            continue;
1471                        }
1472                        try {
1473                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1474                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1475                                didDexOptLibraryOrTool = true;
1476                            }
1477                        } catch (FileNotFoundException e) {
1478                            Slog.w(TAG, "Jar not found: " + path);
1479                        } catch (IOException e) {
1480                            Slog.w(TAG, "Exception reading jar: " + path, e);
1481                        }
1482                    }
1483                }
1484            }
1485
1486            if (didDexOptLibraryOrTool) {
1487                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1488            }
1489
1490            // Collect vendor overlay packages.
1491            // (Do this before scanning any apps.)
1492            // For security and version matching reason, only consider
1493            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1494            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1495            mVendorOverlayInstallObserver = new AppDirObserver(
1496                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1497            mVendorOverlayInstallObserver.startWatching();
1498            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1499                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1500
1501            // Find base frameworks (resource packages without code).
1502            mFrameworkInstallObserver = new AppDirObserver(
1503                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1504            mFrameworkInstallObserver.startWatching();
1505            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1506                    | PackageParser.PARSE_IS_SYSTEM_DIR
1507                    | PackageParser.PARSE_IS_PRIVILEGED,
1508                    scanMode | SCAN_NO_DEX, 0);
1509
1510            // Collected privileged system packages.
1511            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1512            mPrivilegedInstallObserver = new AppDirObserver(
1513                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1514            mPrivilegedInstallObserver.startWatching();
1515                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1516                        | PackageParser.PARSE_IS_SYSTEM_DIR
1517                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1518
1519            // Collect ordinary system packages.
1520            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1521            mSystemInstallObserver = new AppDirObserver(
1522                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1523            mSystemInstallObserver.startWatching();
1524            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1525                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1526
1527            // Collect all vendor packages.
1528            File vendorAppDir = new File("/vendor/app");
1529            try {
1530                vendorAppDir = vendorAppDir.getCanonicalFile();
1531            } catch (IOException e) {
1532                // failed to look up canonical path, continue with original one
1533            }
1534            mVendorInstallObserver = new AppDirObserver(
1535                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1536            mVendorInstallObserver.startWatching();
1537            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1538                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1539
1540            // Collect all OEM packages.
1541            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1542            mOemInstallObserver = new AppDirObserver(
1543                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1544            mOemInstallObserver.startWatching();
1545            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1547
1548            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1549            mInstaller.moveFiles();
1550
1551            // Prune any system packages that no longer exist.
1552            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1553            if (!mOnlyCore) {
1554                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1555                while (psit.hasNext()) {
1556                    PackageSetting ps = psit.next();
1557
1558                    /*
1559                     * If this is not a system app, it can't be a
1560                     * disable system app.
1561                     */
1562                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1563                        continue;
1564                    }
1565
1566                    /*
1567                     * If the package is scanned, it's not erased.
1568                     */
1569                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1570                    if (scannedPkg != null) {
1571                        /*
1572                         * If the system app is both scanned and in the
1573                         * disabled packages list, then it must have been
1574                         * added via OTA. Remove it from the currently
1575                         * scanned package so the previously user-installed
1576                         * application can be scanned.
1577                         */
1578                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1579                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1580                                    + "; removing system app");
1581                            removePackageLI(ps, true);
1582                        }
1583
1584                        continue;
1585                    }
1586
1587                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1588                        psit.remove();
1589                        String msg = "System package " + ps.name
1590                                + " no longer exists; wiping its data";
1591                        reportSettingsProblem(Log.WARN, msg);
1592                        removeDataDirsLI(ps.name);
1593                    } else {
1594                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1595                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1596                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1597                        }
1598                    }
1599                }
1600            }
1601
1602            //look for any incomplete package installations
1603            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1604            //clean up list
1605            for(int i = 0; i < deletePkgsList.size(); i++) {
1606                //clean up here
1607                cleanupInstallFailedPackage(deletePkgsList.get(i));
1608            }
1609            //delete tmp files
1610            deleteTempPackageFiles();
1611
1612            // Remove any shared userIDs that have no associated packages
1613            mSettings.pruneSharedUsersLPw();
1614
1615            if (!mOnlyCore) {
1616                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1617                        SystemClock.uptimeMillis());
1618                mAppInstallObserver = new AppDirObserver(
1619                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1620                mAppInstallObserver.startWatching();
1621                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1622
1623                mDrmAppInstallObserver = new AppDirObserver(
1624                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1625                mDrmAppInstallObserver.startWatching();
1626                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1627                        scanMode, 0);
1628
1629                /**
1630                 * Remove disable package settings for any updated system
1631                 * apps that were removed via an OTA. If they're not a
1632                 * previously-updated app, remove them completely.
1633                 * Otherwise, just revoke their system-level permissions.
1634                 */
1635                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1636                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1637                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1638
1639                    String msg;
1640                    if (deletedPkg == null) {
1641                        msg = "Updated system package " + deletedAppName
1642                                + " no longer exists; wiping its data";
1643                        removeDataDirsLI(deletedAppName);
1644                    } else {
1645                        msg = "Updated system app + " + deletedAppName
1646                                + " no longer present; removing system privileges for "
1647                                + deletedAppName;
1648
1649                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1650
1651                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1652                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1653                    }
1654                    reportSettingsProblem(Log.WARN, msg);
1655                }
1656            } else {
1657                mAppInstallObserver = null;
1658                mDrmAppInstallObserver = null;
1659            }
1660
1661            // Now that we know all of the shared libraries, update all clients to have
1662            // the correct library paths.
1663            updateAllSharedLibrariesLPw();
1664
1665            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1666                // NOTE: We ignore potential failures here during a system scan (like
1667                // the rest of the commands above) because there's precious little we
1668                // can do about it. A settings error is reported, though.
1669                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1670                        false /* force dexopt */, false /* defer dexopt */);
1671            }
1672
1673            // Now that we know all the packages we are keeping,
1674            // read and update their last usage times.
1675            mPackageUsage.readLP();
1676
1677            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1678                    SystemClock.uptimeMillis());
1679            Slog.i(TAG, "Time to scan packages: "
1680                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1681                    + " seconds");
1682
1683            // If the platform SDK has changed since the last time we booted,
1684            // we need to re-grant app permission to catch any new ones that
1685            // appear.  This is really a hack, and means that apps can in some
1686            // cases get permissions that the user didn't initially explicitly
1687            // allow...  it would be nice to have some better way to handle
1688            // this situation.
1689            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1690                    != mSdkVersion;
1691            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1692                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1693                    + "; regranting permissions for internal storage");
1694            mSettings.mInternalSdkPlatform = mSdkVersion;
1695
1696            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1697                    | (regrantPermissions
1698                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1699                            : 0));
1700
1701            // If this is the first boot, and it is a normal boot, then
1702            // we need to initialize the default preferred apps.
1703            if (!mRestoredSettings && !onlyCore) {
1704                mSettings.readDefaultPreferredAppsLPw(this, 0);
1705            }
1706
1707            // All the changes are done during package scanning.
1708            mSettings.updateInternalDatabaseVersion();
1709
1710            // can downgrade to reader
1711            mSettings.writeLPr();
1712
1713            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1714                    SystemClock.uptimeMillis());
1715
1716
1717            mRequiredVerifierPackage = getRequiredVerifierLPr();
1718        } // synchronized (mPackages)
1719        } // synchronized (mInstallLock)
1720
1721        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1722
1723        // Now after opening every single application zip, make sure they
1724        // are all flushed.  Not really needed, but keeps things nice and
1725        // tidy.
1726        Runtime.getRuntime().gc();
1727    }
1728
1729    private static void pruneDexFiles(File cacheDir) {
1730        // If we had to do a dexopt of one of the previous
1731        // things, then something on the system has changed.
1732        // Consider this significant, and wipe away all other
1733        // existing dexopt files to ensure we don't leave any
1734        // dangling around.
1735        //
1736        // Additionally, delete all dex files from the root directory
1737        // since there shouldn't be any there anyway.
1738        //
1739        // Note: This isn't as good an indicator as it used to be. It
1740        // used to include the boot classpath but at some point
1741        // DexFile.isDexOptNeeded started returning false for the boot
1742        // class path files in all cases. It is very possible in a
1743        // small maintenance release update that the library and tool
1744        // jars may be unchanged but APK could be removed resulting in
1745        // unused dalvik-cache files.
1746        File[] files = cacheDir.listFiles();
1747        if (files != null) {
1748            for (File file : files) {
1749                if (!file.isDirectory()) {
1750                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1751                    file.delete();
1752                } else {
1753                    File[] subDirList = file.listFiles();
1754                    if (subDirList != null) {
1755                        for (File subDirFile : subDirList) {
1756                            final String fn = subDirFile.getName();
1757                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1758                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1759                                subDirFile.delete();
1760                            }
1761                        }
1762                    }
1763                }
1764            }
1765        }
1766    }
1767
1768    @Override
1769    public boolean isFirstBoot() {
1770        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1771    }
1772
1773    @Override
1774    public boolean isOnlyCoreApps() {
1775        return mOnlyCore;
1776    }
1777
1778    private String getRequiredVerifierLPr() {
1779        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1780        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1781                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1782
1783        String requiredVerifier = null;
1784
1785        final int N = receivers.size();
1786        for (int i = 0; i < N; i++) {
1787            final ResolveInfo info = receivers.get(i);
1788
1789            if (info.activityInfo == null) {
1790                continue;
1791            }
1792
1793            final String packageName = info.activityInfo.packageName;
1794
1795            final PackageSetting ps = mSettings.mPackages.get(packageName);
1796            if (ps == null) {
1797                continue;
1798            }
1799
1800            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1801            if (!gp.grantedPermissions
1802                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1803                continue;
1804            }
1805
1806            if (requiredVerifier != null) {
1807                throw new RuntimeException("There can be only one required verifier");
1808            }
1809
1810            requiredVerifier = packageName;
1811        }
1812
1813        return requiredVerifier;
1814    }
1815
1816    @Override
1817    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1818            throws RemoteException {
1819        try {
1820            return super.onTransact(code, data, reply, flags);
1821        } catch (RuntimeException e) {
1822            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1823                Slog.wtf(TAG, "Package Manager Crash", e);
1824            }
1825            throw e;
1826        }
1827    }
1828
1829    void cleanupInstallFailedPackage(PackageSetting ps) {
1830        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1831        removeDataDirsLI(ps.name);
1832        if (ps.codePath != null) {
1833            if (!ps.codePath.delete()) {
1834                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1835            }
1836        }
1837        if (ps.resourcePath != null) {
1838            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1839                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1840            }
1841        }
1842        mSettings.removePackageLPw(ps.name);
1843    }
1844
1845    void readPermissions(File libraryDir, boolean onlyFeatures) {
1846        // Read permissions from .../etc/permission directory.
1847        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1848            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1849            return;
1850        }
1851        if (!libraryDir.canRead()) {
1852            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1853            return;
1854        }
1855
1856        // Iterate over the files in the directory and scan .xml files
1857        for (File f : libraryDir.listFiles()) {
1858            // We'll read platform.xml last
1859            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1860                continue;
1861            }
1862
1863            if (!f.getPath().endsWith(".xml")) {
1864                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1865                continue;
1866            }
1867            if (!f.canRead()) {
1868                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1869                continue;
1870            }
1871
1872            readPermissionsFromXml(f, onlyFeatures);
1873        }
1874
1875        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1876        final File permFile = new File(Environment.getRootDirectory(),
1877                "etc/permissions/platform.xml");
1878        readPermissionsFromXml(permFile, onlyFeatures);
1879    }
1880
1881    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1882        FileReader permReader = null;
1883        try {
1884            permReader = new FileReader(permFile);
1885        } catch (FileNotFoundException e) {
1886            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1887            return;
1888        }
1889
1890        try {
1891            XmlPullParser parser = Xml.newPullParser();
1892            parser.setInput(permReader);
1893
1894            XmlUtils.beginDocument(parser, "permissions");
1895
1896            while (true) {
1897                XmlUtils.nextElement(parser);
1898                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1899                    break;
1900                }
1901
1902                String name = parser.getName();
1903                if ("group".equals(name) && !onlyFeatures) {
1904                    String gidStr = parser.getAttributeValue(null, "gid");
1905                    if (gidStr != null) {
1906                        int gid = Process.getGidForName(gidStr);
1907                        mGlobalGids = appendInt(mGlobalGids, gid);
1908                    } else {
1909                        Slog.w(TAG, "<group> without gid at "
1910                                + parser.getPositionDescription());
1911                    }
1912
1913                    XmlUtils.skipCurrentTag(parser);
1914                    continue;
1915                } else if ("permission".equals(name) && !onlyFeatures) {
1916                    String perm = parser.getAttributeValue(null, "name");
1917                    if (perm == null) {
1918                        Slog.w(TAG, "<permission> without name at "
1919                                + parser.getPositionDescription());
1920                        XmlUtils.skipCurrentTag(parser);
1921                        continue;
1922                    }
1923                    perm = perm.intern();
1924                    readPermission(parser, perm);
1925
1926                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1927                    String perm = parser.getAttributeValue(null, "name");
1928                    if (perm == null) {
1929                        Slog.w(TAG, "<assign-permission> without name at "
1930                                + parser.getPositionDescription());
1931                        XmlUtils.skipCurrentTag(parser);
1932                        continue;
1933                    }
1934                    String uidStr = parser.getAttributeValue(null, "uid");
1935                    if (uidStr == null) {
1936                        Slog.w(TAG, "<assign-permission> without uid at "
1937                                + parser.getPositionDescription());
1938                        XmlUtils.skipCurrentTag(parser);
1939                        continue;
1940                    }
1941                    int uid = Process.getUidForName(uidStr);
1942                    if (uid < 0) {
1943                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1944                                + uidStr + "\" at "
1945                                + parser.getPositionDescription());
1946                        XmlUtils.skipCurrentTag(parser);
1947                        continue;
1948                    }
1949                    perm = perm.intern();
1950                    HashSet<String> perms = mSystemPermissions.get(uid);
1951                    if (perms == null) {
1952                        perms = new HashSet<String>();
1953                        mSystemPermissions.put(uid, perms);
1954                    }
1955                    perms.add(perm);
1956                    XmlUtils.skipCurrentTag(parser);
1957
1958                } else if ("library".equals(name) && !onlyFeatures) {
1959                    String lname = parser.getAttributeValue(null, "name");
1960                    String lfile = parser.getAttributeValue(null, "file");
1961                    if (lname == null) {
1962                        Slog.w(TAG, "<library> without name at "
1963                                + parser.getPositionDescription());
1964                    } else if (lfile == null) {
1965                        Slog.w(TAG, "<library> without file at "
1966                                + parser.getPositionDescription());
1967                    } else {
1968                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1969                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1970                    }
1971                    XmlUtils.skipCurrentTag(parser);
1972                    continue;
1973
1974                } else if ("feature".equals(name)) {
1975                    String fname = parser.getAttributeValue(null, "name");
1976                    if (fname == null) {
1977                        Slog.w(TAG, "<feature> without name at "
1978                                + parser.getPositionDescription());
1979                    } else {
1980                        //Log.i(TAG, "Got feature " + fname);
1981                        FeatureInfo fi = new FeatureInfo();
1982                        fi.name = fname;
1983                        mAvailableFeatures.put(fname, fi);
1984                    }
1985                    XmlUtils.skipCurrentTag(parser);
1986                    continue;
1987
1988                } else {
1989                    XmlUtils.skipCurrentTag(parser);
1990                    continue;
1991                }
1992
1993            }
1994            permReader.close();
1995        } catch (XmlPullParserException e) {
1996            Slog.w(TAG, "Got execption parsing permissions.", e);
1997        } catch (IOException e) {
1998            Slog.w(TAG, "Got execption parsing permissions.", e);
1999        }
2000    }
2001
2002    void readPermission(XmlPullParser parser, String name)
2003            throws IOException, XmlPullParserException {
2004
2005        name = name.intern();
2006
2007        BasePermission bp = mSettings.mPermissions.get(name);
2008        if (bp == null) {
2009            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
2010            mSettings.mPermissions.put(name, bp);
2011        }
2012        int outerDepth = parser.getDepth();
2013        int type;
2014        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2015               && (type != XmlPullParser.END_TAG
2016                       || parser.getDepth() > outerDepth)) {
2017            if (type == XmlPullParser.END_TAG
2018                    || type == XmlPullParser.TEXT) {
2019                continue;
2020            }
2021
2022            String tagName = parser.getName();
2023            if ("group".equals(tagName)) {
2024                String gidStr = parser.getAttributeValue(null, "gid");
2025                if (gidStr != null) {
2026                    int gid = Process.getGidForName(gidStr);
2027                    bp.gids = appendInt(bp.gids, gid);
2028                } else {
2029                    Slog.w(TAG, "<group> without gid at "
2030                            + parser.getPositionDescription());
2031                }
2032            }
2033            XmlUtils.skipCurrentTag(parser);
2034        }
2035    }
2036
2037    static int[] appendInts(int[] cur, int[] add) {
2038        if (add == null) return cur;
2039        if (cur == null) return add;
2040        final int N = add.length;
2041        for (int i=0; i<N; i++) {
2042            cur = appendInt(cur, add[i]);
2043        }
2044        return cur;
2045    }
2046
2047    static int[] removeInts(int[] cur, int[] rem) {
2048        if (rem == null) return cur;
2049        if (cur == null) return cur;
2050        final int N = rem.length;
2051        for (int i=0; i<N; i++) {
2052            cur = removeInt(cur, rem[i]);
2053        }
2054        return cur;
2055    }
2056
2057    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2058        if (!sUserManager.exists(userId)) return null;
2059        final PackageSetting ps = (PackageSetting) p.mExtras;
2060        if (ps == null) {
2061            return null;
2062        }
2063        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2064        final PackageUserState state = ps.readUserState(userId);
2065        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2066                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2067                state, userId);
2068    }
2069
2070    @Override
2071    public boolean isPackageAvailable(String packageName, int userId) {
2072        if (!sUserManager.exists(userId)) return false;
2073        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2074        synchronized (mPackages) {
2075            PackageParser.Package p = mPackages.get(packageName);
2076            if (p != null) {
2077                final PackageSetting ps = (PackageSetting) p.mExtras;
2078                if (ps != null) {
2079                    final PackageUserState state = ps.readUserState(userId);
2080                    if (state != null) {
2081                        return PackageParser.isAvailable(state);
2082                    }
2083                }
2084            }
2085        }
2086        return false;
2087    }
2088
2089    @Override
2090    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2091        if (!sUserManager.exists(userId)) return null;
2092        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2093        // reader
2094        synchronized (mPackages) {
2095            PackageParser.Package p = mPackages.get(packageName);
2096            if (DEBUG_PACKAGE_INFO)
2097                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2098            if (p != null) {
2099                return generatePackageInfo(p, flags, userId);
2100            }
2101            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2102                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2103            }
2104        }
2105        return null;
2106    }
2107
2108    @Override
2109    public String[] currentToCanonicalPackageNames(String[] names) {
2110        String[] out = new String[names.length];
2111        // reader
2112        synchronized (mPackages) {
2113            for (int i=names.length-1; i>=0; i--) {
2114                PackageSetting ps = mSettings.mPackages.get(names[i]);
2115                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2116            }
2117        }
2118        return out;
2119    }
2120
2121    @Override
2122    public String[] canonicalToCurrentPackageNames(String[] names) {
2123        String[] out = new String[names.length];
2124        // reader
2125        synchronized (mPackages) {
2126            for (int i=names.length-1; i>=0; i--) {
2127                String cur = mSettings.mRenamedPackages.get(names[i]);
2128                out[i] = cur != null ? cur : names[i];
2129            }
2130        }
2131        return out;
2132    }
2133
2134    @Override
2135    public int getPackageUid(String packageName, int userId) {
2136        if (!sUserManager.exists(userId)) return -1;
2137        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2138        // reader
2139        synchronized (mPackages) {
2140            PackageParser.Package p = mPackages.get(packageName);
2141            if(p != null) {
2142                return UserHandle.getUid(userId, p.applicationInfo.uid);
2143            }
2144            PackageSetting ps = mSettings.mPackages.get(packageName);
2145            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2146                return -1;
2147            }
2148            p = ps.pkg;
2149            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2150        }
2151    }
2152
2153    @Override
2154    public int[] getPackageGids(String packageName) {
2155        // reader
2156        synchronized (mPackages) {
2157            PackageParser.Package p = mPackages.get(packageName);
2158            if (DEBUG_PACKAGE_INFO)
2159                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2160            if (p != null) {
2161                final PackageSetting ps = (PackageSetting)p.mExtras;
2162                return ps.getGids();
2163            }
2164        }
2165        // stupid thing to indicate an error.
2166        return new int[0];
2167    }
2168
2169    static final PermissionInfo generatePermissionInfo(
2170            BasePermission bp, int flags) {
2171        if (bp.perm != null) {
2172            return PackageParser.generatePermissionInfo(bp.perm, flags);
2173        }
2174        PermissionInfo pi = new PermissionInfo();
2175        pi.name = bp.name;
2176        pi.packageName = bp.sourcePackage;
2177        pi.nonLocalizedLabel = bp.name;
2178        pi.protectionLevel = bp.protectionLevel;
2179        return pi;
2180    }
2181
2182    @Override
2183    public PermissionInfo getPermissionInfo(String name, int flags) {
2184        // reader
2185        synchronized (mPackages) {
2186            final BasePermission p = mSettings.mPermissions.get(name);
2187            if (p != null) {
2188                return generatePermissionInfo(p, flags);
2189            }
2190            return null;
2191        }
2192    }
2193
2194    @Override
2195    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2196        // reader
2197        synchronized (mPackages) {
2198            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2199            for (BasePermission p : mSettings.mPermissions.values()) {
2200                if (group == null) {
2201                    if (p.perm == null || p.perm.info.group == null) {
2202                        out.add(generatePermissionInfo(p, flags));
2203                    }
2204                } else {
2205                    if (p.perm != null && group.equals(p.perm.info.group)) {
2206                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2207                    }
2208                }
2209            }
2210
2211            if (out.size() > 0) {
2212                return out;
2213            }
2214            return mPermissionGroups.containsKey(group) ? out : null;
2215        }
2216    }
2217
2218    @Override
2219    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2220        // reader
2221        synchronized (mPackages) {
2222            return PackageParser.generatePermissionGroupInfo(
2223                    mPermissionGroups.get(name), flags);
2224        }
2225    }
2226
2227    @Override
2228    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2229        // reader
2230        synchronized (mPackages) {
2231            final int N = mPermissionGroups.size();
2232            ArrayList<PermissionGroupInfo> out
2233                    = new ArrayList<PermissionGroupInfo>(N);
2234            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2235                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2236            }
2237            return out;
2238        }
2239    }
2240
2241    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2242            int userId) {
2243        if (!sUserManager.exists(userId)) return null;
2244        PackageSetting ps = mSettings.mPackages.get(packageName);
2245        if (ps != null) {
2246            if (ps.pkg == null) {
2247                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2248                        flags, userId);
2249                if (pInfo != null) {
2250                    return pInfo.applicationInfo;
2251                }
2252                return null;
2253            }
2254            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2255                    ps.readUserState(userId), userId);
2256        }
2257        return null;
2258    }
2259
2260    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2261            int userId) {
2262        if (!sUserManager.exists(userId)) return null;
2263        PackageSetting ps = mSettings.mPackages.get(packageName);
2264        if (ps != null) {
2265            PackageParser.Package pkg = ps.pkg;
2266            if (pkg == null) {
2267                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2268                    return null;
2269                }
2270                // TODO: teach about reading split name
2271                pkg = new PackageParser.Package(packageName, null);
2272                pkg.applicationInfo.packageName = packageName;
2273                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2274                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2275                pkg.applicationInfo.sourceDir = ps.codePathString;
2276                pkg.applicationInfo.dataDir =
2277                        getDataPathForPackage(packageName, 0).getPath();
2278                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2279                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2280            }
2281            return generatePackageInfo(pkg, flags, userId);
2282        }
2283        return null;
2284    }
2285
2286    @Override
2287    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2288        if (!sUserManager.exists(userId)) return null;
2289        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2290        // writer
2291        synchronized (mPackages) {
2292            PackageParser.Package p = mPackages.get(packageName);
2293            if (DEBUG_PACKAGE_INFO) Log.v(
2294                    TAG, "getApplicationInfo " + packageName
2295                    + ": " + p);
2296            if (p != null) {
2297                PackageSetting ps = mSettings.mPackages.get(packageName);
2298                if (ps == null) return null;
2299                // Note: isEnabledLP() does not apply here - always return info
2300                return PackageParser.generateApplicationInfo(
2301                        p, flags, ps.readUserState(userId), userId);
2302            }
2303            if ("android".equals(packageName)||"system".equals(packageName)) {
2304                return mAndroidApplication;
2305            }
2306            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2307                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2308            }
2309        }
2310        return null;
2311    }
2312
2313
2314    @Override
2315    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2316        mContext.enforceCallingOrSelfPermission(
2317                android.Manifest.permission.CLEAR_APP_CACHE, null);
2318        // Queue up an async operation since clearing cache may take a little while.
2319        mHandler.post(new Runnable() {
2320            public void run() {
2321                mHandler.removeCallbacks(this);
2322                int retCode = -1;
2323                synchronized (mInstallLock) {
2324                    retCode = mInstaller.freeCache(freeStorageSize);
2325                    if (retCode < 0) {
2326                        Slog.w(TAG, "Couldn't clear application caches");
2327                    }
2328                }
2329                if (observer != null) {
2330                    try {
2331                        observer.onRemoveCompleted(null, (retCode >= 0));
2332                    } catch (RemoteException e) {
2333                        Slog.w(TAG, "RemoveException when invoking call back");
2334                    }
2335                }
2336            }
2337        });
2338    }
2339
2340    @Override
2341    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2342        mContext.enforceCallingOrSelfPermission(
2343                android.Manifest.permission.CLEAR_APP_CACHE, null);
2344        // Queue up an async operation since clearing cache may take a little while.
2345        mHandler.post(new Runnable() {
2346            public void run() {
2347                mHandler.removeCallbacks(this);
2348                int retCode = -1;
2349                synchronized (mInstallLock) {
2350                    retCode = mInstaller.freeCache(freeStorageSize);
2351                    if (retCode < 0) {
2352                        Slog.w(TAG, "Couldn't clear application caches");
2353                    }
2354                }
2355                if(pi != null) {
2356                    try {
2357                        // Callback via pending intent
2358                        int code = (retCode >= 0) ? 1 : 0;
2359                        pi.sendIntent(null, code, null,
2360                                null, null);
2361                    } catch (SendIntentException e1) {
2362                        Slog.i(TAG, "Failed to send pending intent");
2363                    }
2364                }
2365            }
2366        });
2367    }
2368
2369    void freeStorage(long freeStorageSize) throws IOException {
2370        synchronized (mInstallLock) {
2371            if (mInstaller.freeCache(freeStorageSize) < 0) {
2372                throw new IOException("Failed to free enough space");
2373            }
2374        }
2375    }
2376
2377    @Override
2378    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2379        if (!sUserManager.exists(userId)) return null;
2380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2381        synchronized (mPackages) {
2382            PackageParser.Activity a = mActivities.mActivities.get(component);
2383
2384            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2385            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2386                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2387                if (ps == null) return null;
2388                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2389                        userId);
2390            }
2391            if (mResolveComponentName.equals(component)) {
2392                return mResolveActivity;
2393            }
2394        }
2395        return null;
2396    }
2397
2398    @Override
2399    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2400            String resolvedType) {
2401        synchronized (mPackages) {
2402            PackageParser.Activity a = mActivities.mActivities.get(component);
2403            if (a == null) {
2404                return false;
2405            }
2406            for (int i=0; i<a.intents.size(); i++) {
2407                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2408                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2409                    return true;
2410                }
2411            }
2412            return false;
2413        }
2414    }
2415
2416    @Override
2417    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2418        if (!sUserManager.exists(userId)) return null;
2419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2420        synchronized (mPackages) {
2421            PackageParser.Activity a = mReceivers.mActivities.get(component);
2422            if (DEBUG_PACKAGE_INFO) Log.v(
2423                TAG, "getReceiverInfo " + component + ": " + a);
2424            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2425                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2426                if (ps == null) return null;
2427                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2428                        userId);
2429            }
2430        }
2431        return null;
2432    }
2433
2434    @Override
2435    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2436        if (!sUserManager.exists(userId)) return null;
2437        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2438        synchronized (mPackages) {
2439            PackageParser.Service s = mServices.mServices.get(component);
2440            if (DEBUG_PACKAGE_INFO) Log.v(
2441                TAG, "getServiceInfo " + component + ": " + s);
2442            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2443                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2444                if (ps == null) return null;
2445                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2446                        userId);
2447            }
2448        }
2449        return null;
2450    }
2451
2452    @Override
2453    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2454        if (!sUserManager.exists(userId)) return null;
2455        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2456        synchronized (mPackages) {
2457            PackageParser.Provider p = mProviders.mProviders.get(component);
2458            if (DEBUG_PACKAGE_INFO) Log.v(
2459                TAG, "getProviderInfo " + component + ": " + p);
2460            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2461                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2462                if (ps == null) return null;
2463                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2464                        userId);
2465            }
2466        }
2467        return null;
2468    }
2469
2470    @Override
2471    public String[] getSystemSharedLibraryNames() {
2472        Set<String> libSet;
2473        synchronized (mPackages) {
2474            libSet = mSharedLibraries.keySet();
2475            int size = libSet.size();
2476            if (size > 0) {
2477                String[] libs = new String[size];
2478                libSet.toArray(libs);
2479                return libs;
2480            }
2481        }
2482        return null;
2483    }
2484
2485    @Override
2486    public FeatureInfo[] getSystemAvailableFeatures() {
2487        Collection<FeatureInfo> featSet;
2488        synchronized (mPackages) {
2489            featSet = mAvailableFeatures.values();
2490            int size = featSet.size();
2491            if (size > 0) {
2492                FeatureInfo[] features = new FeatureInfo[size+1];
2493                featSet.toArray(features);
2494                FeatureInfo fi = new FeatureInfo();
2495                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2496                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2497                features[size] = fi;
2498                return features;
2499            }
2500        }
2501        return null;
2502    }
2503
2504    @Override
2505    public boolean hasSystemFeature(String name) {
2506        synchronized (mPackages) {
2507            return mAvailableFeatures.containsKey(name);
2508        }
2509    }
2510
2511    private void checkValidCaller(int uid, int userId) {
2512        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2513            return;
2514
2515        throw new SecurityException("Caller uid=" + uid
2516                + " is not privileged to communicate with user=" + userId);
2517    }
2518
2519    @Override
2520    public int checkPermission(String permName, String pkgName) {
2521        synchronized (mPackages) {
2522            PackageParser.Package p = mPackages.get(pkgName);
2523            if (p != null && p.mExtras != null) {
2524                PackageSetting ps = (PackageSetting)p.mExtras;
2525                if (ps.sharedUser != null) {
2526                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2527                        return PackageManager.PERMISSION_GRANTED;
2528                    }
2529                } else if (ps.grantedPermissions.contains(permName)) {
2530                    return PackageManager.PERMISSION_GRANTED;
2531                }
2532            }
2533        }
2534        return PackageManager.PERMISSION_DENIED;
2535    }
2536
2537    @Override
2538    public int checkUidPermission(String permName, int uid) {
2539        synchronized (mPackages) {
2540            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2541            if (obj != null) {
2542                GrantedPermissions gp = (GrantedPermissions)obj;
2543                if (gp.grantedPermissions.contains(permName)) {
2544                    return PackageManager.PERMISSION_GRANTED;
2545                }
2546            } else {
2547                HashSet<String> perms = mSystemPermissions.get(uid);
2548                if (perms != null && perms.contains(permName)) {
2549                    return PackageManager.PERMISSION_GRANTED;
2550                }
2551            }
2552        }
2553        return PackageManager.PERMISSION_DENIED;
2554    }
2555
2556    /**
2557     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2558     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2559     * @param message the message to log on security exception
2560     */
2561    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2562            String message) {
2563        if (userId < 0) {
2564            throw new IllegalArgumentException("Invalid userId " + userId);
2565        }
2566        if (userId == UserHandle.getUserId(callingUid)) return;
2567        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2568            if (requireFullPermission) {
2569                mContext.enforceCallingOrSelfPermission(
2570                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2571            } else {
2572                try {
2573                    mContext.enforceCallingOrSelfPermission(
2574                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2575                } catch (SecurityException se) {
2576                    mContext.enforceCallingOrSelfPermission(
2577                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2578                }
2579            }
2580        }
2581    }
2582
2583    private BasePermission findPermissionTreeLP(String permName) {
2584        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2585            if (permName.startsWith(bp.name) &&
2586                    permName.length() > bp.name.length() &&
2587                    permName.charAt(bp.name.length()) == '.') {
2588                return bp;
2589            }
2590        }
2591        return null;
2592    }
2593
2594    private BasePermission checkPermissionTreeLP(String permName) {
2595        if (permName != null) {
2596            BasePermission bp = findPermissionTreeLP(permName);
2597            if (bp != null) {
2598                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2599                    return bp;
2600                }
2601                throw new SecurityException("Calling uid "
2602                        + Binder.getCallingUid()
2603                        + " is not allowed to add to permission tree "
2604                        + bp.name + " owned by uid " + bp.uid);
2605            }
2606        }
2607        throw new SecurityException("No permission tree found for " + permName);
2608    }
2609
2610    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2611        if (s1 == null) {
2612            return s2 == null;
2613        }
2614        if (s2 == null) {
2615            return false;
2616        }
2617        if (s1.getClass() != s2.getClass()) {
2618            return false;
2619        }
2620        return s1.equals(s2);
2621    }
2622
2623    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2624        if (pi1.icon != pi2.icon) return false;
2625        if (pi1.logo != pi2.logo) return false;
2626        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2627        if (!compareStrings(pi1.name, pi2.name)) return false;
2628        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2629        // We'll take care of setting this one.
2630        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2631        // These are not currently stored in settings.
2632        //if (!compareStrings(pi1.group, pi2.group)) return false;
2633        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2634        //if (pi1.labelRes != pi2.labelRes) return false;
2635        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2636        return true;
2637    }
2638
2639    int permissionInfoFootprint(PermissionInfo info) {
2640        int size = info.name.length();
2641        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2642        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2643        return size;
2644    }
2645
2646    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2647        int size = 0;
2648        for (BasePermission perm : mSettings.mPermissions.values()) {
2649            if (perm.uid == tree.uid) {
2650                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2651            }
2652        }
2653        return size;
2654    }
2655
2656    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2657        // We calculate the max size of permissions defined by this uid and throw
2658        // if that plus the size of 'info' would exceed our stated maximum.
2659        if (tree.uid != Process.SYSTEM_UID) {
2660            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2661            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2662                throw new SecurityException("Permission tree size cap exceeded");
2663            }
2664        }
2665    }
2666
2667    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2668        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2669            throw new SecurityException("Label must be specified in permission");
2670        }
2671        BasePermission tree = checkPermissionTreeLP(info.name);
2672        BasePermission bp = mSettings.mPermissions.get(info.name);
2673        boolean added = bp == null;
2674        boolean changed = true;
2675        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2676        if (added) {
2677            enforcePermissionCapLocked(info, tree);
2678            bp = new BasePermission(info.name, tree.sourcePackage,
2679                    BasePermission.TYPE_DYNAMIC);
2680        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2681            throw new SecurityException(
2682                    "Not allowed to modify non-dynamic permission "
2683                    + info.name);
2684        } else {
2685            if (bp.protectionLevel == fixedLevel
2686                    && bp.perm.owner.equals(tree.perm.owner)
2687                    && bp.uid == tree.uid
2688                    && comparePermissionInfos(bp.perm.info, info)) {
2689                changed = false;
2690            }
2691        }
2692        bp.protectionLevel = fixedLevel;
2693        info = new PermissionInfo(info);
2694        info.protectionLevel = fixedLevel;
2695        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2696        bp.perm.info.packageName = tree.perm.info.packageName;
2697        bp.uid = tree.uid;
2698        if (added) {
2699            mSettings.mPermissions.put(info.name, bp);
2700        }
2701        if (changed) {
2702            if (!async) {
2703                mSettings.writeLPr();
2704            } else {
2705                scheduleWriteSettingsLocked();
2706            }
2707        }
2708        return added;
2709    }
2710
2711    @Override
2712    public boolean addPermission(PermissionInfo info) {
2713        synchronized (mPackages) {
2714            return addPermissionLocked(info, false);
2715        }
2716    }
2717
2718    @Override
2719    public boolean addPermissionAsync(PermissionInfo info) {
2720        synchronized (mPackages) {
2721            return addPermissionLocked(info, true);
2722        }
2723    }
2724
2725    @Override
2726    public void removePermission(String name) {
2727        synchronized (mPackages) {
2728            checkPermissionTreeLP(name);
2729            BasePermission bp = mSettings.mPermissions.get(name);
2730            if (bp != null) {
2731                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2732                    throw new SecurityException(
2733                            "Not allowed to modify non-dynamic permission "
2734                            + name);
2735                }
2736                mSettings.mPermissions.remove(name);
2737                mSettings.writeLPr();
2738            }
2739        }
2740    }
2741
2742    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2743        int index = pkg.requestedPermissions.indexOf(bp.name);
2744        if (index == -1) {
2745            throw new SecurityException("Package " + pkg.packageName
2746                    + " has not requested permission " + bp.name);
2747        }
2748        boolean isNormal =
2749                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2750                        == PermissionInfo.PROTECTION_NORMAL);
2751        boolean isDangerous =
2752                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2753                        == PermissionInfo.PROTECTION_DANGEROUS);
2754        boolean isDevelopment =
2755                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2756
2757        if (!isNormal && !isDangerous && !isDevelopment) {
2758            throw new SecurityException("Permission " + bp.name
2759                    + " is not a changeable permission type");
2760        }
2761
2762        if (isNormal || isDangerous) {
2763            if (pkg.requestedPermissionsRequired.get(index)) {
2764                throw new SecurityException("Can't change " + bp.name
2765                        + ". It is required by the application");
2766            }
2767        }
2768    }
2769
2770    @Override
2771    public void grantPermission(String packageName, String permissionName) {
2772        mContext.enforceCallingOrSelfPermission(
2773                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2774        synchronized (mPackages) {
2775            final PackageParser.Package pkg = mPackages.get(packageName);
2776            if (pkg == null) {
2777                throw new IllegalArgumentException("Unknown package: " + packageName);
2778            }
2779            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2780            if (bp == null) {
2781                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2782            }
2783
2784            checkGrantRevokePermissions(pkg, bp);
2785
2786            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2787            if (ps == null) {
2788                return;
2789            }
2790            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2791            if (gp.grantedPermissions.add(permissionName)) {
2792                if (ps.haveGids) {
2793                    gp.gids = appendInts(gp.gids, bp.gids);
2794                }
2795                mSettings.writeLPr();
2796            }
2797        }
2798    }
2799
2800    @Override
2801    public void revokePermission(String packageName, String permissionName) {
2802        int changedAppId = -1;
2803
2804        synchronized (mPackages) {
2805            final PackageParser.Package pkg = mPackages.get(packageName);
2806            if (pkg == null) {
2807                throw new IllegalArgumentException("Unknown package: " + packageName);
2808            }
2809            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2810                mContext.enforceCallingOrSelfPermission(
2811                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2812            }
2813            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2814            if (bp == null) {
2815                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2816            }
2817
2818            checkGrantRevokePermissions(pkg, bp);
2819
2820            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2821            if (ps == null) {
2822                return;
2823            }
2824            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2825            if (gp.grantedPermissions.remove(permissionName)) {
2826                gp.grantedPermissions.remove(permissionName);
2827                if (ps.haveGids) {
2828                    gp.gids = removeInts(gp.gids, bp.gids);
2829                }
2830                mSettings.writeLPr();
2831                changedAppId = ps.appId;
2832            }
2833        }
2834
2835        if (changedAppId >= 0) {
2836            // We changed the perm on someone, kill its processes.
2837            IActivityManager am = ActivityManagerNative.getDefault();
2838            if (am != null) {
2839                final int callingUserId = UserHandle.getCallingUserId();
2840                final long ident = Binder.clearCallingIdentity();
2841                try {
2842                    //XXX we should only revoke for the calling user's app permissions,
2843                    // but for now we impact all users.
2844                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2845                    //        "revoke " + permissionName);
2846                    int[] users = sUserManager.getUserIds();
2847                    for (int user : users) {
2848                        am.killUid(UserHandle.getUid(user, changedAppId),
2849                                "revoke " + permissionName);
2850                    }
2851                } catch (RemoteException e) {
2852                } finally {
2853                    Binder.restoreCallingIdentity(ident);
2854                }
2855            }
2856        }
2857    }
2858
2859    @Override
2860    public boolean isProtectedBroadcast(String actionName) {
2861        synchronized (mPackages) {
2862            return mProtectedBroadcasts.contains(actionName);
2863        }
2864    }
2865
2866    @Override
2867    public int checkSignatures(String pkg1, String pkg2) {
2868        synchronized (mPackages) {
2869            final PackageParser.Package p1 = mPackages.get(pkg1);
2870            final PackageParser.Package p2 = mPackages.get(pkg2);
2871            if (p1 == null || p1.mExtras == null
2872                    || p2 == null || p2.mExtras == null) {
2873                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2874            }
2875            return compareSignatures(p1.mSignatures, p2.mSignatures);
2876        }
2877    }
2878
2879    @Override
2880    public int checkUidSignatures(int uid1, int uid2) {
2881        // Map to base uids.
2882        uid1 = UserHandle.getAppId(uid1);
2883        uid2 = UserHandle.getAppId(uid2);
2884        // reader
2885        synchronized (mPackages) {
2886            Signature[] s1;
2887            Signature[] s2;
2888            Object obj = mSettings.getUserIdLPr(uid1);
2889            if (obj != null) {
2890                if (obj instanceof SharedUserSetting) {
2891                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2892                } else if (obj instanceof PackageSetting) {
2893                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2894                } else {
2895                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2896                }
2897            } else {
2898                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2899            }
2900            obj = mSettings.getUserIdLPr(uid2);
2901            if (obj != null) {
2902                if (obj instanceof SharedUserSetting) {
2903                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2904                } else if (obj instanceof PackageSetting) {
2905                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2906                } else {
2907                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2908                }
2909            } else {
2910                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2911            }
2912            return compareSignatures(s1, s2);
2913        }
2914    }
2915
2916    /**
2917     * Compares two sets of signatures. Returns:
2918     * <br />
2919     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2920     * <br />
2921     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2922     * <br />
2923     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2924     * <br />
2925     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2926     * <br />
2927     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2928     */
2929    static int compareSignatures(Signature[] s1, Signature[] s2) {
2930        if (s1 == null) {
2931            return s2 == null
2932                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2933                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2934        }
2935
2936        if (s2 == null) {
2937            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2938        }
2939
2940        if (s1.length != s2.length) {
2941            return PackageManager.SIGNATURE_NO_MATCH;
2942        }
2943
2944        // Since both signature sets are of size 1, we can compare without HashSets.
2945        if (s1.length == 1) {
2946            return s1[0].equals(s2[0]) ?
2947                    PackageManager.SIGNATURE_MATCH :
2948                    PackageManager.SIGNATURE_NO_MATCH;
2949        }
2950
2951        HashSet<Signature> set1 = new HashSet<Signature>();
2952        for (Signature sig : s1) {
2953            set1.add(sig);
2954        }
2955        HashSet<Signature> set2 = new HashSet<Signature>();
2956        for (Signature sig : s2) {
2957            set2.add(sig);
2958        }
2959        // Make sure s2 contains all signatures in s1.
2960        if (set1.equals(set2)) {
2961            return PackageManager.SIGNATURE_MATCH;
2962        }
2963        return PackageManager.SIGNATURE_NO_MATCH;
2964    }
2965
2966    /**
2967     * If the database version for this type of package (internal storage or
2968     * external storage) is less than the version where package signatures
2969     * were updated, return true.
2970     */
2971    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2972        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2973                DatabaseVersion.SIGNATURE_END_ENTITY))
2974                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2975                        DatabaseVersion.SIGNATURE_END_ENTITY));
2976    }
2977
2978    /**
2979     * Used for backward compatibility to make sure any packages with
2980     * certificate chains get upgraded to the new style. {@code existingSigs}
2981     * will be in the old format (since they were stored on disk from before the
2982     * system upgrade) and {@code scannedSigs} will be in the newer format.
2983     */
2984    private int compareSignaturesCompat(PackageSignatures existingSigs,
2985            PackageParser.Package scannedPkg) {
2986        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2987            return PackageManager.SIGNATURE_NO_MATCH;
2988        }
2989
2990        HashSet<Signature> existingSet = new HashSet<Signature>();
2991        for (Signature sig : existingSigs.mSignatures) {
2992            existingSet.add(sig);
2993        }
2994        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2995        for (Signature sig : scannedPkg.mSignatures) {
2996            try {
2997                Signature[] chainSignatures = sig.getChainSignatures();
2998                for (Signature chainSig : chainSignatures) {
2999                    scannedCompatSet.add(chainSig);
3000                }
3001            } catch (CertificateEncodingException e) {
3002                scannedCompatSet.add(sig);
3003            }
3004        }
3005        /*
3006         * Make sure the expanded scanned set contains all signatures in the
3007         * existing one.
3008         */
3009        if (scannedCompatSet.equals(existingSet)) {
3010            // Migrate the old signatures to the new scheme.
3011            existingSigs.assignSignatures(scannedPkg.mSignatures);
3012            // The new KeySets will be re-added later in the scanning process.
3013            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
3014            return PackageManager.SIGNATURE_MATCH;
3015        }
3016        return PackageManager.SIGNATURE_NO_MATCH;
3017    }
3018
3019    @Override
3020    public String[] getPackagesForUid(int uid) {
3021        uid = UserHandle.getAppId(uid);
3022        // reader
3023        synchronized (mPackages) {
3024            Object obj = mSettings.getUserIdLPr(uid);
3025            if (obj instanceof SharedUserSetting) {
3026                final SharedUserSetting sus = (SharedUserSetting) obj;
3027                final int N = sus.packages.size();
3028                final String[] res = new String[N];
3029                final Iterator<PackageSetting> it = sus.packages.iterator();
3030                int i = 0;
3031                while (it.hasNext()) {
3032                    res[i++] = it.next().name;
3033                }
3034                return res;
3035            } else if (obj instanceof PackageSetting) {
3036                final PackageSetting ps = (PackageSetting) obj;
3037                return new String[] { ps.name };
3038            }
3039        }
3040        return null;
3041    }
3042
3043    @Override
3044    public String getNameForUid(int uid) {
3045        // reader
3046        synchronized (mPackages) {
3047            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3048            if (obj instanceof SharedUserSetting) {
3049                final SharedUserSetting sus = (SharedUserSetting) obj;
3050                return sus.name + ":" + sus.userId;
3051            } else if (obj instanceof PackageSetting) {
3052                final PackageSetting ps = (PackageSetting) obj;
3053                return ps.name;
3054            }
3055        }
3056        return null;
3057    }
3058
3059    @Override
3060    public int getUidForSharedUser(String sharedUserName) {
3061        if(sharedUserName == null) {
3062            return -1;
3063        }
3064        // reader
3065        synchronized (mPackages) {
3066            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3067            if (suid == null) {
3068                return -1;
3069            }
3070            return suid.userId;
3071        }
3072    }
3073
3074    @Override
3075    public int getFlagsForUid(int uid) {
3076        synchronized (mPackages) {
3077            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3078            if (obj instanceof SharedUserSetting) {
3079                final SharedUserSetting sus = (SharedUserSetting) obj;
3080                return sus.pkgFlags;
3081            } else if (obj instanceof PackageSetting) {
3082                final PackageSetting ps = (PackageSetting) obj;
3083                return ps.pkgFlags;
3084            }
3085        }
3086        return 0;
3087    }
3088
3089    @Override
3090    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3091            int flags, int userId) {
3092        if (!sUserManager.exists(userId)) return null;
3093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3094        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3095        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3096    }
3097
3098    @Override
3099    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3100            IntentFilter filter, int match, ComponentName activity) {
3101        final int userId = UserHandle.getCallingUserId();
3102        if (DEBUG_PREFERRED) {
3103            Log.v(TAG, "setLastChosenActivity intent=" + intent
3104                + " resolvedType=" + resolvedType
3105                + " flags=" + flags
3106                + " filter=" + filter
3107                + " match=" + match
3108                + " activity=" + activity);
3109            filter.dump(new PrintStreamPrinter(System.out), "    ");
3110        }
3111        intent.setComponent(null);
3112        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3113        // Find any earlier preferred or last chosen entries and nuke them
3114        findPreferredActivity(intent, resolvedType,
3115                flags, query, 0, false, true, false, userId);
3116        // Add the new activity as the last chosen for this filter
3117        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3118    }
3119
3120    @Override
3121    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3122        final int userId = UserHandle.getCallingUserId();
3123        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3124        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3125        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3126                false, false, false, userId);
3127    }
3128
3129    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3130            int flags, List<ResolveInfo> query, int userId) {
3131        if (query != null) {
3132            final int N = query.size();
3133            if (N == 1) {
3134                return query.get(0);
3135            } else if (N > 1) {
3136                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3137                // If there is more than one activity with the same priority,
3138                // then let the user decide between them.
3139                ResolveInfo r0 = query.get(0);
3140                ResolveInfo r1 = query.get(1);
3141                if (DEBUG_INTENT_MATCHING || debug) {
3142                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3143                            + r1.activityInfo.name + "=" + r1.priority);
3144                }
3145                // If the first activity has a higher priority, or a different
3146                // default, then it is always desireable to pick it.
3147                if (r0.priority != r1.priority
3148                        || r0.preferredOrder != r1.preferredOrder
3149                        || r0.isDefault != r1.isDefault) {
3150                    return query.get(0);
3151                }
3152                // If we have saved a preference for a preferred activity for
3153                // this Intent, use that.
3154                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3155                        flags, query, r0.priority, true, false, debug, userId);
3156                if (ri != null) {
3157                    return ri;
3158                }
3159                if (userId != 0) {
3160                    ri = new ResolveInfo(mResolveInfo);
3161                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3162                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3163                            ri.activityInfo.applicationInfo);
3164                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3165                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3166                    return ri;
3167                }
3168                return mResolveInfo;
3169            }
3170        }
3171        return null;
3172    }
3173
3174    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3175            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3176        final int N = query.size();
3177        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3178                .get(userId);
3179        // Get the list of persistent preferred activities that handle the intent
3180        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3181        List<PersistentPreferredActivity> pprefs = ppir != null
3182                ? ppir.queryIntent(intent, resolvedType,
3183                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3184                : null;
3185        if (pprefs != null && pprefs.size() > 0) {
3186            final int M = pprefs.size();
3187            for (int i=0; i<M; i++) {
3188                final PersistentPreferredActivity ppa = pprefs.get(i);
3189                if (DEBUG_PREFERRED || debug) {
3190                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3191                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3192                            + "\n  component=" + ppa.mComponent);
3193                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3194                }
3195                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3196                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3197                if (DEBUG_PREFERRED || debug) {
3198                    Slog.v(TAG, "Found persistent preferred activity:");
3199                    if (ai != null) {
3200                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3201                    } else {
3202                        Slog.v(TAG, "  null");
3203                    }
3204                }
3205                if (ai == null) {
3206                    // This previously registered persistent preferred activity
3207                    // component is no longer known. Ignore it and do NOT remove it.
3208                    continue;
3209                }
3210                for (int j=0; j<N; j++) {
3211                    final ResolveInfo ri = query.get(j);
3212                    if (!ri.activityInfo.applicationInfo.packageName
3213                            .equals(ai.applicationInfo.packageName)) {
3214                        continue;
3215                    }
3216                    if (!ri.activityInfo.name.equals(ai.name)) {
3217                        continue;
3218                    }
3219                    //  Found a persistent preference that can handle the intent.
3220                    if (DEBUG_PREFERRED || debug) {
3221                        Slog.v(TAG, "Returning persistent preferred activity: " +
3222                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3223                    }
3224                    return ri;
3225                }
3226            }
3227        }
3228        return null;
3229    }
3230
3231    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3232            List<ResolveInfo> query, int priority, boolean always,
3233            boolean removeMatches, boolean debug, int userId) {
3234        if (!sUserManager.exists(userId)) return null;
3235        // writer
3236        synchronized (mPackages) {
3237            if (intent.getSelector() != null) {
3238                intent = intent.getSelector();
3239            }
3240            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3241
3242            // Try to find a matching persistent preferred activity.
3243            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3244                    debug, userId);
3245
3246            // If a persistent preferred activity matched, use it.
3247            if (pri != null) {
3248                return pri;
3249            }
3250
3251            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3252            // Get the list of preferred activities that handle the intent
3253            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3254            List<PreferredActivity> prefs = pir != null
3255                    ? pir.queryIntent(intent, resolvedType,
3256                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3257                    : null;
3258            if (prefs != null && prefs.size() > 0) {
3259                // First figure out how good the original match set is.
3260                // We will only allow preferred activities that came
3261                // from the same match quality.
3262                int match = 0;
3263
3264                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3265
3266                final int N = query.size();
3267                for (int j=0; j<N; j++) {
3268                    final ResolveInfo ri = query.get(j);
3269                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3270                            + ": 0x" + Integer.toHexString(match));
3271                    if (ri.match > match) {
3272                        match = ri.match;
3273                    }
3274                }
3275
3276                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3277                        + Integer.toHexString(match));
3278
3279                match &= IntentFilter.MATCH_CATEGORY_MASK;
3280                final int M = prefs.size();
3281                for (int i=0; i<M; i++) {
3282                    final PreferredActivity pa = prefs.get(i);
3283                    if (DEBUG_PREFERRED || debug) {
3284                        Slog.v(TAG, "Checking PreferredActivity ds="
3285                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3286                                + "\n  component=" + pa.mPref.mComponent);
3287                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3288                    }
3289                    if (pa.mPref.mMatch != match) {
3290                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3291                                + Integer.toHexString(pa.mPref.mMatch));
3292                        continue;
3293                    }
3294                    // If it's not an "always" type preferred activity and that's what we're
3295                    // looking for, skip it.
3296                    if (always && !pa.mPref.mAlways) {
3297                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3298                        continue;
3299                    }
3300                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3301                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3302                    if (DEBUG_PREFERRED || debug) {
3303                        Slog.v(TAG, "Found preferred activity:");
3304                        if (ai != null) {
3305                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3306                        } else {
3307                            Slog.v(TAG, "  null");
3308                        }
3309                    }
3310                    if (ai == null) {
3311                        // This previously registered preferred activity
3312                        // component is no longer known.  Most likely an update
3313                        // to the app was installed and in the new version this
3314                        // component no longer exists.  Clean it up by removing
3315                        // it from the preferred activities list, and skip it.
3316                        Slog.w(TAG, "Removing dangling preferred activity: "
3317                                + pa.mPref.mComponent);
3318                        pir.removeFilter(pa);
3319                        continue;
3320                    }
3321                    for (int j=0; j<N; j++) {
3322                        final ResolveInfo ri = query.get(j);
3323                        if (!ri.activityInfo.applicationInfo.packageName
3324                                .equals(ai.applicationInfo.packageName)) {
3325                            continue;
3326                        }
3327                        if (!ri.activityInfo.name.equals(ai.name)) {
3328                            continue;
3329                        }
3330
3331                        if (removeMatches) {
3332                            pir.removeFilter(pa);
3333                            if (DEBUG_PREFERRED) {
3334                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3335                            }
3336                            break;
3337                        }
3338
3339                        // Okay we found a previously set preferred or last chosen app.
3340                        // If the result set is different from when this
3341                        // was created, we need to clear it and re-ask the
3342                        // user their preference, if we're looking for an "always" type entry.
3343                        if (always && !pa.mPref.sameSet(query, priority)) {
3344                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3345                                    + intent + " type " + resolvedType);
3346                            if (DEBUG_PREFERRED) {
3347                                Slog.v(TAG, "Removing preferred activity since set changed "
3348                                        + pa.mPref.mComponent);
3349                            }
3350                            pir.removeFilter(pa);
3351                            // Re-add the filter as a "last chosen" entry (!always)
3352                            PreferredActivity lastChosen = new PreferredActivity(
3353                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3354                            pir.addFilter(lastChosen);
3355                            mSettings.writePackageRestrictionsLPr(userId);
3356                            return null;
3357                        }
3358
3359                        // Yay! Either the set matched or we're looking for the last chosen
3360                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3361                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3362                        mSettings.writePackageRestrictionsLPr(userId);
3363                        return ri;
3364                    }
3365                }
3366            }
3367            mSettings.writePackageRestrictionsLPr(userId);
3368        }
3369        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3370        return null;
3371    }
3372
3373    /*
3374     * Returns if intent can be forwarded from the userId from to dest
3375     */
3376    @Override
3377    public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) {
3378        mContext.enforceCallingOrSelfPermission(
3379                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3380        List<ForwardingIntentFilter> matches =
3381                getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom);
3382        if (matches != null) {
3383            int size = matches.size();
3384            for (int i = 0; i < size; i++) {
3385                if (matches.get(i).getUserIdDest() == userIdDest) return true;
3386            }
3387        }
3388        return false;
3389    }
3390
3391    private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent,
3392            String resolvedType, int userId) {
3393        ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId);
3394        if (fir != null) {
3395            return fir.queryIntent(intent, resolvedType, false, userId);
3396        }
3397        return null;
3398    }
3399
3400    @Override
3401    public List<ResolveInfo> queryIntentActivities(Intent intent,
3402            String resolvedType, int flags, int userId) {
3403        if (!sUserManager.exists(userId)) return Collections.emptyList();
3404        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3405        ComponentName comp = intent.getComponent();
3406        if (comp == null) {
3407            if (intent.getSelector() != null) {
3408                intent = intent.getSelector();
3409                comp = intent.getComponent();
3410            }
3411        }
3412
3413        if (comp != null) {
3414            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3415            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3416            if (ai != null) {
3417                final ResolveInfo ri = new ResolveInfo();
3418                ri.activityInfo = ai;
3419                list.add(ri);
3420            }
3421            return list;
3422        }
3423
3424        // reader
3425        synchronized (mPackages) {
3426            final String pkgName = intent.getPackage();
3427            if (pkgName == null) {
3428                List<ResolveInfo> result =
3429                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3430                // Checking if we can forward the intent to another user
3431                List<ForwardingIntentFilter> fifs =
3432                        getMatchingForwardingIntentFilters(intent, resolvedType, userId);
3433                if (fifs != null) {
3434                    ForwardingIntentFilter forwardingIntentFilterWithResult = null;
3435                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3436                    for (ForwardingIntentFilter fif : fifs) {
3437                        int userIdDest = fif.getUserIdDest();
3438                        // Two {@link ForwardingIntentFilter}s can have the same userIdDest and
3439                        // match the same an intent. For performance reasons, it is better not to
3440                        // run queryIntent twice for the same userId
3441                        if (!alreadyTriedUserIds.contains(userIdDest)) {
3442                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3443                                    resolvedType, flags, userIdDest);
3444                            if (resultUser != null) {
3445                                forwardingIntentFilterWithResult = fif;
3446                                // As soon as there is a match in another user, we add the
3447                                // intentForwarderActivity to the list of ResolveInfo.
3448                                break;
3449                            }
3450                            alreadyTriedUserIds.add(userIdDest);
3451                        }
3452                    }
3453                    if (forwardingIntentFilterWithResult != null) {
3454                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3455                                forwardingIntentFilterWithResult, userId);
3456                        result.add(forwardingResolveInfo);
3457                    }
3458                }
3459                return result;
3460            }
3461            final PackageParser.Package pkg = mPackages.get(pkgName);
3462            if (pkg != null) {
3463                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3464                        pkg.activities, userId);
3465            }
3466            return new ArrayList<ResolveInfo>();
3467        }
3468    }
3469
3470    private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) {
3471        String className;
3472        int userIdDest = fif.getUserIdDest();
3473        if (userIdDest == UserHandle.USER_OWNER) {
3474            className = FORWARD_INTENT_TO_USER_OWNER;
3475        } else {
3476            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3477        }
3478        ComponentName forwardingActivityComponentName = new ComponentName(
3479                mAndroidApplication.packageName, className);
3480        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3481                userIdFrom);
3482        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3483        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3484        forwardingResolveInfo.priority = 0;
3485        forwardingResolveInfo.preferredOrder = 0;
3486        forwardingResolveInfo.match = 0;
3487        forwardingResolveInfo.isDefault = true;
3488        forwardingResolveInfo.filter = fif;
3489        return forwardingResolveInfo;
3490    }
3491
3492    @Override
3493    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3494            Intent[] specifics, String[] specificTypes, Intent intent,
3495            String resolvedType, int flags, int userId) {
3496        if (!sUserManager.exists(userId)) return Collections.emptyList();
3497        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3498                "query intent activity options");
3499        final String resultsAction = intent.getAction();
3500
3501        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3502                | PackageManager.GET_RESOLVED_FILTER, userId);
3503
3504        if (DEBUG_INTENT_MATCHING) {
3505            Log.v(TAG, "Query " + intent + ": " + results);
3506        }
3507
3508        int specificsPos = 0;
3509        int N;
3510
3511        // todo: note that the algorithm used here is O(N^2).  This
3512        // isn't a problem in our current environment, but if we start running
3513        // into situations where we have more than 5 or 10 matches then this
3514        // should probably be changed to something smarter...
3515
3516        // First we go through and resolve each of the specific items
3517        // that were supplied, taking care of removing any corresponding
3518        // duplicate items in the generic resolve list.
3519        if (specifics != null) {
3520            for (int i=0; i<specifics.length; i++) {
3521                final Intent sintent = specifics[i];
3522                if (sintent == null) {
3523                    continue;
3524                }
3525
3526                if (DEBUG_INTENT_MATCHING) {
3527                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3528                }
3529
3530                String action = sintent.getAction();
3531                if (resultsAction != null && resultsAction.equals(action)) {
3532                    // If this action was explicitly requested, then don't
3533                    // remove things that have it.
3534                    action = null;
3535                }
3536
3537                ResolveInfo ri = null;
3538                ActivityInfo ai = null;
3539
3540                ComponentName comp = sintent.getComponent();
3541                if (comp == null) {
3542                    ri = resolveIntent(
3543                        sintent,
3544                        specificTypes != null ? specificTypes[i] : null,
3545                            flags, userId);
3546                    if (ri == null) {
3547                        continue;
3548                    }
3549                    if (ri == mResolveInfo) {
3550                        // ACK!  Must do something better with this.
3551                    }
3552                    ai = ri.activityInfo;
3553                    comp = new ComponentName(ai.applicationInfo.packageName,
3554                            ai.name);
3555                } else {
3556                    ai = getActivityInfo(comp, flags, userId);
3557                    if (ai == null) {
3558                        continue;
3559                    }
3560                }
3561
3562                // Look for any generic query activities that are duplicates
3563                // of this specific one, and remove them from the results.
3564                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3565                N = results.size();
3566                int j;
3567                for (j=specificsPos; j<N; j++) {
3568                    ResolveInfo sri = results.get(j);
3569                    if ((sri.activityInfo.name.equals(comp.getClassName())
3570                            && sri.activityInfo.applicationInfo.packageName.equals(
3571                                    comp.getPackageName()))
3572                        || (action != null && sri.filter.matchAction(action))) {
3573                        results.remove(j);
3574                        if (DEBUG_INTENT_MATCHING) Log.v(
3575                            TAG, "Removing duplicate item from " + j
3576                            + " due to specific " + specificsPos);
3577                        if (ri == null) {
3578                            ri = sri;
3579                        }
3580                        j--;
3581                        N--;
3582                    }
3583                }
3584
3585                // Add this specific item to its proper place.
3586                if (ri == null) {
3587                    ri = new ResolveInfo();
3588                    ri.activityInfo = ai;
3589                }
3590                results.add(specificsPos, ri);
3591                ri.specificIndex = i;
3592                specificsPos++;
3593            }
3594        }
3595
3596        // Now we go through the remaining generic results and remove any
3597        // duplicate actions that are found here.
3598        N = results.size();
3599        for (int i=specificsPos; i<N-1; i++) {
3600            final ResolveInfo rii = results.get(i);
3601            if (rii.filter == null) {
3602                continue;
3603            }
3604
3605            // Iterate over all of the actions of this result's intent
3606            // filter...  typically this should be just one.
3607            final Iterator<String> it = rii.filter.actionsIterator();
3608            if (it == null) {
3609                continue;
3610            }
3611            while (it.hasNext()) {
3612                final String action = it.next();
3613                if (resultsAction != null && resultsAction.equals(action)) {
3614                    // If this action was explicitly requested, then don't
3615                    // remove things that have it.
3616                    continue;
3617                }
3618                for (int j=i+1; j<N; j++) {
3619                    final ResolveInfo rij = results.get(j);
3620                    if (rij.filter != null && rij.filter.hasAction(action)) {
3621                        results.remove(j);
3622                        if (DEBUG_INTENT_MATCHING) Log.v(
3623                            TAG, "Removing duplicate item from " + j
3624                            + " due to action " + action + " at " + i);
3625                        j--;
3626                        N--;
3627                    }
3628                }
3629            }
3630
3631            // If the caller didn't request filter information, drop it now
3632            // so we don't have to marshall/unmarshall it.
3633            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3634                rii.filter = null;
3635            }
3636        }
3637
3638        // Filter out the caller activity if so requested.
3639        if (caller != null) {
3640            N = results.size();
3641            for (int i=0; i<N; i++) {
3642                ActivityInfo ainfo = results.get(i).activityInfo;
3643                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3644                        && caller.getClassName().equals(ainfo.name)) {
3645                    results.remove(i);
3646                    break;
3647                }
3648            }
3649        }
3650
3651        // If the caller didn't request filter information,
3652        // drop them now so we don't have to
3653        // marshall/unmarshall it.
3654        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3655            N = results.size();
3656            for (int i=0; i<N; i++) {
3657                results.get(i).filter = null;
3658            }
3659        }
3660
3661        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3662        return results;
3663    }
3664
3665    @Override
3666    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3667            int userId) {
3668        if (!sUserManager.exists(userId)) return Collections.emptyList();
3669        ComponentName comp = intent.getComponent();
3670        if (comp == null) {
3671            if (intent.getSelector() != null) {
3672                intent = intent.getSelector();
3673                comp = intent.getComponent();
3674            }
3675        }
3676        if (comp != null) {
3677            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3678            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3679            if (ai != null) {
3680                ResolveInfo ri = new ResolveInfo();
3681                ri.activityInfo = ai;
3682                list.add(ri);
3683            }
3684            return list;
3685        }
3686
3687        // reader
3688        synchronized (mPackages) {
3689            String pkgName = intent.getPackage();
3690            if (pkgName == null) {
3691                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3692            }
3693            final PackageParser.Package pkg = mPackages.get(pkgName);
3694            if (pkg != null) {
3695                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3696                        userId);
3697            }
3698            return null;
3699        }
3700    }
3701
3702    @Override
3703    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3704        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3705        if (!sUserManager.exists(userId)) return null;
3706        if (query != null) {
3707            if (query.size() >= 1) {
3708                // If there is more than one service with the same priority,
3709                // just arbitrarily pick the first one.
3710                return query.get(0);
3711            }
3712        }
3713        return null;
3714    }
3715
3716    @Override
3717    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3718            int userId) {
3719        if (!sUserManager.exists(userId)) return Collections.emptyList();
3720        ComponentName comp = intent.getComponent();
3721        if (comp == null) {
3722            if (intent.getSelector() != null) {
3723                intent = intent.getSelector();
3724                comp = intent.getComponent();
3725            }
3726        }
3727        if (comp != null) {
3728            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3729            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3730            if (si != null) {
3731                final ResolveInfo ri = new ResolveInfo();
3732                ri.serviceInfo = si;
3733                list.add(ri);
3734            }
3735            return list;
3736        }
3737
3738        // reader
3739        synchronized (mPackages) {
3740            String pkgName = intent.getPackage();
3741            if (pkgName == null) {
3742                return mServices.queryIntent(intent, resolvedType, flags, userId);
3743            }
3744            final PackageParser.Package pkg = mPackages.get(pkgName);
3745            if (pkg != null) {
3746                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3747                        userId);
3748            }
3749            return null;
3750        }
3751    }
3752
3753    @Override
3754    public List<ResolveInfo> queryIntentContentProviders(
3755            Intent intent, String resolvedType, int flags, int userId) {
3756        if (!sUserManager.exists(userId)) return Collections.emptyList();
3757        ComponentName comp = intent.getComponent();
3758        if (comp == null) {
3759            if (intent.getSelector() != null) {
3760                intent = intent.getSelector();
3761                comp = intent.getComponent();
3762            }
3763        }
3764        if (comp != null) {
3765            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3766            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3767            if (pi != null) {
3768                final ResolveInfo ri = new ResolveInfo();
3769                ri.providerInfo = pi;
3770                list.add(ri);
3771            }
3772            return list;
3773        }
3774
3775        // reader
3776        synchronized (mPackages) {
3777            String pkgName = intent.getPackage();
3778            if (pkgName == null) {
3779                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3780            }
3781            final PackageParser.Package pkg = mPackages.get(pkgName);
3782            if (pkg != null) {
3783                return mProviders.queryIntentForPackage(
3784                        intent, resolvedType, flags, pkg.providers, userId);
3785            }
3786            return null;
3787        }
3788    }
3789
3790    @Override
3791    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3792        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3793
3794        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3795
3796        // writer
3797        synchronized (mPackages) {
3798            ArrayList<PackageInfo> list;
3799            if (listUninstalled) {
3800                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3801                for (PackageSetting ps : mSettings.mPackages.values()) {
3802                    PackageInfo pi;
3803                    if (ps.pkg != null) {
3804                        pi = generatePackageInfo(ps.pkg, flags, userId);
3805                    } else {
3806                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3807                    }
3808                    if (pi != null) {
3809                        list.add(pi);
3810                    }
3811                }
3812            } else {
3813                list = new ArrayList<PackageInfo>(mPackages.size());
3814                for (PackageParser.Package p : mPackages.values()) {
3815                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3816                    if (pi != null) {
3817                        list.add(pi);
3818                    }
3819                }
3820            }
3821
3822            return new ParceledListSlice<PackageInfo>(list);
3823        }
3824    }
3825
3826    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3827            String[] permissions, boolean[] tmp, int flags, int userId) {
3828        int numMatch = 0;
3829        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3830        for (int i=0; i<permissions.length; i++) {
3831            if (gp.grantedPermissions.contains(permissions[i])) {
3832                tmp[i] = true;
3833                numMatch++;
3834            } else {
3835                tmp[i] = false;
3836            }
3837        }
3838        if (numMatch == 0) {
3839            return;
3840        }
3841        PackageInfo pi;
3842        if (ps.pkg != null) {
3843            pi = generatePackageInfo(ps.pkg, flags, userId);
3844        } else {
3845            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3846        }
3847        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3848            if (numMatch == permissions.length) {
3849                pi.requestedPermissions = permissions;
3850            } else {
3851                pi.requestedPermissions = new String[numMatch];
3852                numMatch = 0;
3853                for (int i=0; i<permissions.length; i++) {
3854                    if (tmp[i]) {
3855                        pi.requestedPermissions[numMatch] = permissions[i];
3856                        numMatch++;
3857                    }
3858                }
3859            }
3860        }
3861        list.add(pi);
3862    }
3863
3864    @Override
3865    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3866            String[] permissions, int flags, int userId) {
3867        if (!sUserManager.exists(userId)) return null;
3868        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3869
3870        // writer
3871        synchronized (mPackages) {
3872            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3873            boolean[] tmpBools = new boolean[permissions.length];
3874            if (listUninstalled) {
3875                for (PackageSetting ps : mSettings.mPackages.values()) {
3876                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3877                }
3878            } else {
3879                for (PackageParser.Package pkg : mPackages.values()) {
3880                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3881                    if (ps != null) {
3882                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3883                                userId);
3884                    }
3885                }
3886            }
3887
3888            return new ParceledListSlice<PackageInfo>(list);
3889        }
3890    }
3891
3892    @Override
3893    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3896
3897        // writer
3898        synchronized (mPackages) {
3899            ArrayList<ApplicationInfo> list;
3900            if (listUninstalled) {
3901                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3902                for (PackageSetting ps : mSettings.mPackages.values()) {
3903                    ApplicationInfo ai;
3904                    if (ps.pkg != null) {
3905                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3906                                ps.readUserState(userId), userId);
3907                    } else {
3908                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3909                    }
3910                    if (ai != null) {
3911                        list.add(ai);
3912                    }
3913                }
3914            } else {
3915                list = new ArrayList<ApplicationInfo>(mPackages.size());
3916                for (PackageParser.Package p : mPackages.values()) {
3917                    if (p.mExtras != null) {
3918                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3919                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3920                        if (ai != null) {
3921                            list.add(ai);
3922                        }
3923                    }
3924                }
3925            }
3926
3927            return new ParceledListSlice<ApplicationInfo>(list);
3928        }
3929    }
3930
3931    public List<ApplicationInfo> getPersistentApplications(int flags) {
3932        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3933
3934        // reader
3935        synchronized (mPackages) {
3936            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3937            final int userId = UserHandle.getCallingUserId();
3938            while (i.hasNext()) {
3939                final PackageParser.Package p = i.next();
3940                if (p.applicationInfo != null
3941                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3942                        && (!mSafeMode || isSystemApp(p))) {
3943                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3944                    if (ps != null) {
3945                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3946                                ps.readUserState(userId), userId);
3947                        if (ai != null) {
3948                            finalList.add(ai);
3949                        }
3950                    }
3951                }
3952            }
3953        }
3954
3955        return finalList;
3956    }
3957
3958    @Override
3959    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3960        if (!sUserManager.exists(userId)) return null;
3961        // reader
3962        synchronized (mPackages) {
3963            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3964            PackageSetting ps = provider != null
3965                    ? mSettings.mPackages.get(provider.owner.packageName)
3966                    : null;
3967            return ps != null
3968                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3969                    && (!mSafeMode || (provider.info.applicationInfo.flags
3970                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3971                    ? PackageParser.generateProviderInfo(provider, flags,
3972                            ps.readUserState(userId), userId)
3973                    : null;
3974        }
3975    }
3976
3977    /**
3978     * @deprecated
3979     */
3980    @Deprecated
3981    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3982        // reader
3983        synchronized (mPackages) {
3984            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3985                    .entrySet().iterator();
3986            final int userId = UserHandle.getCallingUserId();
3987            while (i.hasNext()) {
3988                Map.Entry<String, PackageParser.Provider> entry = i.next();
3989                PackageParser.Provider p = entry.getValue();
3990                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3991
3992                if (ps != null && p.syncable
3993                        && (!mSafeMode || (p.info.applicationInfo.flags
3994                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3995                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3996                            ps.readUserState(userId), userId);
3997                    if (info != null) {
3998                        outNames.add(entry.getKey());
3999                        outInfo.add(info);
4000                    }
4001                }
4002            }
4003        }
4004    }
4005
4006    @Override
4007    public List<ProviderInfo> queryContentProviders(String processName,
4008            int uid, int flags) {
4009        ArrayList<ProviderInfo> finalList = null;
4010        // reader
4011        synchronized (mPackages) {
4012            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4013            final int userId = processName != null ?
4014                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4015            while (i.hasNext()) {
4016                final PackageParser.Provider p = i.next();
4017                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4018                if (ps != null && p.info.authority != null
4019                        && (processName == null
4020                                || (p.info.processName.equals(processName)
4021                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4022                        && mSettings.isEnabledLPr(p.info, flags, userId)
4023                        && (!mSafeMode
4024                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4025                    if (finalList == null) {
4026                        finalList = new ArrayList<ProviderInfo>(3);
4027                    }
4028                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4029                            ps.readUserState(userId), userId);
4030                    if (info != null) {
4031                        finalList.add(info);
4032                    }
4033                }
4034            }
4035        }
4036
4037        if (finalList != null) {
4038            Collections.sort(finalList, mProviderInitOrderSorter);
4039        }
4040
4041        return finalList;
4042    }
4043
4044    @Override
4045    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4046            int flags) {
4047        // reader
4048        synchronized (mPackages) {
4049            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4050            return PackageParser.generateInstrumentationInfo(i, flags);
4051        }
4052    }
4053
4054    @Override
4055    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4056            int flags) {
4057        ArrayList<InstrumentationInfo> finalList =
4058            new ArrayList<InstrumentationInfo>();
4059
4060        // reader
4061        synchronized (mPackages) {
4062            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4063            while (i.hasNext()) {
4064                final PackageParser.Instrumentation p = i.next();
4065                if (targetPackage == null
4066                        || targetPackage.equals(p.info.targetPackage)) {
4067                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4068                            flags);
4069                    if (ii != null) {
4070                        finalList.add(ii);
4071                    }
4072                }
4073            }
4074        }
4075
4076        return finalList;
4077    }
4078
4079    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4080        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4081        if (overlays == null) {
4082            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4083            return;
4084        }
4085        for (PackageParser.Package opkg : overlays.values()) {
4086            // Not much to do if idmap fails: we already logged the error
4087            // and we certainly don't want to abort installation of pkg simply
4088            // because an overlay didn't fit properly. For these reasons,
4089            // ignore the return value of createIdmapForPackagePairLI.
4090            createIdmapForPackagePairLI(pkg, opkg);
4091        }
4092    }
4093
4094    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4095            PackageParser.Package opkg) {
4096        if (!opkg.mTrustedOverlay) {
4097            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4098                    opkg.mScanPath + ": overlay not trusted");
4099            return false;
4100        }
4101        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4102        if (overlaySet == null) {
4103            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4104                    opkg.mScanPath + " but target package has no known overlays");
4105            return false;
4106        }
4107        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4108        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4109            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4110            return false;
4111        }
4112        PackageParser.Package[] overlayArray =
4113            overlaySet.values().toArray(new PackageParser.Package[0]);
4114        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4115            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4116                return p1.mOverlayPriority - p2.mOverlayPriority;
4117            }
4118        };
4119        Arrays.sort(overlayArray, cmp);
4120
4121        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4122        int i = 0;
4123        for (PackageParser.Package p : overlayArray) {
4124            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4125        }
4126        return true;
4127    }
4128
4129    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4130        String[] files = dir.list();
4131        if (files == null) {
4132            Log.d(TAG, "No files in app dir " + dir);
4133            return;
4134        }
4135
4136        if (DEBUG_PACKAGE_SCANNING) {
4137            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4138                    + " flags=0x" + Integer.toHexString(flags));
4139        }
4140
4141        int i;
4142        for (i=0; i<files.length; i++) {
4143            File file = new File(dir, files[i]);
4144            if (!isPackageFilename(files[i])) {
4145                // Ignore entries which are not apk's
4146                continue;
4147            }
4148            PackageParser.Package pkg = scanPackageLI(file,
4149                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4150            // Don't mess around with apps in system partition.
4151            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4152                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4153                // Delete the apk
4154                Slog.w(TAG, "Cleaning up failed install of " + file);
4155                file.delete();
4156            }
4157        }
4158    }
4159
4160    private static File getSettingsProblemFile() {
4161        File dataDir = Environment.getDataDirectory();
4162        File systemDir = new File(dataDir, "system");
4163        File fname = new File(systemDir, "uiderrors.txt");
4164        return fname;
4165    }
4166
4167    static void reportSettingsProblem(int priority, String msg) {
4168        try {
4169            File fname = getSettingsProblemFile();
4170            FileOutputStream out = new FileOutputStream(fname, true);
4171            PrintWriter pw = new FastPrintWriter(out);
4172            SimpleDateFormat formatter = new SimpleDateFormat();
4173            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4174            pw.println(dateString + ": " + msg);
4175            pw.close();
4176            FileUtils.setPermissions(
4177                    fname.toString(),
4178                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4179                    -1, -1);
4180        } catch (java.io.IOException e) {
4181        }
4182        Slog.println(priority, TAG, msg);
4183    }
4184
4185    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4186            PackageParser.Package pkg, File srcFile, int parseFlags) {
4187        if (ps != null
4188                && ps.codePath.equals(srcFile)
4189                && ps.timeStamp == srcFile.lastModified()
4190                && !isCompatSignatureUpdateNeeded(pkg)) {
4191            if (ps.signatures.mSignatures != null
4192                    && ps.signatures.mSignatures.length != 0) {
4193                // Optimization: reuse the existing cached certificates
4194                // if the package appears to be unchanged.
4195                pkg.mSignatures = ps.signatures.mSignatures;
4196                return true;
4197            }
4198
4199            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4200        } else {
4201            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4202        }
4203
4204        if (!pp.collectCertificates(pkg, parseFlags)) {
4205            mLastScanError = pp.getParseError();
4206            return false;
4207        }
4208        return true;
4209    }
4210
4211    /*
4212     *  Scan a package and return the newly parsed package.
4213     *  Returns null in case of errors and the error code is stored in mLastScanError
4214     */
4215    private PackageParser.Package scanPackageLI(File scanFile,
4216            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4217        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4218        String scanPath = scanFile.getPath();
4219        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4220        parseFlags |= mDefParseFlags;
4221        PackageParser pp = new PackageParser(scanPath);
4222        pp.setSeparateProcesses(mSeparateProcesses);
4223        pp.setOnlyCoreApps(mOnlyCore);
4224        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4225                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4226
4227        if (pkg == null) {
4228            mLastScanError = pp.getParseError();
4229            return null;
4230        }
4231
4232        PackageSetting ps = null;
4233        PackageSetting updatedPkg;
4234        // reader
4235        synchronized (mPackages) {
4236            // Look to see if we already know about this package.
4237            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4238            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4239                // This package has been renamed to its original name.  Let's
4240                // use that.
4241                ps = mSettings.peekPackageLPr(oldName);
4242            }
4243            // If there was no original package, see one for the real package name.
4244            if (ps == null) {
4245                ps = mSettings.peekPackageLPr(pkg.packageName);
4246            }
4247            // Check to see if this package could be hiding/updating a system
4248            // package.  Must look for it either under the original or real
4249            // package name depending on our state.
4250            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4251            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4252        }
4253        boolean updatedPkgBetter = false;
4254        // First check if this is a system package that may involve an update
4255        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4256            if (ps != null && !ps.codePath.equals(scanFile)) {
4257                // The path has changed from what was last scanned...  check the
4258                // version of the new path against what we have stored to determine
4259                // what to do.
4260                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4261                if (pkg.mVersionCode < ps.versionCode) {
4262                    // The system package has been updated and the code path does not match
4263                    // Ignore entry. Skip it.
4264                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4265                            + " ignored: updated version " + ps.versionCode
4266                            + " better than this " + pkg.mVersionCode);
4267                    if (!updatedPkg.codePath.equals(scanFile)) {
4268                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4269                                + ps.name + " changing from " + updatedPkg.codePathString
4270                                + " to " + scanFile);
4271                        updatedPkg.codePath = scanFile;
4272                        updatedPkg.codePathString = scanFile.toString();
4273                        // This is the point at which we know that the system-disk APK
4274                        // for this package has moved during a reboot (e.g. due to an OTA),
4275                        // so we need to reevaluate it for privilege policy.
4276                        if (locationIsPrivileged(scanFile)) {
4277                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4278                        }
4279                    }
4280                    updatedPkg.pkg = pkg;
4281                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4282                    return null;
4283                } else {
4284                    // The current app on the system partion is better than
4285                    // what we have updated to on the data partition; switch
4286                    // back to the system partition version.
4287                    // At this point, its safely assumed that package installation for
4288                    // apps in system partition will go through. If not there won't be a working
4289                    // version of the app
4290                    // writer
4291                    synchronized (mPackages) {
4292                        // Just remove the loaded entries from package lists.
4293                        mPackages.remove(ps.name);
4294                    }
4295                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4296                            + "reverting from " + ps.codePathString
4297                            + ": new version " + pkg.mVersionCode
4298                            + " better than installed " + ps.versionCode);
4299
4300                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4301                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4302                            getAppInstructionSetFromSettings(ps));
4303                    synchronized (mInstallLock) {
4304                        args.cleanUpResourcesLI();
4305                    }
4306                    synchronized (mPackages) {
4307                        mSettings.enableSystemPackageLPw(ps.name);
4308                    }
4309                    updatedPkgBetter = true;
4310                }
4311            }
4312        }
4313
4314        if (updatedPkg != null) {
4315            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4316            // initially
4317            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4318
4319            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4320            // flag set initially
4321            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4322                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4323            }
4324        }
4325        // Verify certificates against what was last scanned
4326        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4327            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4328            return null;
4329        }
4330
4331        /*
4332         * A new system app appeared, but we already had a non-system one of the
4333         * same name installed earlier.
4334         */
4335        boolean shouldHideSystemApp = false;
4336        if (updatedPkg == null && ps != null
4337                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4338            /*
4339             * Check to make sure the signatures match first. If they don't,
4340             * wipe the installed application and its data.
4341             */
4342            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4343                    != PackageManager.SIGNATURE_MATCH) {
4344                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4345                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4346                ps = null;
4347            } else {
4348                /*
4349                 * If the newly-added system app is an older version than the
4350                 * already installed version, hide it. It will be scanned later
4351                 * and re-added like an update.
4352                 */
4353                if (pkg.mVersionCode < ps.versionCode) {
4354                    shouldHideSystemApp = true;
4355                } else {
4356                    /*
4357                     * The newly found system app is a newer version that the
4358                     * one previously installed. Simply remove the
4359                     * already-installed application and replace it with our own
4360                     * while keeping the application data.
4361                     */
4362                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4363                            + ps.codePathString + ": new version " + pkg.mVersionCode
4364                            + " better than installed " + ps.versionCode);
4365                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4366                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4367                            getAppInstructionSetFromSettings(ps));
4368                    synchronized (mInstallLock) {
4369                        args.cleanUpResourcesLI();
4370                    }
4371                }
4372            }
4373        }
4374
4375        // The apk is forward locked (not public) if its code and resources
4376        // are kept in different files. (except for app in either system or
4377        // vendor path).
4378        // TODO grab this value from PackageSettings
4379        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4380            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4381                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4382            }
4383        }
4384
4385        String codePath = null;
4386        String resPath = null;
4387        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4388            if (ps != null && ps.resourcePathString != null) {
4389                resPath = ps.resourcePathString;
4390            } else {
4391                // Should not happen at all. Just log an error.
4392                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4393            }
4394        } else {
4395            resPath = pkg.mScanPath;
4396        }
4397
4398        codePath = pkg.mScanPath;
4399        // Set application objects path explicitly.
4400        setApplicationInfoPaths(pkg, codePath, resPath);
4401        // Note that we invoke the following method only if we are about to unpack an application
4402        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4403                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4404
4405        /*
4406         * If the system app should be overridden by a previously installed
4407         * data, hide the system app now and let the /data/app scan pick it up
4408         * again.
4409         */
4410        if (shouldHideSystemApp) {
4411            synchronized (mPackages) {
4412                /*
4413                 * We have to grant systems permissions before we hide, because
4414                 * grantPermissions will assume the package update is trying to
4415                 * expand its permissions.
4416                 */
4417                grantPermissionsLPw(pkg, true);
4418                mSettings.disableSystemPackageLPw(pkg.packageName);
4419            }
4420        }
4421
4422        return scannedPkg;
4423    }
4424
4425    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4426            String destResPath) {
4427        pkg.mPath = pkg.mScanPath = destCodePath;
4428        pkg.applicationInfo.sourceDir = destCodePath;
4429        pkg.applicationInfo.publicSourceDir = destResPath;
4430    }
4431
4432    private static String fixProcessName(String defProcessName,
4433            String processName, int uid) {
4434        if (processName == null) {
4435            return defProcessName;
4436        }
4437        return processName;
4438    }
4439
4440    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4441        if (pkgSetting.signatures.mSignatures != null) {
4442            // Already existing package. Make sure signatures match
4443            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4444                    == PackageManager.SIGNATURE_MATCH;
4445            if (!match) {
4446                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4447                        == PackageManager.SIGNATURE_MATCH;
4448            }
4449            if (!match) {
4450                Slog.e(TAG, "Package " + pkg.packageName
4451                        + " signatures do not match the previously installed version; ignoring!");
4452                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4453                return false;
4454            }
4455        }
4456        // Check for shared user signatures
4457        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4458            // Already existing package. Make sure signatures match
4459            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4460                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4461            if (!match) {
4462                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4463                        == PackageManager.SIGNATURE_MATCH;
4464            }
4465            if (!match) {
4466                Slog.e(TAG, "Package " + pkg.packageName
4467                        + " has no signatures that match those in shared user "
4468                        + pkgSetting.sharedUser.name + "; ignoring!");
4469                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4470                return false;
4471            }
4472        }
4473        return true;
4474    }
4475
4476    /**
4477     * Enforces that only the system UID or root's UID can call a method exposed
4478     * via Binder.
4479     *
4480     * @param message used as message if SecurityException is thrown
4481     * @throws SecurityException if the caller is not system or root
4482     */
4483    private static final void enforceSystemOrRoot(String message) {
4484        final int uid = Binder.getCallingUid();
4485        if (uid != Process.SYSTEM_UID && uid != 0) {
4486            throw new SecurityException(message);
4487        }
4488    }
4489
4490    @Override
4491    public void performBootDexOpt() {
4492        enforceSystemOrRoot("Only the system can request dexopt be performed");
4493
4494        final HashSet<PackageParser.Package> pkgs;
4495        synchronized (mPackages) {
4496            pkgs = mDeferredDexOpt;
4497            mDeferredDexOpt = null;
4498        }
4499
4500        if (pkgs != null) {
4501            // Filter out packages that aren't recently used.
4502            //
4503            // The exception is first boot of a non-eng device, which
4504            // should do a full dexopt.
4505            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4506            if (eng || !isFirstBoot()) {
4507                // TODO: add a property to control this?
4508                long dexOptLRUThresholdInMinutes;
4509                if (eng) {
4510                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4511                } else {
4512                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4513                }
4514                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4515
4516                int total = pkgs.size();
4517                int skipped = 0;
4518                long now = System.currentTimeMillis();
4519                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4520                    PackageParser.Package pkg = i.next();
4521                    long then = pkg.mLastPackageUsageTimeInMills;
4522                    if (then + dexOptLRUThresholdInMills < now) {
4523                        if (DEBUG_DEXOPT) {
4524                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4525                                  ((then == 0) ? "never" : new Date(then)));
4526                        }
4527                        i.remove();
4528                        skipped++;
4529                    }
4530                }
4531                if (DEBUG_DEXOPT) {
4532                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4533                }
4534            }
4535
4536            int i = 0;
4537            for (PackageParser.Package pkg : pkgs) {
4538                i++;
4539                if (DEBUG_DEXOPT) {
4540                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4541                          + ": " + pkg.packageName);
4542                }
4543                if (!isFirstBoot()) {
4544                    try {
4545                        ActivityManagerNative.getDefault().showBootMessage(
4546                                mContext.getResources().getString(
4547                                        R.string.android_upgrading_apk,
4548                                        i, pkgs.size()), true);
4549                    } catch (RemoteException e) {
4550                    }
4551                }
4552                PackageParser.Package p = pkg;
4553                synchronized (mInstallLock) {
4554                    if (p.mDexOptNeeded) {
4555                        performDexOptLI(p, false /* force dex */, false /* defer */,
4556                                true /* include dependencies */);
4557                    }
4558                }
4559            }
4560        }
4561    }
4562
4563    @Override
4564    public boolean performDexOpt(String packageName) {
4565        enforceSystemOrRoot("Only the system can request dexopt be performed");
4566        return performDexOpt(packageName, true);
4567    }
4568
4569    public boolean performDexOpt(String packageName, boolean updateUsage) {
4570
4571        PackageParser.Package p;
4572        synchronized (mPackages) {
4573            p = mPackages.get(packageName);
4574            if (p == null) {
4575                return false;
4576            }
4577            if (updateUsage) {
4578                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4579            }
4580            mPackageUsage.write(false);
4581            if (!p.mDexOptNeeded) {
4582                return false;
4583            }
4584        }
4585
4586        synchronized (mInstallLock) {
4587            return performDexOptLI(p, false /* force dex */, false /* defer */,
4588                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4589        }
4590    }
4591
4592    public HashSet<String> getPackagesThatNeedDexOpt() {
4593        HashSet<String> pkgs = null;
4594        synchronized (mPackages) {
4595            for (PackageParser.Package p : mPackages.values()) {
4596                if (DEBUG_DEXOPT) {
4597                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4598                }
4599                if (!p.mDexOptNeeded) {
4600                    continue;
4601                }
4602                if (pkgs == null) {
4603                    pkgs = new HashSet<String>();
4604                }
4605                pkgs.add(p.packageName);
4606            }
4607        }
4608        return pkgs;
4609    }
4610
4611    public void shutdown() {
4612        mPackageUsage.write(true);
4613    }
4614
4615    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4616             boolean forceDex, boolean defer, HashSet<String> done) {
4617        for (int i=0; i<libs.size(); i++) {
4618            PackageParser.Package libPkg;
4619            String libName;
4620            synchronized (mPackages) {
4621                libName = libs.get(i);
4622                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4623                if (lib != null && lib.apk != null) {
4624                    libPkg = mPackages.get(lib.apk);
4625                } else {
4626                    libPkg = null;
4627                }
4628            }
4629            if (libPkg != null && !done.contains(libName)) {
4630                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4631            }
4632        }
4633    }
4634
4635    static final int DEX_OPT_SKIPPED = 0;
4636    static final int DEX_OPT_PERFORMED = 1;
4637    static final int DEX_OPT_DEFERRED = 2;
4638    static final int DEX_OPT_FAILED = -1;
4639
4640    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4641            boolean forceDex, boolean defer, HashSet<String> done) {
4642        final String instructionSet = instructionSetOverride != null ?
4643                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4644
4645        if (done != null) {
4646            done.add(pkg.packageName);
4647            if (pkg.usesLibraries != null) {
4648                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4649            }
4650            if (pkg.usesOptionalLibraries != null) {
4651                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4652            }
4653        }
4654
4655        boolean performed = false;
4656        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4657            String path = pkg.mScanPath;
4658            try {
4659                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4660                                                                                pkg.packageName,
4661                                                                                instructionSet,
4662                                                                                defer);
4663                // There are three basic cases here:
4664                // 1.) we need to dexopt, either because we are forced or it is needed
4665                // 2.) we are defering a needed dexopt
4666                // 3.) we are skipping an unneeded dexopt
4667                if (forceDex || (!defer && isDexOptNeededInternal)) {
4668                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4669                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4670                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4671                                                pkg.packageName, instructionSet);
4672                    // Note that we ran dexopt, since rerunning will
4673                    // probably just result in an error again.
4674                    pkg.mDexOptNeeded = false;
4675                    if (ret < 0) {
4676                        return DEX_OPT_FAILED;
4677                    }
4678                    return DEX_OPT_PERFORMED;
4679                }
4680                if (defer && isDexOptNeededInternal) {
4681                    if (mDeferredDexOpt == null) {
4682                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4683                    }
4684                    mDeferredDexOpt.add(pkg);
4685                    return DEX_OPT_DEFERRED;
4686                }
4687                pkg.mDexOptNeeded = false;
4688                return DEX_OPT_SKIPPED;
4689            } catch (FileNotFoundException e) {
4690                Slog.w(TAG, "Apk not found for dexopt: " + path);
4691                return DEX_OPT_FAILED;
4692            } catch (IOException e) {
4693                Slog.w(TAG, "IOException reading apk: " + path, e);
4694                return DEX_OPT_FAILED;
4695            } catch (StaleDexCacheError e) {
4696                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4697                return DEX_OPT_FAILED;
4698            } catch (Exception e) {
4699                Slog.w(TAG, "Exception when doing dexopt : ", e);
4700                return DEX_OPT_FAILED;
4701            }
4702        }
4703        return DEX_OPT_SKIPPED;
4704    }
4705
4706    private String getAppInstructionSet(ApplicationInfo info) {
4707        String instructionSet = getPreferredInstructionSet();
4708
4709        if (info.cpuAbi != null) {
4710            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4711        }
4712
4713        return instructionSet;
4714    }
4715
4716    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4717        String instructionSet = getPreferredInstructionSet();
4718
4719        if (ps.cpuAbiString != null) {
4720            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4721        }
4722
4723        return instructionSet;
4724    }
4725
4726    private static String getPreferredInstructionSet() {
4727        if (sPreferredInstructionSet == null) {
4728            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4729        }
4730
4731        return sPreferredInstructionSet;
4732    }
4733
4734    private static List<String> getAllInstructionSets() {
4735        final String[] allAbis = Build.SUPPORTED_ABIS;
4736        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4737
4738        for (String abi : allAbis) {
4739            final String instructionSet = VMRuntime.getInstructionSet(abi);
4740            if (!allInstructionSets.contains(instructionSet)) {
4741                allInstructionSets.add(instructionSet);
4742            }
4743        }
4744
4745        return allInstructionSets;
4746    }
4747
4748    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4749            boolean inclDependencies) {
4750        HashSet<String> done;
4751        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4752            done = new HashSet<String>();
4753            done.add(pkg.packageName);
4754        } else {
4755            done = null;
4756        }
4757        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4758    }
4759
4760    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4761        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4762            Slog.w(TAG, "Unable to update from " + oldPkg.name
4763                    + " to " + newPkg.packageName
4764                    + ": old package not in system partition");
4765            return false;
4766        } else if (mPackages.get(oldPkg.name) != null) {
4767            Slog.w(TAG, "Unable to update from " + oldPkg.name
4768                    + " to " + newPkg.packageName
4769                    + ": old package still exists");
4770            return false;
4771        }
4772        return true;
4773    }
4774
4775    File getDataPathForUser(int userId) {
4776        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4777    }
4778
4779    private File getDataPathForPackage(String packageName, int userId) {
4780        /*
4781         * Until we fully support multiple users, return the directory we
4782         * previously would have. The PackageManagerTests will need to be
4783         * revised when this is changed back..
4784         */
4785        if (userId == 0) {
4786            return new File(mAppDataDir, packageName);
4787        } else {
4788            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4789                + File.separator + packageName);
4790        }
4791    }
4792
4793    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4794        int[] users = sUserManager.getUserIds();
4795        int res = mInstaller.install(packageName, uid, uid, seinfo);
4796        if (res < 0) {
4797            return res;
4798        }
4799        for (int user : users) {
4800            if (user != 0) {
4801                res = mInstaller.createUserData(packageName,
4802                        UserHandle.getUid(user, uid), user, seinfo);
4803                if (res < 0) {
4804                    return res;
4805                }
4806            }
4807        }
4808        return res;
4809    }
4810
4811    private int removeDataDirsLI(String packageName) {
4812        int[] users = sUserManager.getUserIds();
4813        int res = 0;
4814        for (int user : users) {
4815            int resInner = mInstaller.remove(packageName, user);
4816            if (resInner < 0) {
4817                res = resInner;
4818            }
4819        }
4820
4821        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4822        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4823        if (!nativeLibraryFile.delete()) {
4824            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4825        }
4826
4827        return res;
4828    }
4829
4830    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4831            PackageParser.Package changingLib) {
4832        if (file.path != null) {
4833            mTmpSharedLibraries[num] = file.path;
4834            return num+1;
4835        }
4836        PackageParser.Package p = mPackages.get(file.apk);
4837        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4838            // If we are doing this while in the middle of updating a library apk,
4839            // then we need to make sure to use that new apk for determining the
4840            // dependencies here.  (We haven't yet finished committing the new apk
4841            // to the package manager state.)
4842            if (p == null || p.packageName.equals(changingLib.packageName)) {
4843                p = changingLib;
4844            }
4845        }
4846        if (p != null) {
4847            String path = p.mPath;
4848            for (int i=0; i<num; i++) {
4849                if (mTmpSharedLibraries[i].equals(path)) {
4850                    return num;
4851                }
4852            }
4853            mTmpSharedLibraries[num] = p.mPath;
4854            return num+1;
4855        }
4856        return num;
4857    }
4858
4859    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4860            PackageParser.Package changingLib) {
4861        // We might be upgrading from a version of the platform that did not
4862        // provide per-package native library directories for system apps.
4863        // Fix that up here.
4864        if (isSystemApp(pkg)) {
4865            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4866            setInternalAppNativeLibraryPath(pkg, ps);
4867        }
4868
4869        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4870            if (mTmpSharedLibraries == null ||
4871                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4872                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4873            }
4874            int num = 0;
4875            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4876            for (int i=0; i<N; i++) {
4877                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4878                if (file == null) {
4879                    Slog.e(TAG, "Package " + pkg.packageName
4880                            + " requires unavailable shared library "
4881                            + pkg.usesLibraries.get(i) + "; failing!");
4882                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4883                    return false;
4884                }
4885                num = addSharedLibraryLPw(file, num, changingLib);
4886            }
4887            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4888            for (int i=0; i<N; i++) {
4889                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4890                if (file == null) {
4891                    Slog.w(TAG, "Package " + pkg.packageName
4892                            + " desires unavailable shared library "
4893                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4894                } else {
4895                    num = addSharedLibraryLPw(file, num, changingLib);
4896                }
4897            }
4898            if (num > 0) {
4899                pkg.usesLibraryFiles = new String[num];
4900                System.arraycopy(mTmpSharedLibraries, 0,
4901                        pkg.usesLibraryFiles, 0, num);
4902            } else {
4903                pkg.usesLibraryFiles = null;
4904            }
4905        }
4906        return true;
4907    }
4908
4909    private static boolean hasString(List<String> list, List<String> which) {
4910        if (list == null) {
4911            return false;
4912        }
4913        for (int i=list.size()-1; i>=0; i--) {
4914            for (int j=which.size()-1; j>=0; j--) {
4915                if (which.get(j).equals(list.get(i))) {
4916                    return true;
4917                }
4918            }
4919        }
4920        return false;
4921    }
4922
4923    private void updateAllSharedLibrariesLPw() {
4924        for (PackageParser.Package pkg : mPackages.values()) {
4925            updateSharedLibrariesLPw(pkg, null);
4926        }
4927    }
4928
4929    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4930            PackageParser.Package changingPkg) {
4931        ArrayList<PackageParser.Package> res = null;
4932        for (PackageParser.Package pkg : mPackages.values()) {
4933            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4934                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4935                if (res == null) {
4936                    res = new ArrayList<PackageParser.Package>();
4937                }
4938                res.add(pkg);
4939                updateSharedLibrariesLPw(pkg, changingPkg);
4940            }
4941        }
4942        return res;
4943    }
4944
4945    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4946            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4947        File scanFile = new File(pkg.mScanPath);
4948        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4949                pkg.applicationInfo.publicSourceDir == null) {
4950            // Bail out. The resource and code paths haven't been set.
4951            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4952            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4953            return null;
4954        }
4955
4956        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4957            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4958        }
4959
4960        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4961            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4962        }
4963
4964        if (mCustomResolverComponentName != null &&
4965                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4966            setUpCustomResolverActivity(pkg);
4967        }
4968
4969        if (pkg.packageName.equals("android")) {
4970            synchronized (mPackages) {
4971                if (mAndroidApplication != null) {
4972                    Slog.w(TAG, "*************************************************");
4973                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4974                    Slog.w(TAG, " file=" + scanFile);
4975                    Slog.w(TAG, "*************************************************");
4976                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4977                    return null;
4978                }
4979
4980                // Set up information for our fall-back user intent resolution activity.
4981                mPlatformPackage = pkg;
4982                pkg.mVersionCode = mSdkVersion;
4983                mAndroidApplication = pkg.applicationInfo;
4984
4985                if (!mResolverReplaced) {
4986                    mResolveActivity.applicationInfo = mAndroidApplication;
4987                    mResolveActivity.name = ResolverActivity.class.getName();
4988                    mResolveActivity.packageName = mAndroidApplication.packageName;
4989                    mResolveActivity.processName = "system:ui";
4990                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4991                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4992                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4993                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4994                    mResolveActivity.exported = true;
4995                    mResolveActivity.enabled = true;
4996                    mResolveInfo.activityInfo = mResolveActivity;
4997                    mResolveInfo.priority = 0;
4998                    mResolveInfo.preferredOrder = 0;
4999                    mResolveInfo.match = 0;
5000                    mResolveComponentName = new ComponentName(
5001                            mAndroidApplication.packageName, mResolveActivity.name);
5002                }
5003            }
5004        }
5005
5006        if (DEBUG_PACKAGE_SCANNING) {
5007            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5008                Log.d(TAG, "Scanning package " + pkg.packageName);
5009        }
5010
5011        if (mPackages.containsKey(pkg.packageName)
5012                || mSharedLibraries.containsKey(pkg.packageName)) {
5013            Slog.w(TAG, "Application package " + pkg.packageName
5014                    + " already installed.  Skipping duplicate.");
5015            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5016            return null;
5017        }
5018
5019        // Initialize package source and resource directories
5020        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
5021        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
5022
5023        SharedUserSetting suid = null;
5024        PackageSetting pkgSetting = null;
5025
5026        if (!isSystemApp(pkg)) {
5027            // Only system apps can use these features.
5028            pkg.mOriginalPackages = null;
5029            pkg.mRealPackage = null;
5030            pkg.mAdoptPermissions = null;
5031        }
5032
5033        // writer
5034        synchronized (mPackages) {
5035            if (pkg.mSharedUserId != null) {
5036                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5037                if (suid == null) {
5038                    Slog.w(TAG, "Creating application package " + pkg.packageName
5039                            + " for shared user failed");
5040                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5041                    return null;
5042                }
5043                if (DEBUG_PACKAGE_SCANNING) {
5044                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5045                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5046                                + "): packages=" + suid.packages);
5047                }
5048            }
5049
5050            // Check if we are renaming from an original package name.
5051            PackageSetting origPackage = null;
5052            String realName = null;
5053            if (pkg.mOriginalPackages != null) {
5054                // This package may need to be renamed to a previously
5055                // installed name.  Let's check on that...
5056                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5057                if (pkg.mOriginalPackages.contains(renamed)) {
5058                    // This package had originally been installed as the
5059                    // original name, and we have already taken care of
5060                    // transitioning to the new one.  Just update the new
5061                    // one to continue using the old name.
5062                    realName = pkg.mRealPackage;
5063                    if (!pkg.packageName.equals(renamed)) {
5064                        // Callers into this function may have already taken
5065                        // care of renaming the package; only do it here if
5066                        // it is not already done.
5067                        pkg.setPackageName(renamed);
5068                    }
5069
5070                } else {
5071                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5072                        if ((origPackage = mSettings.peekPackageLPr(
5073                                pkg.mOriginalPackages.get(i))) != null) {
5074                            // We do have the package already installed under its
5075                            // original name...  should we use it?
5076                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5077                                // New package is not compatible with original.
5078                                origPackage = null;
5079                                continue;
5080                            } else if (origPackage.sharedUser != null) {
5081                                // Make sure uid is compatible between packages.
5082                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5083                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5084                                            + " to " + pkg.packageName + ": old uid "
5085                                            + origPackage.sharedUser.name
5086                                            + " differs from " + pkg.mSharedUserId);
5087                                    origPackage = null;
5088                                    continue;
5089                                }
5090                            } else {
5091                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5092                                        + pkg.packageName + " to old name " + origPackage.name);
5093                            }
5094                            break;
5095                        }
5096                    }
5097                }
5098            }
5099
5100            if (mTransferedPackages.contains(pkg.packageName)) {
5101                Slog.w(TAG, "Package " + pkg.packageName
5102                        + " was transferred to another, but its .apk remains");
5103            }
5104
5105            // Just create the setting, don't add it yet. For already existing packages
5106            // the PkgSetting exists already and doesn't have to be created.
5107            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5108                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5109                    pkg.applicationInfo.cpuAbi,
5110                    pkg.applicationInfo.flags, user, false);
5111            if (pkgSetting == null) {
5112                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5113                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5114                return null;
5115            }
5116
5117            if (pkgSetting.origPackage != null) {
5118                // If we are first transitioning from an original package,
5119                // fix up the new package's name now.  We need to do this after
5120                // looking up the package under its new name, so getPackageLP
5121                // can take care of fiddling things correctly.
5122                pkg.setPackageName(origPackage.name);
5123
5124                // File a report about this.
5125                String msg = "New package " + pkgSetting.realName
5126                        + " renamed to replace old package " + pkgSetting.name;
5127                reportSettingsProblem(Log.WARN, msg);
5128
5129                // Make a note of it.
5130                mTransferedPackages.add(origPackage.name);
5131
5132                // No longer need to retain this.
5133                pkgSetting.origPackage = null;
5134            }
5135
5136            if (realName != null) {
5137                // Make a note of it.
5138                mTransferedPackages.add(pkg.packageName);
5139            }
5140
5141            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5142                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5143            }
5144
5145            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5146                // Check all shared libraries and map to their actual file path.
5147                // We only do this here for apps not on a system dir, because those
5148                // are the only ones that can fail an install due to this.  We
5149                // will take care of the system apps by updating all of their
5150                // library paths after the scan is done.
5151                if (!updateSharedLibrariesLPw(pkg, null)) {
5152                    return null;
5153                }
5154            }
5155
5156            if (mFoundPolicyFile) {
5157                SELinuxMMAC.assignSeinfoValue(pkg);
5158            }
5159
5160            pkg.applicationInfo.uid = pkgSetting.appId;
5161            pkg.mExtras = pkgSetting;
5162
5163            if (!verifySignaturesLP(pkgSetting, pkg)) {
5164                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5165                    return null;
5166                }
5167                // The signature has changed, but this package is in the system
5168                // image...  let's recover!
5169                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5170                // However...  if this package is part of a shared user, but it
5171                // doesn't match the signature of the shared user, let's fail.
5172                // What this means is that you can't change the signatures
5173                // associated with an overall shared user, which doesn't seem all
5174                // that unreasonable.
5175                if (pkgSetting.sharedUser != null) {
5176                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5177                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5178                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5179                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5180                        return null;
5181                    }
5182                }
5183                // File a report about this.
5184                String msg = "System package " + pkg.packageName
5185                        + " signature changed; retaining data.";
5186                reportSettingsProblem(Log.WARN, msg);
5187            }
5188
5189            // Verify that this new package doesn't have any content providers
5190            // that conflict with existing packages.  Only do this if the
5191            // package isn't already installed, since we don't want to break
5192            // things that are installed.
5193            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5194                final int N = pkg.providers.size();
5195                int i;
5196                for (i=0; i<N; i++) {
5197                    PackageParser.Provider p = pkg.providers.get(i);
5198                    if (p.info.authority != null) {
5199                        String names[] = p.info.authority.split(";");
5200                        for (int j = 0; j < names.length; j++) {
5201                            if (mProvidersByAuthority.containsKey(names[j])) {
5202                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5203                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5204                                        " (in package " + pkg.applicationInfo.packageName +
5205                                        ") is already used by "
5206                                        + ((other != null && other.getComponentName() != null)
5207                                                ? other.getComponentName().getPackageName() : "?"));
5208                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5209                                return null;
5210                            }
5211                        }
5212                    }
5213                }
5214            }
5215
5216            if (pkg.mAdoptPermissions != null) {
5217                // This package wants to adopt ownership of permissions from
5218                // another package.
5219                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5220                    final String origName = pkg.mAdoptPermissions.get(i);
5221                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5222                    if (orig != null) {
5223                        if (verifyPackageUpdateLPr(orig, pkg)) {
5224                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5225                                    + pkg.packageName);
5226                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5227                        }
5228                    }
5229                }
5230            }
5231        }
5232
5233        final String pkgName = pkg.packageName;
5234
5235        final long scanFileTime = scanFile.lastModified();
5236        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5237        pkg.applicationInfo.processName = fixProcessName(
5238                pkg.applicationInfo.packageName,
5239                pkg.applicationInfo.processName,
5240                pkg.applicationInfo.uid);
5241
5242        File dataPath;
5243        if (mPlatformPackage == pkg) {
5244            // The system package is special.
5245            dataPath = new File (Environment.getDataDirectory(), "system");
5246            pkg.applicationInfo.dataDir = dataPath.getPath();
5247        } else {
5248            // This is a normal package, need to make its data directory.
5249            dataPath = getDataPathForPackage(pkg.packageName, 0);
5250
5251            boolean uidError = false;
5252
5253            if (dataPath.exists()) {
5254                int currentUid = 0;
5255                try {
5256                    StructStat stat = Os.stat(dataPath.getPath());
5257                    currentUid = stat.st_uid;
5258                } catch (ErrnoException e) {
5259                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5260                }
5261
5262                // If we have mismatched owners for the data path, we have a problem.
5263                if (currentUid != pkg.applicationInfo.uid) {
5264                    boolean recovered = false;
5265                    if (currentUid == 0) {
5266                        // The directory somehow became owned by root.  Wow.
5267                        // This is probably because the system was stopped while
5268                        // installd was in the middle of messing with its libs
5269                        // directory.  Ask installd to fix that.
5270                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5271                                pkg.applicationInfo.uid);
5272                        if (ret >= 0) {
5273                            recovered = true;
5274                            String msg = "Package " + pkg.packageName
5275                                    + " unexpectedly changed to uid 0; recovered to " +
5276                                    + pkg.applicationInfo.uid;
5277                            reportSettingsProblem(Log.WARN, msg);
5278                        }
5279                    }
5280                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5281                            || (scanMode&SCAN_BOOTING) != 0)) {
5282                        // If this is a system app, we can at least delete its
5283                        // current data so the application will still work.
5284                        int ret = removeDataDirsLI(pkgName);
5285                        if (ret >= 0) {
5286                            // TODO: Kill the processes first
5287                            // Old data gone!
5288                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5289                                    ? "System package " : "Third party package ";
5290                            String msg = prefix + pkg.packageName
5291                                    + " has changed from uid: "
5292                                    + currentUid + " to "
5293                                    + pkg.applicationInfo.uid + "; old data erased";
5294                            reportSettingsProblem(Log.WARN, msg);
5295                            recovered = true;
5296
5297                            // And now re-install the app.
5298                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5299                                                   pkg.applicationInfo.seinfo);
5300                            if (ret == -1) {
5301                                // Ack should not happen!
5302                                msg = prefix + pkg.packageName
5303                                        + " could not have data directory re-created after delete.";
5304                                reportSettingsProblem(Log.WARN, msg);
5305                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5306                                return null;
5307                            }
5308                        }
5309                        if (!recovered) {
5310                            mHasSystemUidErrors = true;
5311                        }
5312                    } else if (!recovered) {
5313                        // If we allow this install to proceed, we will be broken.
5314                        // Abort, abort!
5315                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5316                        return null;
5317                    }
5318                    if (!recovered) {
5319                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5320                            + pkg.applicationInfo.uid + "/fs_"
5321                            + currentUid;
5322                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5323                        String msg = "Package " + pkg.packageName
5324                                + " has mismatched uid: "
5325                                + currentUid + " on disk, "
5326                                + pkg.applicationInfo.uid + " in settings";
5327                        // writer
5328                        synchronized (mPackages) {
5329                            mSettings.mReadMessages.append(msg);
5330                            mSettings.mReadMessages.append('\n');
5331                            uidError = true;
5332                            if (!pkgSetting.uidError) {
5333                                reportSettingsProblem(Log.ERROR, msg);
5334                            }
5335                        }
5336                    }
5337                }
5338                pkg.applicationInfo.dataDir = dataPath.getPath();
5339                if (mShouldRestoreconData) {
5340                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5341                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5342                                pkg.applicationInfo.uid);
5343                }
5344            } else {
5345                if (DEBUG_PACKAGE_SCANNING) {
5346                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5347                        Log.v(TAG, "Want this data dir: " + dataPath);
5348                }
5349                //invoke installer to do the actual installation
5350                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5351                                           pkg.applicationInfo.seinfo);
5352                if (ret < 0) {
5353                    // Error from installer
5354                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5355                    return null;
5356                }
5357
5358                if (dataPath.exists()) {
5359                    pkg.applicationInfo.dataDir = dataPath.getPath();
5360                } else {
5361                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5362                    pkg.applicationInfo.dataDir = null;
5363                }
5364            }
5365
5366            /*
5367             * Set the data dir to the default "/data/data/<package name>/lib"
5368             * if we got here without anyone telling us different (e.g., apps
5369             * stored on SD card have their native libraries stored in the ASEC
5370             * container with the APK).
5371             *
5372             * This happens during an upgrade from a package settings file that
5373             * doesn't have a native library path attribute at all.
5374             */
5375            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5376                if (pkgSetting.nativeLibraryPathString == null) {
5377                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5378                } else {
5379                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5380                }
5381            }
5382            pkgSetting.uidError = uidError;
5383        }
5384
5385        String path = scanFile.getPath();
5386        /* Note: We don't want to unpack the native binaries for
5387         *        system applications, unless they have been updated
5388         *        (the binaries are already under /system/lib).
5389         *        Also, don't unpack libs for apps on the external card
5390         *        since they should have their libraries in the ASEC
5391         *        container already.
5392         *
5393         *        In other words, we're going to unpack the binaries
5394         *        only for non-system apps and system app upgrades.
5395         */
5396        if (pkg.applicationInfo.nativeLibraryDir != null) {
5397            try {
5398                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5399                final String dataPathString = dataPath.getCanonicalPath();
5400
5401                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5402                    /*
5403                     * Upgrading from a previous version of the OS sometimes
5404                     * leaves native libraries in the /data/data/<app>/lib
5405                     * directory for system apps even when they shouldn't be.
5406                     * Recent changes in the JNI library search path
5407                     * necessitates we remove those to match previous behavior.
5408                     */
5409                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5410                        Log.i(TAG, "removed obsolete native libraries for system package "
5411                                + path);
5412                    }
5413
5414                    setInternalAppAbi(pkg, pkgSetting);
5415                } else {
5416                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5417                        /*
5418                         * Update native library dir if it starts with
5419                         * /data/data
5420                         */
5421                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5422                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5423                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5424                        }
5425
5426                        try {
5427                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5428                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5429                                Slog.e(TAG, "Unable to copy native libraries");
5430                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5431                                return null;
5432                            }
5433
5434                            // We've successfully copied native libraries across, so we make a
5435                            // note of what ABI we're using
5436                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5437                                pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[copyRet];
5438                            } else {
5439                                pkg.applicationInfo.cpuAbi = null;
5440                            }
5441                        } catch (IOException e) {
5442                            Slog.e(TAG, "Unable to copy native libraries", e);
5443                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5444                            return null;
5445                        }
5446                    } else {
5447                        // We don't have to copy the shared libraries if we're in the ASEC container
5448                        // but we still need to scan the file to figure out what ABI the app needs.
5449                        //
5450                        // TODO: This duplicates work done in the default container service. It's possible
5451                        // to clean this up but we'll need to change the interface between this service
5452                        // and IMediaContainerService (but doing so will spread this logic out, rather
5453                        // than centralizing it).
5454                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5455                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5456                        if (abi >= 0) {
5457                            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[abi];
5458                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5459                            // Note that (non upgraded) system apps will not have any native
5460                            // libraries bundled in their APK, but we're guaranteed not to be
5461                            // such an app at this point.
5462                            pkg.applicationInfo.cpuAbi = null;
5463                        } else {
5464                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5465                            return null;
5466                        }
5467                        handle.close();
5468                    }
5469
5470                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5471                    final int[] userIds = sUserManager.getUserIds();
5472                    synchronized (mInstallLock) {
5473                        for (int userId : userIds) {
5474                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5475                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5476                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5477                                        + ")");
5478                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5479                                return null;
5480                            }
5481                        }
5482                    }
5483                }
5484            } catch (IOException ioe) {
5485                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5486            }
5487        }
5488        pkg.mScanPath = path;
5489
5490        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5491            // We don't do this here during boot because we can do it all
5492            // at once after scanning all existing packages.
5493            //
5494            // We also do this *before* we perform dexopt on this package, so that
5495            // we can avoid redundant dexopts, and also to make sure we've got the
5496            // code and package path correct.
5497            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5498                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5499                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5500                return null;
5501            }
5502        }
5503
5504        if ((scanMode&SCAN_NO_DEX) == 0) {
5505            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5506                    == DEX_OPT_FAILED) {
5507                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5508                    removeDataDirsLI(pkg.packageName);
5509                }
5510
5511                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5512                return null;
5513            }
5514        }
5515
5516        if (mFactoryTest && pkg.requestedPermissions.contains(
5517                android.Manifest.permission.FACTORY_TEST)) {
5518            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5519        }
5520
5521        ArrayList<PackageParser.Package> clientLibPkgs = null;
5522
5523        // writer
5524        synchronized (mPackages) {
5525            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5526                // Only system apps can add new shared libraries.
5527                if (pkg.libraryNames != null) {
5528                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5529                        String name = pkg.libraryNames.get(i);
5530                        boolean allowed = false;
5531                        if (isUpdatedSystemApp(pkg)) {
5532                            // New library entries can only be added through the
5533                            // system image.  This is important to get rid of a lot
5534                            // of nasty edge cases: for example if we allowed a non-
5535                            // system update of the app to add a library, then uninstalling
5536                            // the update would make the library go away, and assumptions
5537                            // we made such as through app install filtering would now
5538                            // have allowed apps on the device which aren't compatible
5539                            // with it.  Better to just have the restriction here, be
5540                            // conservative, and create many fewer cases that can negatively
5541                            // impact the user experience.
5542                            final PackageSetting sysPs = mSettings
5543                                    .getDisabledSystemPkgLPr(pkg.packageName);
5544                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5545                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5546                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5547                                        allowed = true;
5548                                        allowed = true;
5549                                        break;
5550                                    }
5551                                }
5552                            }
5553                        } else {
5554                            allowed = true;
5555                        }
5556                        if (allowed) {
5557                            if (!mSharedLibraries.containsKey(name)) {
5558                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5559                            } else if (!name.equals(pkg.packageName)) {
5560                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5561                                        + name + " already exists; skipping");
5562                            }
5563                        } else {
5564                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5565                                    + name + " that is not declared on system image; skipping");
5566                        }
5567                    }
5568                    if ((scanMode&SCAN_BOOTING) == 0) {
5569                        // If we are not booting, we need to update any applications
5570                        // that are clients of our shared library.  If we are booting,
5571                        // this will all be done once the scan is complete.
5572                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5573                    }
5574                }
5575            }
5576        }
5577
5578        // We also need to dexopt any apps that are dependent on this library.  Note that
5579        // if these fail, we should abort the install since installing the library will
5580        // result in some apps being broken.
5581        if (clientLibPkgs != null) {
5582            if ((scanMode&SCAN_NO_DEX) == 0) {
5583                for (int i=0; i<clientLibPkgs.size(); i++) {
5584                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5585                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5586                            == DEX_OPT_FAILED) {
5587                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5588                            removeDataDirsLI(pkg.packageName);
5589                        }
5590
5591                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5592                        return null;
5593                    }
5594                }
5595            }
5596        }
5597
5598        // Request the ActivityManager to kill the process(only for existing packages)
5599        // so that we do not end up in a confused state while the user is still using the older
5600        // version of the application while the new one gets installed.
5601        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5602            // If the package lives in an asec, tell everyone that the container is going
5603            // away so they can clean up any references to its resources (which would prevent
5604            // vold from being able to unmount the asec)
5605            if (isForwardLocked(pkg) || isExternal(pkg)) {
5606                if (DEBUG_INSTALL) {
5607                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5608                }
5609                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5610                final ArrayList<String> pkgList = new ArrayList<String>(1);
5611                pkgList.add(pkg.applicationInfo.packageName);
5612                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5613            }
5614
5615            // Post the request that it be killed now that the going-away broadcast is en route
5616            killApplication(pkg.applicationInfo.packageName,
5617                        pkg.applicationInfo.uid, "update pkg");
5618        }
5619
5620        // Also need to kill any apps that are dependent on the library.
5621        if (clientLibPkgs != null) {
5622            for (int i=0; i<clientLibPkgs.size(); i++) {
5623                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5624                killApplication(clientPkg.applicationInfo.packageName,
5625                        clientPkg.applicationInfo.uid, "update lib");
5626            }
5627        }
5628
5629        // writer
5630        synchronized (mPackages) {
5631            // We don't expect installation to fail beyond this point,
5632            if ((scanMode&SCAN_MONITOR) != 0) {
5633                mAppDirs.put(pkg.mPath, pkg);
5634            }
5635            // Add the new setting to mSettings
5636            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5637            // Add the new setting to mPackages
5638            mPackages.put(pkg.applicationInfo.packageName, pkg);
5639            // Make sure we don't accidentally delete its data.
5640            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5641            while (iter.hasNext()) {
5642                PackageCleanItem item = iter.next();
5643                if (pkgName.equals(item.packageName)) {
5644                    iter.remove();
5645                }
5646            }
5647
5648            // Take care of first install / last update times.
5649            if (currentTime != 0) {
5650                if (pkgSetting.firstInstallTime == 0) {
5651                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5652                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5653                    pkgSetting.lastUpdateTime = currentTime;
5654                }
5655            } else if (pkgSetting.firstInstallTime == 0) {
5656                // We need *something*.  Take time time stamp of the file.
5657                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5658            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5659                if (scanFileTime != pkgSetting.timeStamp) {
5660                    // A package on the system image has changed; consider this
5661                    // to be an update.
5662                    pkgSetting.lastUpdateTime = scanFileTime;
5663                }
5664            }
5665
5666            // Add the package's KeySets to the global KeySetManager
5667            KeySetManager ksm = mSettings.mKeySetManager;
5668            try {
5669                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5670                if (pkg.mKeySetMapping != null) {
5671                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5672                        if (entry.getValue() != null) {
5673                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5674                                entry.getValue(), entry.getKey());
5675                        }
5676                    }
5677                }
5678            } catch (NullPointerException e) {
5679                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5680            } catch (IllegalArgumentException e) {
5681                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5682            }
5683
5684            int N = pkg.providers.size();
5685            StringBuilder r = null;
5686            int i;
5687            for (i=0; i<N; i++) {
5688                PackageParser.Provider p = pkg.providers.get(i);
5689                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5690                        p.info.processName, pkg.applicationInfo.uid);
5691                mProviders.addProvider(p);
5692                p.syncable = p.info.isSyncable;
5693                if (p.info.authority != null) {
5694                    String names[] = p.info.authority.split(";");
5695                    p.info.authority = null;
5696                    for (int j = 0; j < names.length; j++) {
5697                        if (j == 1 && p.syncable) {
5698                            // We only want the first authority for a provider to possibly be
5699                            // syncable, so if we already added this provider using a different
5700                            // authority clear the syncable flag. We copy the provider before
5701                            // changing it because the mProviders object contains a reference
5702                            // to a provider that we don't want to change.
5703                            // Only do this for the second authority since the resulting provider
5704                            // object can be the same for all future authorities for this provider.
5705                            p = new PackageParser.Provider(p);
5706                            p.syncable = false;
5707                        }
5708                        if (!mProvidersByAuthority.containsKey(names[j])) {
5709                            mProvidersByAuthority.put(names[j], p);
5710                            if (p.info.authority == null) {
5711                                p.info.authority = names[j];
5712                            } else {
5713                                p.info.authority = p.info.authority + ";" + names[j];
5714                            }
5715                            if (DEBUG_PACKAGE_SCANNING) {
5716                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5717                                    Log.d(TAG, "Registered content provider: " + names[j]
5718                                            + ", className = " + p.info.name + ", isSyncable = "
5719                                            + p.info.isSyncable);
5720                            }
5721                        } else {
5722                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5723                            Slog.w(TAG, "Skipping provider name " + names[j] +
5724                                    " (in package " + pkg.applicationInfo.packageName +
5725                                    "): name already used by "
5726                                    + ((other != null && other.getComponentName() != null)
5727                                            ? other.getComponentName().getPackageName() : "?"));
5728                        }
5729                    }
5730                }
5731                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5732                    if (r == null) {
5733                        r = new StringBuilder(256);
5734                    } else {
5735                        r.append(' ');
5736                    }
5737                    r.append(p.info.name);
5738                }
5739            }
5740            if (r != null) {
5741                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5742            }
5743
5744            N = pkg.services.size();
5745            r = null;
5746            for (i=0; i<N; i++) {
5747                PackageParser.Service s = pkg.services.get(i);
5748                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5749                        s.info.processName, pkg.applicationInfo.uid);
5750                mServices.addService(s);
5751                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5752                    if (r == null) {
5753                        r = new StringBuilder(256);
5754                    } else {
5755                        r.append(' ');
5756                    }
5757                    r.append(s.info.name);
5758                }
5759            }
5760            if (r != null) {
5761                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5762            }
5763
5764            N = pkg.receivers.size();
5765            r = null;
5766            for (i=0; i<N; i++) {
5767                PackageParser.Activity a = pkg.receivers.get(i);
5768                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5769                        a.info.processName, pkg.applicationInfo.uid);
5770                mReceivers.addActivity(a, "receiver");
5771                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5772                    if (r == null) {
5773                        r = new StringBuilder(256);
5774                    } else {
5775                        r.append(' ');
5776                    }
5777                    r.append(a.info.name);
5778                }
5779            }
5780            if (r != null) {
5781                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5782            }
5783
5784            N = pkg.activities.size();
5785            r = null;
5786            for (i=0; i<N; i++) {
5787                PackageParser.Activity a = pkg.activities.get(i);
5788                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5789                        a.info.processName, pkg.applicationInfo.uid);
5790                mActivities.addActivity(a, "activity");
5791                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5792                    if (r == null) {
5793                        r = new StringBuilder(256);
5794                    } else {
5795                        r.append(' ');
5796                    }
5797                    r.append(a.info.name);
5798                }
5799            }
5800            if (r != null) {
5801                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5802            }
5803
5804            N = pkg.permissionGroups.size();
5805            r = null;
5806            for (i=0; i<N; i++) {
5807                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5808                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5809                if (cur == null) {
5810                    mPermissionGroups.put(pg.info.name, pg);
5811                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5812                        if (r == null) {
5813                            r = new StringBuilder(256);
5814                        } else {
5815                            r.append(' ');
5816                        }
5817                        r.append(pg.info.name);
5818                    }
5819                } else {
5820                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5821                            + pg.info.packageName + " ignored: original from "
5822                            + cur.info.packageName);
5823                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5824                        if (r == null) {
5825                            r = new StringBuilder(256);
5826                        } else {
5827                            r.append(' ');
5828                        }
5829                        r.append("DUP:");
5830                        r.append(pg.info.name);
5831                    }
5832                }
5833            }
5834            if (r != null) {
5835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5836            }
5837
5838            N = pkg.permissions.size();
5839            r = null;
5840            for (i=0; i<N; i++) {
5841                PackageParser.Permission p = pkg.permissions.get(i);
5842                HashMap<String, BasePermission> permissionMap =
5843                        p.tree ? mSettings.mPermissionTrees
5844                        : mSettings.mPermissions;
5845                p.group = mPermissionGroups.get(p.info.group);
5846                if (p.info.group == null || p.group != null) {
5847                    BasePermission bp = permissionMap.get(p.info.name);
5848                    if (bp == null) {
5849                        bp = new BasePermission(p.info.name, p.info.packageName,
5850                                BasePermission.TYPE_NORMAL);
5851                        permissionMap.put(p.info.name, bp);
5852                    }
5853                    if (bp.perm == null) {
5854                        if (bp.sourcePackage != null
5855                                && !bp.sourcePackage.equals(p.info.packageName)) {
5856                            // If this is a permission that was formerly defined by a non-system
5857                            // app, but is now defined by a system app (following an upgrade),
5858                            // discard the previous declaration and consider the system's to be
5859                            // canonical.
5860                            if (isSystemApp(p.owner)) {
5861                                String msg = "New decl " + p.owner + " of permission  "
5862                                        + p.info.name + " is system";
5863                                reportSettingsProblem(Log.WARN, msg);
5864                                bp.sourcePackage = null;
5865                            }
5866                        }
5867                        if (bp.sourcePackage == null
5868                                || bp.sourcePackage.equals(p.info.packageName)) {
5869                            BasePermission tree = findPermissionTreeLP(p.info.name);
5870                            if (tree == null
5871                                    || tree.sourcePackage.equals(p.info.packageName)) {
5872                                bp.packageSetting = pkgSetting;
5873                                bp.perm = p;
5874                                bp.uid = pkg.applicationInfo.uid;
5875                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5876                                    if (r == null) {
5877                                        r = new StringBuilder(256);
5878                                    } else {
5879                                        r.append(' ');
5880                                    }
5881                                    r.append(p.info.name);
5882                                }
5883                            } else {
5884                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5885                                        + p.info.packageName + " ignored: base tree "
5886                                        + tree.name + " is from package "
5887                                        + tree.sourcePackage);
5888                            }
5889                        } else {
5890                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5891                                    + p.info.packageName + " ignored: original from "
5892                                    + bp.sourcePackage);
5893                        }
5894                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5895                        if (r == null) {
5896                            r = new StringBuilder(256);
5897                        } else {
5898                            r.append(' ');
5899                        }
5900                        r.append("DUP:");
5901                        r.append(p.info.name);
5902                    }
5903                    if (bp.perm == p) {
5904                        bp.protectionLevel = p.info.protectionLevel;
5905                    }
5906                } else {
5907                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5908                            + p.info.packageName + " ignored: no group "
5909                            + p.group);
5910                }
5911            }
5912            if (r != null) {
5913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5914            }
5915
5916            N = pkg.instrumentation.size();
5917            r = null;
5918            for (i=0; i<N; i++) {
5919                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5920                a.info.packageName = pkg.applicationInfo.packageName;
5921                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5922                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5923                a.info.dataDir = pkg.applicationInfo.dataDir;
5924                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5925                mInstrumentation.put(a.getComponentName(), a);
5926                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5927                    if (r == null) {
5928                        r = new StringBuilder(256);
5929                    } else {
5930                        r.append(' ');
5931                    }
5932                    r.append(a.info.name);
5933                }
5934            }
5935            if (r != null) {
5936                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5937            }
5938
5939            if (pkg.protectedBroadcasts != null) {
5940                N = pkg.protectedBroadcasts.size();
5941                for (i=0; i<N; i++) {
5942                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5943                }
5944            }
5945
5946            pkgSetting.setTimeStamp(scanFileTime);
5947
5948            // Create idmap files for pairs of (packages, overlay packages).
5949            // Note: "android", ie framework-res.apk, is handled by native layers.
5950            if (pkg.mOverlayTarget != null) {
5951                // This is an overlay package.
5952                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5953                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5954                        mOverlays.put(pkg.mOverlayTarget,
5955                                new HashMap<String, PackageParser.Package>());
5956                    }
5957                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5958                    map.put(pkg.packageName, pkg);
5959                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5960                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5961                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5962                        return null;
5963                    }
5964                }
5965            } else if (mOverlays.containsKey(pkg.packageName) &&
5966                    !pkg.packageName.equals("android")) {
5967                // This is a regular package, with one or more known overlay packages.
5968                createIdmapsForPackageLI(pkg);
5969            }
5970        }
5971
5972        return pkg;
5973    }
5974
5975    /**
5976     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5977     * i.e, so that all packages can be run inside a single process if required.
5978     *
5979     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5980     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5981     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5982     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5983     * updating a package that belongs to a shared user.
5984     */
5985    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5986            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5987        String requiredInstructionSet = null;
5988        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5989            requiredInstructionSet = VMRuntime.getInstructionSet(
5990                     scannedPackage.applicationInfo.cpuAbi);
5991        }
5992
5993        PackageSetting requirer = null;
5994        for (PackageSetting ps : packagesForUser) {
5995            // If packagesForUser contains scannedPackage, we skip it. This will happen
5996            // when scannedPackage is an update of an existing package. Without this check,
5997            // we will never be able to change the ABI of any package belonging to a shared
5998            // user, even if it's compatible with other packages.
5999            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6000                if (ps.cpuAbiString == null) {
6001                    continue;
6002                }
6003
6004                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6005                if (requiredInstructionSet != null) {
6006                    if (!instructionSet.equals(requiredInstructionSet)) {
6007                        // We have a mismatch between instruction sets (say arm vs arm64).
6008                        // bail out.
6009                        String errorMessage = "Instruction set mismatch, "
6010                                + ((requirer == null) ? "[caller]" : requirer)
6011                                + " requires " + requiredInstructionSet + " whereas " + ps
6012                                + " requires " + instructionSet;
6013                        Slog.e(TAG, errorMessage);
6014
6015                        reportSettingsProblem(Log.WARN, errorMessage);
6016                        // Give up, don't bother making any other changes to the package settings.
6017                        return false;
6018                    }
6019                } else {
6020                    requiredInstructionSet = instructionSet;
6021                    requirer = ps;
6022                }
6023            }
6024        }
6025
6026        if (requiredInstructionSet != null) {
6027            String adjustedAbi;
6028            if (requirer != null) {
6029                // requirer != null implies that either scannedPackage was null or that scannedPackage
6030                // did not require an ABI, in which case we have to adjust scannedPackage to match
6031                // the ABI of the set (which is the same as requirer's ABI)
6032                adjustedAbi = requirer.cpuAbiString;
6033                if (scannedPackage != null) {
6034                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6035                }
6036            } else {
6037                // requirer == null implies that we're updating all ABIs in the set to
6038                // match scannedPackage.
6039                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6040            }
6041
6042            for (PackageSetting ps : packagesForUser) {
6043                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6044                    if (ps.cpuAbiString != null) {
6045                        continue;
6046                    }
6047
6048                    ps.cpuAbiString = adjustedAbi;
6049                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6050                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6051                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6052
6053                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6054                            ps.cpuAbiString = null;
6055                            ps.pkg.applicationInfo.cpuAbi = null;
6056                            return false;
6057                        } else {
6058                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6059                        }
6060                    }
6061                }
6062            }
6063        }
6064
6065        return true;
6066    }
6067
6068    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6069        synchronized (mPackages) {
6070            mResolverReplaced = true;
6071            // Set up information for custom user intent resolution activity.
6072            mResolveActivity.applicationInfo = pkg.applicationInfo;
6073            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6074            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6075            mResolveActivity.processName = null;
6076            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6077            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6078                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6079            mResolveActivity.theme = 0;
6080            mResolveActivity.exported = true;
6081            mResolveActivity.enabled = true;
6082            mResolveInfo.activityInfo = mResolveActivity;
6083            mResolveInfo.priority = 0;
6084            mResolveInfo.preferredOrder = 0;
6085            mResolveInfo.match = 0;
6086            mResolveComponentName = mCustomResolverComponentName;
6087            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6088                    mResolveComponentName);
6089        }
6090    }
6091
6092    private String calculateApkRoot(final String codePathString) {
6093        final File codePath = new File(codePathString);
6094        final File codeRoot;
6095        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6096            codeRoot = Environment.getRootDirectory();
6097        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6098            codeRoot = Environment.getOemDirectory();
6099        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6100            codeRoot = Environment.getVendorDirectory();
6101        } else {
6102            // Unrecognized code path; take its top real segment as the apk root:
6103            // e.g. /something/app/blah.apk => /something
6104            try {
6105                File f = codePath.getCanonicalFile();
6106                File parent = f.getParentFile();    // non-null because codePath is a file
6107                File tmp;
6108                while ((tmp = parent.getParentFile()) != null) {
6109                    f = parent;
6110                    parent = tmp;
6111                }
6112                codeRoot = f;
6113                Slog.w(TAG, "Unrecognized code path "
6114                        + codePath + " - using " + codeRoot);
6115            } catch (IOException e) {
6116                // Can't canonicalize the lib path -- shenanigans?
6117                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6118                return Environment.getRootDirectory().getPath();
6119            }
6120        }
6121        return codeRoot.getPath();
6122    }
6123
6124    // This is the initial scan-time determination of how to handle a given
6125    // package for purposes of native library location.
6126    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6127            PackageSetting pkgSetting) {
6128        // "bundled" here means system-installed with no overriding update
6129        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6130        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6131        final File libDir;
6132        if (bundledApk) {
6133            // If "/system/lib64/apkname" exists, assume that is the per-package
6134            // native library directory to use; otherwise use "/system/lib/apkname".
6135            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6136            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6137            File packLib64 = new File(lib64, apkName);
6138            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6139        } else {
6140            libDir = mAppLibInstallDir;
6141        }
6142        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6143        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6144        // pkgSetting might be null during rescan following uninstall of updates
6145        // to a bundled app, so accommodate that possibility.  The settings in
6146        // that case will be established later from the parsed package.
6147        if (pkgSetting != null) {
6148            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6149        }
6150    }
6151
6152    // Deduces the required ABI of an upgraded system app.
6153    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6154        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6155        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6156
6157        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6158        // or similar.
6159        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6160        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6161
6162        // Assume that the bundled native libraries always correspond to the
6163        // most preferred 32 or 64 bit ABI.
6164        if (lib64.exists()) {
6165            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6166            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6167        } else if (lib.exists()) {
6168            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6169            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6170        } else {
6171            // This is the case where the app has no native code.
6172            pkg.applicationInfo.cpuAbi = null;
6173            pkgSetting.cpuAbiString = null;
6174        }
6175    }
6176
6177    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
6178            throws IOException {
6179        if (!nativeLibraryDir.isDirectory()) {
6180            nativeLibraryDir.delete();
6181
6182            if (!nativeLibraryDir.mkdir()) {
6183                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6184            }
6185
6186            try {
6187                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6188            } catch (ErrnoException e) {
6189                throw new IOException("Cannot chmod native library directory "
6190                        + nativeLibraryDir.getPath(), e);
6191            }
6192        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6193            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6194        }
6195
6196        /*
6197         * If this is an internal application or our nativeLibraryPath points to
6198         * the app-lib directory, unpack the libraries if necessary.
6199         */
6200        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
6201        try {
6202            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
6203            if (abi >= 0) {
6204                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6205                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6206                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6207                    return copyRet;
6208                }
6209            }
6210
6211            return abi;
6212        } finally {
6213            handle.close();
6214        }
6215    }
6216
6217    private void killApplication(String pkgName, int appId, String reason) {
6218        // Request the ActivityManager to kill the process(only for existing packages)
6219        // so that we do not end up in a confused state while the user is still using the older
6220        // version of the application while the new one gets installed.
6221        IActivityManager am = ActivityManagerNative.getDefault();
6222        if (am != null) {
6223            try {
6224                am.killApplicationWithAppId(pkgName, appId, reason);
6225            } catch (RemoteException e) {
6226            }
6227        }
6228    }
6229
6230    void removePackageLI(PackageSetting ps, boolean chatty) {
6231        if (DEBUG_INSTALL) {
6232            if (chatty)
6233                Log.d(TAG, "Removing package " + ps.name);
6234        }
6235
6236        // writer
6237        synchronized (mPackages) {
6238            mPackages.remove(ps.name);
6239            if (ps.codePathString != null) {
6240                mAppDirs.remove(ps.codePathString);
6241            }
6242
6243            final PackageParser.Package pkg = ps.pkg;
6244            if (pkg != null) {
6245                cleanPackageDataStructuresLILPw(pkg, chatty);
6246            }
6247        }
6248    }
6249
6250    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6251        if (DEBUG_INSTALL) {
6252            if (chatty)
6253                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6254        }
6255
6256        // writer
6257        synchronized (mPackages) {
6258            mPackages.remove(pkg.applicationInfo.packageName);
6259            if (pkg.mPath != null) {
6260                mAppDirs.remove(pkg.mPath);
6261            }
6262            cleanPackageDataStructuresLILPw(pkg, chatty);
6263        }
6264    }
6265
6266    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6267        int N = pkg.providers.size();
6268        StringBuilder r = null;
6269        int i;
6270        for (i=0; i<N; i++) {
6271            PackageParser.Provider p = pkg.providers.get(i);
6272            mProviders.removeProvider(p);
6273            if (p.info.authority == null) {
6274
6275                /* There was another ContentProvider with this authority when
6276                 * this app was installed so this authority is null,
6277                 * Ignore it as we don't have to unregister the provider.
6278                 */
6279                continue;
6280            }
6281            String names[] = p.info.authority.split(";");
6282            for (int j = 0; j < names.length; j++) {
6283                if (mProvidersByAuthority.get(names[j]) == p) {
6284                    mProvidersByAuthority.remove(names[j]);
6285                    if (DEBUG_REMOVE) {
6286                        if (chatty)
6287                            Log.d(TAG, "Unregistered content provider: " + names[j]
6288                                    + ", className = " + p.info.name + ", isSyncable = "
6289                                    + p.info.isSyncable);
6290                    }
6291                }
6292            }
6293            if (DEBUG_REMOVE && chatty) {
6294                if (r == null) {
6295                    r = new StringBuilder(256);
6296                } else {
6297                    r.append(' ');
6298                }
6299                r.append(p.info.name);
6300            }
6301        }
6302        if (r != null) {
6303            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6304        }
6305
6306        N = pkg.services.size();
6307        r = null;
6308        for (i=0; i<N; i++) {
6309            PackageParser.Service s = pkg.services.get(i);
6310            mServices.removeService(s);
6311            if (chatty) {
6312                if (r == null) {
6313                    r = new StringBuilder(256);
6314                } else {
6315                    r.append(' ');
6316                }
6317                r.append(s.info.name);
6318            }
6319        }
6320        if (r != null) {
6321            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6322        }
6323
6324        N = pkg.receivers.size();
6325        r = null;
6326        for (i=0; i<N; i++) {
6327            PackageParser.Activity a = pkg.receivers.get(i);
6328            mReceivers.removeActivity(a, "receiver");
6329            if (DEBUG_REMOVE && chatty) {
6330                if (r == null) {
6331                    r = new StringBuilder(256);
6332                } else {
6333                    r.append(' ');
6334                }
6335                r.append(a.info.name);
6336            }
6337        }
6338        if (r != null) {
6339            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6340        }
6341
6342        N = pkg.activities.size();
6343        r = null;
6344        for (i=0; i<N; i++) {
6345            PackageParser.Activity a = pkg.activities.get(i);
6346            mActivities.removeActivity(a, "activity");
6347            if (DEBUG_REMOVE && chatty) {
6348                if (r == null) {
6349                    r = new StringBuilder(256);
6350                } else {
6351                    r.append(' ');
6352                }
6353                r.append(a.info.name);
6354            }
6355        }
6356        if (r != null) {
6357            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6358        }
6359
6360        N = pkg.permissions.size();
6361        r = null;
6362        for (i=0; i<N; i++) {
6363            PackageParser.Permission p = pkg.permissions.get(i);
6364            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6365            if (bp == null) {
6366                bp = mSettings.mPermissionTrees.get(p.info.name);
6367            }
6368            if (bp != null && bp.perm == p) {
6369                bp.perm = null;
6370                if (DEBUG_REMOVE && chatty) {
6371                    if (r == null) {
6372                        r = new StringBuilder(256);
6373                    } else {
6374                        r.append(' ');
6375                    }
6376                    r.append(p.info.name);
6377                }
6378            }
6379        }
6380        if (r != null) {
6381            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6382        }
6383
6384        N = pkg.instrumentation.size();
6385        r = null;
6386        for (i=0; i<N; i++) {
6387            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6388            mInstrumentation.remove(a.getComponentName());
6389            if (DEBUG_REMOVE && chatty) {
6390                if (r == null) {
6391                    r = new StringBuilder(256);
6392                } else {
6393                    r.append(' ');
6394                }
6395                r.append(a.info.name);
6396            }
6397        }
6398        if (r != null) {
6399            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6400        }
6401
6402        r = null;
6403        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6404            // Only system apps can hold shared libraries.
6405            if (pkg.libraryNames != null) {
6406                for (i=0; i<pkg.libraryNames.size(); i++) {
6407                    String name = pkg.libraryNames.get(i);
6408                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6409                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6410                        mSharedLibraries.remove(name);
6411                        if (DEBUG_REMOVE && chatty) {
6412                            if (r == null) {
6413                                r = new StringBuilder(256);
6414                            } else {
6415                                r.append(' ');
6416                            }
6417                            r.append(name);
6418                        }
6419                    }
6420                }
6421            }
6422        }
6423        if (r != null) {
6424            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6425        }
6426    }
6427
6428    private static final boolean isPackageFilename(String name) {
6429        return name != null && name.endsWith(".apk");
6430    }
6431
6432    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6433        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6434            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6435                return true;
6436            }
6437        }
6438        return false;
6439    }
6440
6441    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6442    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6443    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6444
6445    private void updatePermissionsLPw(String changingPkg,
6446            PackageParser.Package pkgInfo, int flags) {
6447        // Make sure there are no dangling permission trees.
6448        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6449        while (it.hasNext()) {
6450            final BasePermission bp = it.next();
6451            if (bp.packageSetting == null) {
6452                // We may not yet have parsed the package, so just see if
6453                // we still know about its settings.
6454                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6455            }
6456            if (bp.packageSetting == null) {
6457                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6458                        + " from package " + bp.sourcePackage);
6459                it.remove();
6460            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6461                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6462                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6463                            + " from package " + bp.sourcePackage);
6464                    flags |= UPDATE_PERMISSIONS_ALL;
6465                    it.remove();
6466                }
6467            }
6468        }
6469
6470        // Make sure all dynamic permissions have been assigned to a package,
6471        // and make sure there are no dangling permissions.
6472        it = mSettings.mPermissions.values().iterator();
6473        while (it.hasNext()) {
6474            final BasePermission bp = it.next();
6475            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6476                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6477                        + bp.name + " pkg=" + bp.sourcePackage
6478                        + " info=" + bp.pendingInfo);
6479                if (bp.packageSetting == null && bp.pendingInfo != null) {
6480                    final BasePermission tree = findPermissionTreeLP(bp.name);
6481                    if (tree != null && tree.perm != null) {
6482                        bp.packageSetting = tree.packageSetting;
6483                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6484                                new PermissionInfo(bp.pendingInfo));
6485                        bp.perm.info.packageName = tree.perm.info.packageName;
6486                        bp.perm.info.name = bp.name;
6487                        bp.uid = tree.uid;
6488                    }
6489                }
6490            }
6491            if (bp.packageSetting == null) {
6492                // We may not yet have parsed the package, so just see if
6493                // we still know about its settings.
6494                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6495            }
6496            if (bp.packageSetting == null) {
6497                Slog.w(TAG, "Removing dangling permission: " + bp.name
6498                        + " from package " + bp.sourcePackage);
6499                it.remove();
6500            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6501                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6502                    Slog.i(TAG, "Removing old permission: " + bp.name
6503                            + " from package " + bp.sourcePackage);
6504                    flags |= UPDATE_PERMISSIONS_ALL;
6505                    it.remove();
6506                }
6507            }
6508        }
6509
6510        // Now update the permissions for all packages, in particular
6511        // replace the granted permissions of the system packages.
6512        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6513            for (PackageParser.Package pkg : mPackages.values()) {
6514                if (pkg != pkgInfo) {
6515                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6516                }
6517            }
6518        }
6519
6520        if (pkgInfo != null) {
6521            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6522        }
6523    }
6524
6525    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6526        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6527        if (ps == null) {
6528            return;
6529        }
6530        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6531        HashSet<String> origPermissions = gp.grantedPermissions;
6532        boolean changedPermission = false;
6533
6534        if (replace) {
6535            ps.permissionsFixed = false;
6536            if (gp == ps) {
6537                origPermissions = new HashSet<String>(gp.grantedPermissions);
6538                gp.grantedPermissions.clear();
6539                gp.gids = mGlobalGids;
6540            }
6541        }
6542
6543        if (gp.gids == null) {
6544            gp.gids = mGlobalGids;
6545        }
6546
6547        final int N = pkg.requestedPermissions.size();
6548        for (int i=0; i<N; i++) {
6549            final String name = pkg.requestedPermissions.get(i);
6550            final boolean required = pkg.requestedPermissionsRequired.get(i);
6551            final BasePermission bp = mSettings.mPermissions.get(name);
6552            if (DEBUG_INSTALL) {
6553                if (gp != ps) {
6554                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6555                }
6556            }
6557
6558            if (bp == null || bp.packageSetting == null) {
6559                Slog.w(TAG, "Unknown permission " + name
6560                        + " in package " + pkg.packageName);
6561                continue;
6562            }
6563
6564            final String perm = bp.name;
6565            boolean allowed;
6566            boolean allowedSig = false;
6567            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6568            if (level == PermissionInfo.PROTECTION_NORMAL
6569                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6570                // We grant a normal or dangerous permission if any of the following
6571                // are true:
6572                // 1) The permission is required
6573                // 2) The permission is optional, but was granted in the past
6574                // 3) The permission is optional, but was requested by an
6575                //    app in /system (not /data)
6576                //
6577                // Otherwise, reject the permission.
6578                allowed = (required || origPermissions.contains(perm)
6579                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6580            } else if (bp.packageSetting == null) {
6581                // This permission is invalid; skip it.
6582                allowed = false;
6583            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6584                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6585                if (allowed) {
6586                    allowedSig = true;
6587                }
6588            } else {
6589                allowed = false;
6590            }
6591            if (DEBUG_INSTALL) {
6592                if (gp != ps) {
6593                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6594                }
6595            }
6596            if (allowed) {
6597                if (!isSystemApp(ps) && ps.permissionsFixed) {
6598                    // If this is an existing, non-system package, then
6599                    // we can't add any new permissions to it.
6600                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6601                        // Except...  if this is a permission that was added
6602                        // to the platform (note: need to only do this when
6603                        // updating the platform).
6604                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6605                    }
6606                }
6607                if (allowed) {
6608                    if (!gp.grantedPermissions.contains(perm)) {
6609                        changedPermission = true;
6610                        gp.grantedPermissions.add(perm);
6611                        gp.gids = appendInts(gp.gids, bp.gids);
6612                    } else if (!ps.haveGids) {
6613                        gp.gids = appendInts(gp.gids, bp.gids);
6614                    }
6615                } else {
6616                    Slog.w(TAG, "Not granting permission " + perm
6617                            + " to package " + pkg.packageName
6618                            + " because it was previously installed without");
6619                }
6620            } else {
6621                if (gp.grantedPermissions.remove(perm)) {
6622                    changedPermission = true;
6623                    gp.gids = removeInts(gp.gids, bp.gids);
6624                    Slog.i(TAG, "Un-granting permission " + perm
6625                            + " from package " + pkg.packageName
6626                            + " (protectionLevel=" + bp.protectionLevel
6627                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6628                            + ")");
6629                } else {
6630                    Slog.w(TAG, "Not granting permission " + perm
6631                            + " to package " + pkg.packageName
6632                            + " (protectionLevel=" + bp.protectionLevel
6633                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6634                            + ")");
6635                }
6636            }
6637        }
6638
6639        if ((changedPermission || replace) && !ps.permissionsFixed &&
6640                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6641            // This is the first that we have heard about this package, so the
6642            // permissions we have now selected are fixed until explicitly
6643            // changed.
6644            ps.permissionsFixed = true;
6645        }
6646        ps.haveGids = true;
6647    }
6648
6649    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6650        boolean allowed = false;
6651        final int NP = PackageParser.NEW_PERMISSIONS.length;
6652        for (int ip=0; ip<NP; ip++) {
6653            final PackageParser.NewPermissionInfo npi
6654                    = PackageParser.NEW_PERMISSIONS[ip];
6655            if (npi.name.equals(perm)
6656                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6657                allowed = true;
6658                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6659                        + pkg.packageName);
6660                break;
6661            }
6662        }
6663        return allowed;
6664    }
6665
6666    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6667                                          BasePermission bp, HashSet<String> origPermissions) {
6668        boolean allowed;
6669        allowed = (compareSignatures(
6670                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6671                        == PackageManager.SIGNATURE_MATCH)
6672                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6673                        == PackageManager.SIGNATURE_MATCH);
6674        if (!allowed && (bp.protectionLevel
6675                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6676            if (isSystemApp(pkg)) {
6677                // For updated system applications, a system permission
6678                // is granted only if it had been defined by the original application.
6679                if (isUpdatedSystemApp(pkg)) {
6680                    final PackageSetting sysPs = mSettings
6681                            .getDisabledSystemPkgLPr(pkg.packageName);
6682                    final GrantedPermissions origGp = sysPs.sharedUser != null
6683                            ? sysPs.sharedUser : sysPs;
6684
6685                    if (origGp.grantedPermissions.contains(perm)) {
6686                        // If the original was granted this permission, we take
6687                        // that grant decision as read and propagate it to the
6688                        // update.
6689                        allowed = true;
6690                    } else {
6691                        // The system apk may have been updated with an older
6692                        // version of the one on the data partition, but which
6693                        // granted a new system permission that it didn't have
6694                        // before.  In this case we do want to allow the app to
6695                        // now get the new permission if the ancestral apk is
6696                        // privileged to get it.
6697                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6698                            for (int j=0;
6699                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6700                                if (perm.equals(
6701                                        sysPs.pkg.requestedPermissions.get(j))) {
6702                                    allowed = true;
6703                                    break;
6704                                }
6705                            }
6706                        }
6707                    }
6708                } else {
6709                    allowed = isPrivilegedApp(pkg);
6710                }
6711            }
6712        }
6713        if (!allowed && (bp.protectionLevel
6714                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6715            // For development permissions, a development permission
6716            // is granted only if it was already granted.
6717            allowed = origPermissions.contains(perm);
6718        }
6719        return allowed;
6720    }
6721
6722    final class ActivityIntentResolver
6723            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6724        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6725                boolean defaultOnly, int userId) {
6726            if (!sUserManager.exists(userId)) return null;
6727            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6728            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6729        }
6730
6731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6732                int userId) {
6733            if (!sUserManager.exists(userId)) return null;
6734            mFlags = flags;
6735            return super.queryIntent(intent, resolvedType,
6736                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6737        }
6738
6739        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6740                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6741            if (!sUserManager.exists(userId)) return null;
6742            if (packageActivities == null) {
6743                return null;
6744            }
6745            mFlags = flags;
6746            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6747            final int N = packageActivities.size();
6748            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6749                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6750
6751            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6752            for (int i = 0; i < N; ++i) {
6753                intentFilters = packageActivities.get(i).intents;
6754                if (intentFilters != null && intentFilters.size() > 0) {
6755                    PackageParser.ActivityIntentInfo[] array =
6756                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6757                    intentFilters.toArray(array);
6758                    listCut.add(array);
6759                }
6760            }
6761            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6762        }
6763
6764        public final void addActivity(PackageParser.Activity a, String type) {
6765            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6766            mActivities.put(a.getComponentName(), a);
6767            if (DEBUG_SHOW_INFO)
6768                Log.v(
6769                TAG, "  " + type + " " +
6770                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6771            if (DEBUG_SHOW_INFO)
6772                Log.v(TAG, "    Class=" + a.info.name);
6773            final int NI = a.intents.size();
6774            for (int j=0; j<NI; j++) {
6775                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6776                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6777                    intent.setPriority(0);
6778                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6779                            + a.className + " with priority > 0, forcing to 0");
6780                }
6781                if (DEBUG_SHOW_INFO) {
6782                    Log.v(TAG, "    IntentFilter:");
6783                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6784                }
6785                if (!intent.debugCheck()) {
6786                    Log.w(TAG, "==> For Activity " + a.info.name);
6787                }
6788                addFilter(intent);
6789            }
6790        }
6791
6792        public final void removeActivity(PackageParser.Activity a, String type) {
6793            mActivities.remove(a.getComponentName());
6794            if (DEBUG_SHOW_INFO) {
6795                Log.v(TAG, "  " + type + " "
6796                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6797                                : a.info.name) + ":");
6798                Log.v(TAG, "    Class=" + a.info.name);
6799            }
6800            final int NI = a.intents.size();
6801            for (int j=0; j<NI; j++) {
6802                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6803                if (DEBUG_SHOW_INFO) {
6804                    Log.v(TAG, "    IntentFilter:");
6805                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6806                }
6807                removeFilter(intent);
6808            }
6809        }
6810
6811        @Override
6812        protected boolean allowFilterResult(
6813                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6814            ActivityInfo filterAi = filter.activity.info;
6815            for (int i=dest.size()-1; i>=0; i--) {
6816                ActivityInfo destAi = dest.get(i).activityInfo;
6817                if (destAi.name == filterAi.name
6818                        && destAi.packageName == filterAi.packageName) {
6819                    return false;
6820                }
6821            }
6822            return true;
6823        }
6824
6825        @Override
6826        protected ActivityIntentInfo[] newArray(int size) {
6827            return new ActivityIntentInfo[size];
6828        }
6829
6830        @Override
6831        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6832            if (!sUserManager.exists(userId)) return true;
6833            PackageParser.Package p = filter.activity.owner;
6834            if (p != null) {
6835                PackageSetting ps = (PackageSetting)p.mExtras;
6836                if (ps != null) {
6837                    // System apps are never considered stopped for purposes of
6838                    // filtering, because there may be no way for the user to
6839                    // actually re-launch them.
6840                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6841                            && ps.getStopped(userId);
6842                }
6843            }
6844            return false;
6845        }
6846
6847        @Override
6848        protected boolean isPackageForFilter(String packageName,
6849                PackageParser.ActivityIntentInfo info) {
6850            return packageName.equals(info.activity.owner.packageName);
6851        }
6852
6853        @Override
6854        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6855                int match, int userId) {
6856            if (!sUserManager.exists(userId)) return null;
6857            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6858                return null;
6859            }
6860            final PackageParser.Activity activity = info.activity;
6861            if (mSafeMode && (activity.info.applicationInfo.flags
6862                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6863                return null;
6864            }
6865            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6866            if (ps == null) {
6867                return null;
6868            }
6869            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6870                    ps.readUserState(userId), userId);
6871            if (ai == null) {
6872                return null;
6873            }
6874            final ResolveInfo res = new ResolveInfo();
6875            res.activityInfo = ai;
6876            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6877                res.filter = info;
6878            }
6879            res.priority = info.getPriority();
6880            res.preferredOrder = activity.owner.mPreferredOrder;
6881            //System.out.println("Result: " + res.activityInfo.className +
6882            //                   " = " + res.priority);
6883            res.match = match;
6884            res.isDefault = info.hasDefault;
6885            res.labelRes = info.labelRes;
6886            res.nonLocalizedLabel = info.nonLocalizedLabel;
6887            res.icon = info.icon;
6888            res.system = isSystemApp(res.activityInfo.applicationInfo);
6889            return res;
6890        }
6891
6892        @Override
6893        protected void sortResults(List<ResolveInfo> results) {
6894            Collections.sort(results, mResolvePrioritySorter);
6895        }
6896
6897        @Override
6898        protected void dumpFilter(PrintWriter out, String prefix,
6899                PackageParser.ActivityIntentInfo filter) {
6900            out.print(prefix); out.print(
6901                    Integer.toHexString(System.identityHashCode(filter.activity)));
6902                    out.print(' ');
6903                    filter.activity.printComponentShortName(out);
6904                    out.print(" filter ");
6905                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6906        }
6907
6908//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6909//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6910//            final List<ResolveInfo> retList = Lists.newArrayList();
6911//            while (i.hasNext()) {
6912//                final ResolveInfo resolveInfo = i.next();
6913//                if (isEnabledLP(resolveInfo.activityInfo)) {
6914//                    retList.add(resolveInfo);
6915//                }
6916//            }
6917//            return retList;
6918//        }
6919
6920        // Keys are String (activity class name), values are Activity.
6921        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6922                = new HashMap<ComponentName, PackageParser.Activity>();
6923        private int mFlags;
6924    }
6925
6926    private final class ServiceIntentResolver
6927            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6929                boolean defaultOnly, int userId) {
6930            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6931            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6932        }
6933
6934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6935                int userId) {
6936            if (!sUserManager.exists(userId)) return null;
6937            mFlags = flags;
6938            return super.queryIntent(intent, resolvedType,
6939                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6940        }
6941
6942        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6943                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6944            if (!sUserManager.exists(userId)) return null;
6945            if (packageServices == null) {
6946                return null;
6947            }
6948            mFlags = flags;
6949            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6950            final int N = packageServices.size();
6951            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6952                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6953
6954            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6955            for (int i = 0; i < N; ++i) {
6956                intentFilters = packageServices.get(i).intents;
6957                if (intentFilters != null && intentFilters.size() > 0) {
6958                    PackageParser.ServiceIntentInfo[] array =
6959                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6960                    intentFilters.toArray(array);
6961                    listCut.add(array);
6962                }
6963            }
6964            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6965        }
6966
6967        public final void addService(PackageParser.Service s) {
6968            mServices.put(s.getComponentName(), s);
6969            if (DEBUG_SHOW_INFO) {
6970                Log.v(TAG, "  "
6971                        + (s.info.nonLocalizedLabel != null
6972                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6973                Log.v(TAG, "    Class=" + s.info.name);
6974            }
6975            final int NI = s.intents.size();
6976            int j;
6977            for (j=0; j<NI; j++) {
6978                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6979                if (DEBUG_SHOW_INFO) {
6980                    Log.v(TAG, "    IntentFilter:");
6981                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6982                }
6983                if (!intent.debugCheck()) {
6984                    Log.w(TAG, "==> For Service " + s.info.name);
6985                }
6986                addFilter(intent);
6987            }
6988        }
6989
6990        public final void removeService(PackageParser.Service s) {
6991            mServices.remove(s.getComponentName());
6992            if (DEBUG_SHOW_INFO) {
6993                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6994                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6995                Log.v(TAG, "    Class=" + s.info.name);
6996            }
6997            final int NI = s.intents.size();
6998            int j;
6999            for (j=0; j<NI; j++) {
7000                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7001                if (DEBUG_SHOW_INFO) {
7002                    Log.v(TAG, "    IntentFilter:");
7003                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7004                }
7005                removeFilter(intent);
7006            }
7007        }
7008
7009        @Override
7010        protected boolean allowFilterResult(
7011                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7012            ServiceInfo filterSi = filter.service.info;
7013            for (int i=dest.size()-1; i>=0; i--) {
7014                ServiceInfo destAi = dest.get(i).serviceInfo;
7015                if (destAi.name == filterSi.name
7016                        && destAi.packageName == filterSi.packageName) {
7017                    return false;
7018                }
7019            }
7020            return true;
7021        }
7022
7023        @Override
7024        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7025            return new PackageParser.ServiceIntentInfo[size];
7026        }
7027
7028        @Override
7029        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7030            if (!sUserManager.exists(userId)) return true;
7031            PackageParser.Package p = filter.service.owner;
7032            if (p != null) {
7033                PackageSetting ps = (PackageSetting)p.mExtras;
7034                if (ps != null) {
7035                    // System apps are never considered stopped for purposes of
7036                    // filtering, because there may be no way for the user to
7037                    // actually re-launch them.
7038                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7039                            && ps.getStopped(userId);
7040                }
7041            }
7042            return false;
7043        }
7044
7045        @Override
7046        protected boolean isPackageForFilter(String packageName,
7047                PackageParser.ServiceIntentInfo info) {
7048            return packageName.equals(info.service.owner.packageName);
7049        }
7050
7051        @Override
7052        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7053                int match, int userId) {
7054            if (!sUserManager.exists(userId)) return null;
7055            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7056            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7057                return null;
7058            }
7059            final PackageParser.Service service = info.service;
7060            if (mSafeMode && (service.info.applicationInfo.flags
7061                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7062                return null;
7063            }
7064            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7065            if (ps == null) {
7066                return null;
7067            }
7068            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7069                    ps.readUserState(userId), userId);
7070            if (si == null) {
7071                return null;
7072            }
7073            final ResolveInfo res = new ResolveInfo();
7074            res.serviceInfo = si;
7075            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7076                res.filter = filter;
7077            }
7078            res.priority = info.getPriority();
7079            res.preferredOrder = service.owner.mPreferredOrder;
7080            //System.out.println("Result: " + res.activityInfo.className +
7081            //                   " = " + res.priority);
7082            res.match = match;
7083            res.isDefault = info.hasDefault;
7084            res.labelRes = info.labelRes;
7085            res.nonLocalizedLabel = info.nonLocalizedLabel;
7086            res.icon = info.icon;
7087            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7088            return res;
7089        }
7090
7091        @Override
7092        protected void sortResults(List<ResolveInfo> results) {
7093            Collections.sort(results, mResolvePrioritySorter);
7094        }
7095
7096        @Override
7097        protected void dumpFilter(PrintWriter out, String prefix,
7098                PackageParser.ServiceIntentInfo filter) {
7099            out.print(prefix); out.print(
7100                    Integer.toHexString(System.identityHashCode(filter.service)));
7101                    out.print(' ');
7102                    filter.service.printComponentShortName(out);
7103                    out.print(" filter ");
7104                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7105        }
7106
7107//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7108//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7109//            final List<ResolveInfo> retList = Lists.newArrayList();
7110//            while (i.hasNext()) {
7111//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7112//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7113//                    retList.add(resolveInfo);
7114//                }
7115//            }
7116//            return retList;
7117//        }
7118
7119        // Keys are String (activity class name), values are Activity.
7120        private final HashMap<ComponentName, PackageParser.Service> mServices
7121                = new HashMap<ComponentName, PackageParser.Service>();
7122        private int mFlags;
7123    };
7124
7125    private final class ProviderIntentResolver
7126            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7127        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7128                boolean defaultOnly, int userId) {
7129            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7130            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7131        }
7132
7133        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7134                int userId) {
7135            if (!sUserManager.exists(userId))
7136                return null;
7137            mFlags = flags;
7138            return super.queryIntent(intent, resolvedType,
7139                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7140        }
7141
7142        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7143                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7144            if (!sUserManager.exists(userId))
7145                return null;
7146            if (packageProviders == null) {
7147                return null;
7148            }
7149            mFlags = flags;
7150            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7151            final int N = packageProviders.size();
7152            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7153                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7154
7155            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7156            for (int i = 0; i < N; ++i) {
7157                intentFilters = packageProviders.get(i).intents;
7158                if (intentFilters != null && intentFilters.size() > 0) {
7159                    PackageParser.ProviderIntentInfo[] array =
7160                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7161                    intentFilters.toArray(array);
7162                    listCut.add(array);
7163                }
7164            }
7165            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7166        }
7167
7168        public final void addProvider(PackageParser.Provider p) {
7169            if (mProviders.containsKey(p.getComponentName())) {
7170                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7171                return;
7172            }
7173
7174            mProviders.put(p.getComponentName(), p);
7175            if (DEBUG_SHOW_INFO) {
7176                Log.v(TAG, "  "
7177                        + (p.info.nonLocalizedLabel != null
7178                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7179                Log.v(TAG, "    Class=" + p.info.name);
7180            }
7181            final int NI = p.intents.size();
7182            int j;
7183            for (j = 0; j < NI; j++) {
7184                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7185                if (DEBUG_SHOW_INFO) {
7186                    Log.v(TAG, "    IntentFilter:");
7187                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7188                }
7189                if (!intent.debugCheck()) {
7190                    Log.w(TAG, "==> For Provider " + p.info.name);
7191                }
7192                addFilter(intent);
7193            }
7194        }
7195
7196        public final void removeProvider(PackageParser.Provider p) {
7197            mProviders.remove(p.getComponentName());
7198            if (DEBUG_SHOW_INFO) {
7199                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7200                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7201                Log.v(TAG, "    Class=" + p.info.name);
7202            }
7203            final int NI = p.intents.size();
7204            int j;
7205            for (j = 0; j < NI; j++) {
7206                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7207                if (DEBUG_SHOW_INFO) {
7208                    Log.v(TAG, "    IntentFilter:");
7209                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7210                }
7211                removeFilter(intent);
7212            }
7213        }
7214
7215        @Override
7216        protected boolean allowFilterResult(
7217                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7218            ProviderInfo filterPi = filter.provider.info;
7219            for (int i = dest.size() - 1; i >= 0; i--) {
7220                ProviderInfo destPi = dest.get(i).providerInfo;
7221                if (destPi.name == filterPi.name
7222                        && destPi.packageName == filterPi.packageName) {
7223                    return false;
7224                }
7225            }
7226            return true;
7227        }
7228
7229        @Override
7230        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7231            return new PackageParser.ProviderIntentInfo[size];
7232        }
7233
7234        @Override
7235        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7236            if (!sUserManager.exists(userId))
7237                return true;
7238            PackageParser.Package p = filter.provider.owner;
7239            if (p != null) {
7240                PackageSetting ps = (PackageSetting) p.mExtras;
7241                if (ps != null) {
7242                    // System apps are never considered stopped for purposes of
7243                    // filtering, because there may be no way for the user to
7244                    // actually re-launch them.
7245                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7246                            && ps.getStopped(userId);
7247                }
7248            }
7249            return false;
7250        }
7251
7252        @Override
7253        protected boolean isPackageForFilter(String packageName,
7254                PackageParser.ProviderIntentInfo info) {
7255            return packageName.equals(info.provider.owner.packageName);
7256        }
7257
7258        @Override
7259        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7260                int match, int userId) {
7261            if (!sUserManager.exists(userId))
7262                return null;
7263            final PackageParser.ProviderIntentInfo info = filter;
7264            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7265                return null;
7266            }
7267            final PackageParser.Provider provider = info.provider;
7268            if (mSafeMode && (provider.info.applicationInfo.flags
7269                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7270                return null;
7271            }
7272            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7273            if (ps == null) {
7274                return null;
7275            }
7276            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7277                    ps.readUserState(userId), userId);
7278            if (pi == null) {
7279                return null;
7280            }
7281            final ResolveInfo res = new ResolveInfo();
7282            res.providerInfo = pi;
7283            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7284                res.filter = filter;
7285            }
7286            res.priority = info.getPriority();
7287            res.preferredOrder = provider.owner.mPreferredOrder;
7288            res.match = match;
7289            res.isDefault = info.hasDefault;
7290            res.labelRes = info.labelRes;
7291            res.nonLocalizedLabel = info.nonLocalizedLabel;
7292            res.icon = info.icon;
7293            res.system = isSystemApp(res.providerInfo.applicationInfo);
7294            return res;
7295        }
7296
7297        @Override
7298        protected void sortResults(List<ResolveInfo> results) {
7299            Collections.sort(results, mResolvePrioritySorter);
7300        }
7301
7302        @Override
7303        protected void dumpFilter(PrintWriter out, String prefix,
7304                PackageParser.ProviderIntentInfo filter) {
7305            out.print(prefix);
7306            out.print(
7307                    Integer.toHexString(System.identityHashCode(filter.provider)));
7308            out.print(' ');
7309            filter.provider.printComponentShortName(out);
7310            out.print(" filter ");
7311            out.println(Integer.toHexString(System.identityHashCode(filter)));
7312        }
7313
7314        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7315                = new HashMap<ComponentName, PackageParser.Provider>();
7316        private int mFlags;
7317    };
7318
7319    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7320            new Comparator<ResolveInfo>() {
7321        public int compare(ResolveInfo r1, ResolveInfo r2) {
7322            int v1 = r1.priority;
7323            int v2 = r2.priority;
7324            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7325            if (v1 != v2) {
7326                return (v1 > v2) ? -1 : 1;
7327            }
7328            v1 = r1.preferredOrder;
7329            v2 = r2.preferredOrder;
7330            if (v1 != v2) {
7331                return (v1 > v2) ? -1 : 1;
7332            }
7333            if (r1.isDefault != r2.isDefault) {
7334                return r1.isDefault ? -1 : 1;
7335            }
7336            v1 = r1.match;
7337            v2 = r2.match;
7338            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7339            if (v1 != v2) {
7340                return (v1 > v2) ? -1 : 1;
7341            }
7342            if (r1.system != r2.system) {
7343                return r1.system ? -1 : 1;
7344            }
7345            return 0;
7346        }
7347    };
7348
7349    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7350            new Comparator<ProviderInfo>() {
7351        public int compare(ProviderInfo p1, ProviderInfo p2) {
7352            final int v1 = p1.initOrder;
7353            final int v2 = p2.initOrder;
7354            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7355        }
7356    };
7357
7358    static final void sendPackageBroadcast(String action, String pkg,
7359            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7360            int[] userIds) {
7361        IActivityManager am = ActivityManagerNative.getDefault();
7362        if (am != null) {
7363            try {
7364                if (userIds == null) {
7365                    userIds = am.getRunningUserIds();
7366                }
7367                for (int id : userIds) {
7368                    final Intent intent = new Intent(action,
7369                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7370                    if (extras != null) {
7371                        intent.putExtras(extras);
7372                    }
7373                    if (targetPkg != null) {
7374                        intent.setPackage(targetPkg);
7375                    }
7376                    // Modify the UID when posting to other users
7377                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7378                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7379                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7380                        intent.putExtra(Intent.EXTRA_UID, uid);
7381                    }
7382                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7383                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7384                    if (DEBUG_BROADCASTS) {
7385                        RuntimeException here = new RuntimeException("here");
7386                        here.fillInStackTrace();
7387                        Slog.d(TAG, "Sending to user " + id + ": "
7388                                + intent.toShortString(false, true, false, false)
7389                                + " " + intent.getExtras(), here);
7390                    }
7391                    am.broadcastIntent(null, intent, null, finishedReceiver,
7392                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7393                            finishedReceiver != null, false, id);
7394                }
7395            } catch (RemoteException ex) {
7396            }
7397        }
7398    }
7399
7400    /**
7401     * Check if the external storage media is available. This is true if there
7402     * is a mounted external storage medium or if the external storage is
7403     * emulated.
7404     */
7405    private boolean isExternalMediaAvailable() {
7406        return mMediaMounted || Environment.isExternalStorageEmulated();
7407    }
7408
7409    @Override
7410    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7411        // writer
7412        synchronized (mPackages) {
7413            if (!isExternalMediaAvailable()) {
7414                // If the external storage is no longer mounted at this point,
7415                // the caller may not have been able to delete all of this
7416                // packages files and can not delete any more.  Bail.
7417                return null;
7418            }
7419            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7420            if (lastPackage != null) {
7421                pkgs.remove(lastPackage);
7422            }
7423            if (pkgs.size() > 0) {
7424                return pkgs.get(0);
7425            }
7426        }
7427        return null;
7428    }
7429
7430    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7431        if (false) {
7432            RuntimeException here = new RuntimeException("here");
7433            here.fillInStackTrace();
7434            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7435                    + " andCode=" + andCode, here);
7436        }
7437        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7438                userId, andCode ? 1 : 0, packageName));
7439    }
7440
7441    void startCleaningPackages() {
7442        // reader
7443        synchronized (mPackages) {
7444            if (!isExternalMediaAvailable()) {
7445                return;
7446            }
7447            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7448                return;
7449            }
7450        }
7451        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7452        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7453        IActivityManager am = ActivityManagerNative.getDefault();
7454        if (am != null) {
7455            try {
7456                am.startService(null, intent, null, UserHandle.USER_OWNER);
7457            } catch (RemoteException e) {
7458            }
7459        }
7460    }
7461
7462    private final class AppDirObserver extends FileObserver {
7463        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7464            super(path, mask);
7465            mRootDir = path;
7466            mIsRom = isrom;
7467            mIsPrivileged = isPrivileged;
7468        }
7469
7470        public void onEvent(int event, String path) {
7471            String removedPackage = null;
7472            int removedAppId = -1;
7473            int[] removedUsers = null;
7474            String addedPackage = null;
7475            int addedAppId = -1;
7476            int[] addedUsers = null;
7477
7478            // TODO post a message to the handler to obtain serial ordering
7479            synchronized (mInstallLock) {
7480                String fullPathStr = null;
7481                File fullPath = null;
7482                if (path != null) {
7483                    fullPath = new File(mRootDir, path);
7484                    fullPathStr = fullPath.getPath();
7485                }
7486
7487                if (DEBUG_APP_DIR_OBSERVER)
7488                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7489
7490                if (!isPackageFilename(path)) {
7491                    if (DEBUG_APP_DIR_OBSERVER)
7492                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7493                    return;
7494                }
7495
7496                // Ignore packages that are being installed or
7497                // have just been installed.
7498                if (ignoreCodePath(fullPathStr)) {
7499                    return;
7500                }
7501                PackageParser.Package p = null;
7502                PackageSetting ps = null;
7503                // reader
7504                synchronized (mPackages) {
7505                    p = mAppDirs.get(fullPathStr);
7506                    if (p != null) {
7507                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7508                        if (ps != null) {
7509                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7510                        } else {
7511                            removedUsers = sUserManager.getUserIds();
7512                        }
7513                    }
7514                    addedUsers = sUserManager.getUserIds();
7515                }
7516                if ((event&REMOVE_EVENTS) != 0) {
7517                    if (ps != null) {
7518                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7519                        removePackageLI(ps, true);
7520                        removedPackage = ps.name;
7521                        removedAppId = ps.appId;
7522                    }
7523                }
7524
7525                if ((event&ADD_EVENTS) != 0) {
7526                    if (p == null) {
7527                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7528                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7529                        if (mIsRom) {
7530                            flags |= PackageParser.PARSE_IS_SYSTEM
7531                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7532                            if (mIsPrivileged) {
7533                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7534                            }
7535                        }
7536                        p = scanPackageLI(fullPath, flags,
7537                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7538                                System.currentTimeMillis(), UserHandle.ALL);
7539                        if (p != null) {
7540                            /*
7541                             * TODO this seems dangerous as the package may have
7542                             * changed since we last acquired the mPackages
7543                             * lock.
7544                             */
7545                            // writer
7546                            synchronized (mPackages) {
7547                                updatePermissionsLPw(p.packageName, p,
7548                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7549                            }
7550                            addedPackage = p.applicationInfo.packageName;
7551                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7552                        }
7553                    }
7554                }
7555
7556                // reader
7557                synchronized (mPackages) {
7558                    mSettings.writeLPr();
7559                }
7560            }
7561
7562            if (removedPackage != null) {
7563                Bundle extras = new Bundle(1);
7564                extras.putInt(Intent.EXTRA_UID, removedAppId);
7565                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7566                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7567                        extras, null, null, removedUsers);
7568            }
7569            if (addedPackage != null) {
7570                Bundle extras = new Bundle(1);
7571                extras.putInt(Intent.EXTRA_UID, addedAppId);
7572                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7573                        extras, null, null, addedUsers);
7574            }
7575        }
7576
7577        private final String mRootDir;
7578        private final boolean mIsRom;
7579        private final boolean mIsPrivileged;
7580    }
7581
7582    /*
7583     * The old-style observer methods all just trampoline to the newer signature with
7584     * expanded install observer API.  The older API continues to work but does not
7585     * supply the additional details of the Observer2 API.
7586     */
7587
7588    /* Called when a downloaded package installation has been confirmed by the user */
7589    public void installPackage(
7590            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7591        installPackageEtc(packageURI, observer, null, flags, null);
7592    }
7593
7594    /* Called when a downloaded package installation has been confirmed by the user */
7595    @Override
7596    public void installPackage(
7597            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7598            final String installerPackageName) {
7599        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7600                installerPackageName, null, null, null);
7601    }
7602
7603    @Override
7604    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7605            int flags, String installerPackageName, Uri verificationURI,
7606            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7607        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7608                VerificationParams.NO_UID, manifestDigest);
7609        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7610                installerPackageName, verificationParams, encryptionParams);
7611    }
7612
7613    @Override
7614    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7615            IPackageInstallObserver observer, int flags, String installerPackageName,
7616            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7617        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7618                installerPackageName, verificationParams, encryptionParams);
7619    }
7620
7621    /*
7622     * And here are the "live" versions that take both observer arguments
7623     */
7624    public void installPackageEtc(
7625            final Uri packageURI, final IPackageInstallObserver observer,
7626            IPackageInstallObserver2 observer2, final int flags) {
7627        installPackageEtc(packageURI, observer, observer2, flags, null);
7628    }
7629
7630    public void installPackageEtc(
7631            final Uri packageURI, final IPackageInstallObserver observer,
7632            final IPackageInstallObserver2 observer2, final int flags,
7633            final String installerPackageName) {
7634        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7635                installerPackageName, null, null, null);
7636    }
7637
7638    @Override
7639    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7640            IPackageInstallObserver2 observer2,
7641            int flags, String installerPackageName, Uri verificationURI,
7642            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7643        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7644                VerificationParams.NO_UID, manifestDigest);
7645        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7646                installerPackageName, verificationParams, encryptionParams);
7647    }
7648
7649    /*
7650     * All of the installPackage...*() methods redirect to this one for the master implementation
7651     */
7652    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7653            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7654            int flags, String installerPackageName,
7655            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7656        if (observer == null && observer2 == null) {
7657            throw new IllegalArgumentException("No install observer supplied");
7658        }
7659        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7660                null);
7661
7662        final int uid = Binder.getCallingUid();
7663        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7664            try {
7665                if (observer != null) {
7666                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7667                }
7668                if (observer2 != null) {
7669                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7670                }
7671            } catch (RemoteException re) {
7672            }
7673            return;
7674        }
7675
7676        UserHandle user;
7677        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7678            user = UserHandle.ALL;
7679        } else {
7680            user = new UserHandle(UserHandle.getUserId(uid));
7681        }
7682
7683        final int filteredFlags;
7684
7685        if (uid == Process.SHELL_UID || uid == 0) {
7686            if (DEBUG_INSTALL) {
7687                Slog.v(TAG, "Install from ADB");
7688            }
7689            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7690        } else {
7691            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7692        }
7693
7694        verificationParams.setInstallerUid(uid);
7695
7696        final Message msg = mHandler.obtainMessage(INIT_COPY);
7697        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7698                installerPackageName, verificationParams, encryptionParams, user);
7699        mHandler.sendMessage(msg);
7700    }
7701
7702    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7703        Bundle extras = new Bundle(1);
7704        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7705
7706        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7707                packageName, extras, null, null, new int[] {userId});
7708        try {
7709            IActivityManager am = ActivityManagerNative.getDefault();
7710            final boolean isSystem =
7711                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7712            if (isSystem && am.isUserRunning(userId, false)) {
7713                // The just-installed/enabled app is bundled on the system, so presumed
7714                // to be able to run automatically without needing an explicit launch.
7715                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7716                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7717                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7718                        .setPackage(packageName);
7719                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7720                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7721            }
7722        } catch (RemoteException e) {
7723            // shouldn't happen
7724            Slog.w(TAG, "Unable to bootstrap installed package", e);
7725        }
7726    }
7727
7728    @Override
7729    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7730            int userId) {
7731        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7732        PackageSetting pkgSetting;
7733        final int uid = Binder.getCallingUid();
7734        if (UserHandle.getUserId(uid) != userId) {
7735            mContext.enforceCallingOrSelfPermission(
7736                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7737                    "setApplicationBlockedSetting for user " + userId);
7738        }
7739
7740        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7741            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7742            return false;
7743        }
7744
7745        long callingId = Binder.clearCallingIdentity();
7746        try {
7747            boolean sendAdded = false;
7748            boolean sendRemoved = false;
7749            // writer
7750            synchronized (mPackages) {
7751                pkgSetting = mSettings.mPackages.get(packageName);
7752                if (pkgSetting == null) {
7753                    return false;
7754                }
7755                if (pkgSetting.getBlocked(userId) != blocked) {
7756                    pkgSetting.setBlocked(blocked, userId);
7757                    mSettings.writePackageRestrictionsLPr(userId);
7758                    if (blocked) {
7759                        sendRemoved = true;
7760                    } else {
7761                        sendAdded = true;
7762                    }
7763                }
7764            }
7765            if (sendAdded) {
7766                sendPackageAddedForUser(packageName, pkgSetting, userId);
7767                return true;
7768            }
7769            if (sendRemoved) {
7770                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7771                        "blocking pkg");
7772                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7773            }
7774        } finally {
7775            Binder.restoreCallingIdentity(callingId);
7776        }
7777        return false;
7778    }
7779
7780    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7781            int userId) {
7782        final PackageRemovedInfo info = new PackageRemovedInfo();
7783        info.removedPackage = packageName;
7784        info.removedUsers = new int[] {userId};
7785        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7786        info.sendBroadcast(false, false, false);
7787    }
7788
7789    /**
7790     * Returns true if application is not found or there was an error. Otherwise it returns
7791     * the blocked state of the package for the given user.
7792     */
7793    @Override
7794    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7795        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7796        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7797                "getApplicationBlocked for user " + userId);
7798        PackageSetting pkgSetting;
7799        long callingId = Binder.clearCallingIdentity();
7800        try {
7801            // writer
7802            synchronized (mPackages) {
7803                pkgSetting = mSettings.mPackages.get(packageName);
7804                if (pkgSetting == null) {
7805                    return true;
7806                }
7807                return pkgSetting.getBlocked(userId);
7808            }
7809        } finally {
7810            Binder.restoreCallingIdentity(callingId);
7811        }
7812    }
7813
7814    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7815            int flags) {
7816        // TODO: install stage!
7817        try {
7818            observer.packageInstalled(basePackageName, null,
7819                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7820        } catch (RemoteException ignored) {
7821        }
7822    }
7823
7824    /**
7825     * @hide
7826     */
7827    @Override
7828    public int installExistingPackageAsUser(String packageName, int userId) {
7829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7830                null);
7831        PackageSetting pkgSetting;
7832        final int uid = Binder.getCallingUid();
7833        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7834        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7835            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7836        }
7837
7838        long callingId = Binder.clearCallingIdentity();
7839        try {
7840            boolean sendAdded = false;
7841            Bundle extras = new Bundle(1);
7842
7843            // writer
7844            synchronized (mPackages) {
7845                pkgSetting = mSettings.mPackages.get(packageName);
7846                if (pkgSetting == null) {
7847                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7848                }
7849                if (!pkgSetting.getInstalled(userId)) {
7850                    pkgSetting.setInstalled(true, userId);
7851                    pkgSetting.setBlocked(false, userId);
7852                    mSettings.writePackageRestrictionsLPr(userId);
7853                    sendAdded = true;
7854                }
7855            }
7856
7857            if (sendAdded) {
7858                sendPackageAddedForUser(packageName, pkgSetting, userId);
7859            }
7860        } finally {
7861            Binder.restoreCallingIdentity(callingId);
7862        }
7863
7864        return PackageManager.INSTALL_SUCCEEDED;
7865    }
7866
7867    boolean isUserRestricted(int userId, String restrictionKey) {
7868        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7869        if (restrictions.getBoolean(restrictionKey, false)) {
7870            Log.w(TAG, "User is restricted: " + restrictionKey);
7871            return true;
7872        }
7873        return false;
7874    }
7875
7876    @Override
7877    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7878        mContext.enforceCallingOrSelfPermission(
7879                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7880                "Only package verification agents can verify applications");
7881
7882        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7883        final PackageVerificationResponse response = new PackageVerificationResponse(
7884                verificationCode, Binder.getCallingUid());
7885        msg.arg1 = id;
7886        msg.obj = response;
7887        mHandler.sendMessage(msg);
7888    }
7889
7890    @Override
7891    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7892            long millisecondsToDelay) {
7893        mContext.enforceCallingOrSelfPermission(
7894                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7895                "Only package verification agents can extend verification timeouts");
7896
7897        final PackageVerificationState state = mPendingVerification.get(id);
7898        final PackageVerificationResponse response = new PackageVerificationResponse(
7899                verificationCodeAtTimeout, Binder.getCallingUid());
7900
7901        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7902            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7903        }
7904        if (millisecondsToDelay < 0) {
7905            millisecondsToDelay = 0;
7906        }
7907        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7908                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7909            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7910        }
7911
7912        if ((state != null) && !state.timeoutExtended()) {
7913            state.extendTimeout();
7914
7915            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7916            msg.arg1 = id;
7917            msg.obj = response;
7918            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7919        }
7920    }
7921
7922    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7923            int verificationCode, UserHandle user) {
7924        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7925        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7926        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7927        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7928        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7929
7930        mContext.sendBroadcastAsUser(intent, user,
7931                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7932    }
7933
7934    private ComponentName matchComponentForVerifier(String packageName,
7935            List<ResolveInfo> receivers) {
7936        ActivityInfo targetReceiver = null;
7937
7938        final int NR = receivers.size();
7939        for (int i = 0; i < NR; i++) {
7940            final ResolveInfo info = receivers.get(i);
7941            if (info.activityInfo == null) {
7942                continue;
7943            }
7944
7945            if (packageName.equals(info.activityInfo.packageName)) {
7946                targetReceiver = info.activityInfo;
7947                break;
7948            }
7949        }
7950
7951        if (targetReceiver == null) {
7952            return null;
7953        }
7954
7955        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7956    }
7957
7958    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7959            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7960        if (pkgInfo.verifiers.length == 0) {
7961            return null;
7962        }
7963
7964        final int N = pkgInfo.verifiers.length;
7965        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7966        for (int i = 0; i < N; i++) {
7967            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7968
7969            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7970                    receivers);
7971            if (comp == null) {
7972                continue;
7973            }
7974
7975            final int verifierUid = getUidForVerifier(verifierInfo);
7976            if (verifierUid == -1) {
7977                continue;
7978            }
7979
7980            if (DEBUG_VERIFY) {
7981                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7982                        + " with the correct signature");
7983            }
7984            sufficientVerifiers.add(comp);
7985            verificationState.addSufficientVerifier(verifierUid);
7986        }
7987
7988        return sufficientVerifiers;
7989    }
7990
7991    private int getUidForVerifier(VerifierInfo verifierInfo) {
7992        synchronized (mPackages) {
7993            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7994            if (pkg == null) {
7995                return -1;
7996            } else if (pkg.mSignatures.length != 1) {
7997                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7998                        + " has more than one signature; ignoring");
7999                return -1;
8000            }
8001
8002            /*
8003             * If the public key of the package's signature does not match
8004             * our expected public key, then this is a different package and
8005             * we should skip.
8006             */
8007
8008            final byte[] expectedPublicKey;
8009            try {
8010                final Signature verifierSig = pkg.mSignatures[0];
8011                final PublicKey publicKey = verifierSig.getPublicKey();
8012                expectedPublicKey = publicKey.getEncoded();
8013            } catch (CertificateException e) {
8014                return -1;
8015            }
8016
8017            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8018
8019            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8020                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8021                        + " does not have the expected public key; ignoring");
8022                return -1;
8023            }
8024
8025            return pkg.applicationInfo.uid;
8026        }
8027    }
8028
8029    @Override
8030    public void finishPackageInstall(int token) {
8031        enforceSystemOrRoot("Only the system is allowed to finish installs");
8032
8033        if (DEBUG_INSTALL) {
8034            Slog.v(TAG, "BM finishing package install for " + token);
8035        }
8036
8037        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8038        mHandler.sendMessage(msg);
8039    }
8040
8041    /**
8042     * Get the verification agent timeout.
8043     *
8044     * @return verification timeout in milliseconds
8045     */
8046    private long getVerificationTimeout() {
8047        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8048                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8049                DEFAULT_VERIFICATION_TIMEOUT);
8050    }
8051
8052    /**
8053     * Get the default verification agent response code.
8054     *
8055     * @return default verification response code
8056     */
8057    private int getDefaultVerificationResponse() {
8058        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8059                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8060                DEFAULT_VERIFICATION_RESPONSE);
8061    }
8062
8063    /**
8064     * Check whether or not package verification has been enabled.
8065     *
8066     * @return true if verification should be performed
8067     */
8068    private boolean isVerificationEnabled(int flags) {
8069        if (!DEFAULT_VERIFY_ENABLE) {
8070            return false;
8071        }
8072
8073        // Check if installing from ADB
8074        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8075            // Do not run verification in a test harness environment
8076            if (ActivityManager.isRunningInTestHarness()) {
8077                return false;
8078            }
8079            // Check if the developer does not want package verification for ADB installs
8080            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8081                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8082                return false;
8083            }
8084        }
8085
8086        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8087                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8088    }
8089
8090    /**
8091     * Get the "allow unknown sources" setting.
8092     *
8093     * @return the current "allow unknown sources" setting
8094     */
8095    private int getUnknownSourcesSettings() {
8096        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8097                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8098                -1);
8099    }
8100
8101    @Override
8102    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8103        final int uid = Binder.getCallingUid();
8104        // writer
8105        synchronized (mPackages) {
8106            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8107            if (targetPackageSetting == null) {
8108                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8109            }
8110
8111            PackageSetting installerPackageSetting;
8112            if (installerPackageName != null) {
8113                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8114                if (installerPackageSetting == null) {
8115                    throw new IllegalArgumentException("Unknown installer package: "
8116                            + installerPackageName);
8117                }
8118            } else {
8119                installerPackageSetting = null;
8120            }
8121
8122            Signature[] callerSignature;
8123            Object obj = mSettings.getUserIdLPr(uid);
8124            if (obj != null) {
8125                if (obj instanceof SharedUserSetting) {
8126                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8127                } else if (obj instanceof PackageSetting) {
8128                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8129                } else {
8130                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8131                }
8132            } else {
8133                throw new SecurityException("Unknown calling uid " + uid);
8134            }
8135
8136            // Verify: can't set installerPackageName to a package that is
8137            // not signed with the same cert as the caller.
8138            if (installerPackageSetting != null) {
8139                if (compareSignatures(callerSignature,
8140                        installerPackageSetting.signatures.mSignatures)
8141                        != PackageManager.SIGNATURE_MATCH) {
8142                    throw new SecurityException(
8143                            "Caller does not have same cert as new installer package "
8144                            + installerPackageName);
8145                }
8146            }
8147
8148            // Verify: if target already has an installer package, it must
8149            // be signed with the same cert as the caller.
8150            if (targetPackageSetting.installerPackageName != null) {
8151                PackageSetting setting = mSettings.mPackages.get(
8152                        targetPackageSetting.installerPackageName);
8153                // If the currently set package isn't valid, then it's always
8154                // okay to change it.
8155                if (setting != null) {
8156                    if (compareSignatures(callerSignature,
8157                            setting.signatures.mSignatures)
8158                            != PackageManager.SIGNATURE_MATCH) {
8159                        throw new SecurityException(
8160                                "Caller does not have same cert as old installer package "
8161                                + targetPackageSetting.installerPackageName);
8162                    }
8163                }
8164            }
8165
8166            // Okay!
8167            targetPackageSetting.installerPackageName = installerPackageName;
8168            scheduleWriteSettingsLocked();
8169        }
8170    }
8171
8172    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8173        // Queue up an async operation since the package installation may take a little while.
8174        mHandler.post(new Runnable() {
8175            public void run() {
8176                mHandler.removeCallbacks(this);
8177                 // Result object to be returned
8178                PackageInstalledInfo res = new PackageInstalledInfo();
8179                res.returnCode = currentStatus;
8180                res.uid = -1;
8181                res.pkg = null;
8182                res.removedInfo = new PackageRemovedInfo();
8183                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8184                    args.doPreInstall(res.returnCode);
8185                    synchronized (mInstallLock) {
8186                        installPackageLI(args, true, res);
8187                    }
8188                    args.doPostInstall(res.returnCode, res.uid);
8189                }
8190
8191                // A restore should be performed at this point if (a) the install
8192                // succeeded, (b) the operation is not an update, and (c) the new
8193                // package has a backupAgent defined.
8194                final boolean update = res.removedInfo.removedPackage != null;
8195                boolean doRestore = (!update
8196                        && res.pkg != null
8197                        && res.pkg.applicationInfo.backupAgentName != null);
8198
8199                // Set up the post-install work request bookkeeping.  This will be used
8200                // and cleaned up by the post-install event handling regardless of whether
8201                // there's a restore pass performed.  Token values are >= 1.
8202                int token;
8203                if (mNextInstallToken < 0) mNextInstallToken = 1;
8204                token = mNextInstallToken++;
8205
8206                PostInstallData data = new PostInstallData(args, res);
8207                mRunningInstalls.put(token, data);
8208                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8209
8210                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8211                    // Pass responsibility to the Backup Manager.  It will perform a
8212                    // restore if appropriate, then pass responsibility back to the
8213                    // Package Manager to run the post-install observer callbacks
8214                    // and broadcasts.
8215                    IBackupManager bm = IBackupManager.Stub.asInterface(
8216                            ServiceManager.getService(Context.BACKUP_SERVICE));
8217                    if (bm != null) {
8218                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8219                                + " to BM for possible restore");
8220                        try {
8221                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8222                        } catch (RemoteException e) {
8223                            // can't happen; the backup manager is local
8224                        } catch (Exception e) {
8225                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8226                            doRestore = false;
8227                        }
8228                    } else {
8229                        Slog.e(TAG, "Backup Manager not found!");
8230                        doRestore = false;
8231                    }
8232                }
8233
8234                if (!doRestore) {
8235                    // No restore possible, or the Backup Manager was mysteriously not
8236                    // available -- just fire the post-install work request directly.
8237                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8238                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8239                    mHandler.sendMessage(msg);
8240                }
8241            }
8242        });
8243    }
8244
8245    private abstract class HandlerParams {
8246        private static final int MAX_RETRIES = 4;
8247
8248        /**
8249         * Number of times startCopy() has been attempted and had a non-fatal
8250         * error.
8251         */
8252        private int mRetries = 0;
8253
8254        /** User handle for the user requesting the information or installation. */
8255        private final UserHandle mUser;
8256
8257        HandlerParams(UserHandle user) {
8258            mUser = user;
8259        }
8260
8261        UserHandle getUser() {
8262            return mUser;
8263        }
8264
8265        final boolean startCopy() {
8266            boolean res;
8267            try {
8268                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8269
8270                if (++mRetries > MAX_RETRIES) {
8271                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8272                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8273                    handleServiceError();
8274                    return false;
8275                } else {
8276                    handleStartCopy();
8277                    res = true;
8278                }
8279            } catch (RemoteException e) {
8280                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8281                mHandler.sendEmptyMessage(MCS_RECONNECT);
8282                res = false;
8283            }
8284            handleReturnCode();
8285            return res;
8286        }
8287
8288        final void serviceError() {
8289            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8290            handleServiceError();
8291            handleReturnCode();
8292        }
8293
8294        abstract void handleStartCopy() throws RemoteException;
8295        abstract void handleServiceError();
8296        abstract void handleReturnCode();
8297    }
8298
8299    class MeasureParams extends HandlerParams {
8300        private final PackageStats mStats;
8301        private boolean mSuccess;
8302
8303        private final IPackageStatsObserver mObserver;
8304
8305        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8306            super(new UserHandle(stats.userHandle));
8307            mObserver = observer;
8308            mStats = stats;
8309        }
8310
8311        @Override
8312        public String toString() {
8313            return "MeasureParams{"
8314                + Integer.toHexString(System.identityHashCode(this))
8315                + " " + mStats.packageName + "}";
8316        }
8317
8318        @Override
8319        void handleStartCopy() throws RemoteException {
8320            synchronized (mInstallLock) {
8321                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8322            }
8323
8324            if (mSuccess) {
8325                final boolean mounted;
8326                if (Environment.isExternalStorageEmulated()) {
8327                    mounted = true;
8328                } else {
8329                    final String status = Environment.getExternalStorageState();
8330                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8331                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8332                }
8333
8334                if (mounted) {
8335                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8336
8337                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8338                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8339
8340                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8341                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8342
8343                    // Always subtract cache size, since it's a subdirectory
8344                    mStats.externalDataSize -= mStats.externalCacheSize;
8345
8346                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8347                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8348
8349                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8350                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8351                }
8352            }
8353        }
8354
8355        @Override
8356        void handleReturnCode() {
8357            if (mObserver != null) {
8358                try {
8359                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8360                } catch (RemoteException e) {
8361                    Slog.i(TAG, "Observer no longer exists.");
8362                }
8363            }
8364        }
8365
8366        @Override
8367        void handleServiceError() {
8368            Slog.e(TAG, "Could not measure application " + mStats.packageName
8369                            + " external storage");
8370        }
8371    }
8372
8373    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8374            throws RemoteException {
8375        long result = 0;
8376        for (File path : paths) {
8377            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8378        }
8379        return result;
8380    }
8381
8382    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8383        for (File path : paths) {
8384            try {
8385                mcs.clearDirectory(path.getAbsolutePath());
8386            } catch (RemoteException e) {
8387            }
8388        }
8389    }
8390
8391    class InstallParams extends HandlerParams {
8392        final IPackageInstallObserver observer;
8393        final IPackageInstallObserver2 observer2;
8394        int flags;
8395
8396        private final Uri mPackageURI;
8397        final String installerPackageName;
8398        final VerificationParams verificationParams;
8399        private InstallArgs mArgs;
8400        private int mRet;
8401        private File mTempPackage;
8402        final ContainerEncryptionParams encryptionParams;
8403
8404        InstallParams(Uri packageURI,
8405                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8406                int flags, String installerPackageName, VerificationParams verificationParams,
8407                ContainerEncryptionParams encryptionParams, UserHandle user) {
8408            super(user);
8409            this.mPackageURI = packageURI;
8410            this.flags = flags;
8411            this.observer = observer;
8412            this.observer2 = observer2;
8413            this.installerPackageName = installerPackageName;
8414            this.verificationParams = verificationParams;
8415            this.encryptionParams = encryptionParams;
8416        }
8417
8418        @Override
8419        public String toString() {
8420            return "InstallParams{"
8421                + Integer.toHexString(System.identityHashCode(this))
8422                + " " + mPackageURI + "}";
8423        }
8424
8425        public ManifestDigest getManifestDigest() {
8426            if (verificationParams == null) {
8427                return null;
8428            }
8429            return verificationParams.getManifestDigest();
8430        }
8431
8432        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8433            String packageName = pkgLite.packageName;
8434            int installLocation = pkgLite.installLocation;
8435            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8436            // reader
8437            synchronized (mPackages) {
8438                PackageParser.Package pkg = mPackages.get(packageName);
8439                if (pkg != null) {
8440                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8441                        // Check for downgrading.
8442                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8443                            if (pkgLite.versionCode < pkg.mVersionCode) {
8444                                Slog.w(TAG, "Can't install update of " + packageName
8445                                        + " update version " + pkgLite.versionCode
8446                                        + " is older than installed version "
8447                                        + pkg.mVersionCode);
8448                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8449                            }
8450                        }
8451                        // Check for updated system application.
8452                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8453                            if (onSd) {
8454                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8455                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8456                            }
8457                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8458                        } else {
8459                            if (onSd) {
8460                                // Install flag overrides everything.
8461                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8462                            }
8463                            // If current upgrade specifies particular preference
8464                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8465                                // Application explicitly specified internal.
8466                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8467                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8468                                // App explictly prefers external. Let policy decide
8469                            } else {
8470                                // Prefer previous location
8471                                if (isExternal(pkg)) {
8472                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8473                                }
8474                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8475                            }
8476                        }
8477                    } else {
8478                        // Invalid install. Return error code
8479                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8480                    }
8481                }
8482            }
8483            // All the special cases have been taken care of.
8484            // Return result based on recommended install location.
8485            if (onSd) {
8486                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8487            }
8488            return pkgLite.recommendedInstallLocation;
8489        }
8490
8491        private long getMemoryLowThreshold() {
8492            final DeviceStorageMonitorInternal
8493                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8494            if (dsm == null) {
8495                return 0L;
8496            }
8497            return dsm.getMemoryLowThreshold();
8498        }
8499
8500        /*
8501         * Invoke remote method to get package information and install
8502         * location values. Override install location based on default
8503         * policy if needed and then create install arguments based
8504         * on the install location.
8505         */
8506        public void handleStartCopy() throws RemoteException {
8507            int ret = PackageManager.INSTALL_SUCCEEDED;
8508            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8509            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8510            PackageInfoLite pkgLite = null;
8511
8512            if (onInt && onSd) {
8513                // Check if both bits are set.
8514                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8515                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8516            } else {
8517                final long lowThreshold = getMemoryLowThreshold();
8518                if (lowThreshold == 0L) {
8519                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8520                }
8521
8522                try {
8523                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8524                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8525
8526                    final File packageFile;
8527                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8528                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8529                        if (mTempPackage != null) {
8530                            ParcelFileDescriptor out;
8531                            try {
8532                                out = ParcelFileDescriptor.open(mTempPackage,
8533                                        ParcelFileDescriptor.MODE_READ_WRITE);
8534                            } catch (FileNotFoundException e) {
8535                                out = null;
8536                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8537                            }
8538
8539                            // Make a temporary file for decryption.
8540                            ret = mContainerService
8541                                    .copyResource(mPackageURI, encryptionParams, out);
8542                            IoUtils.closeQuietly(out);
8543
8544                            packageFile = mTempPackage;
8545
8546                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8547                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8548                                            | FileUtils.S_IROTH,
8549                                    -1, -1);
8550                        } else {
8551                            packageFile = null;
8552                        }
8553                    } else {
8554                        packageFile = new File(mPackageURI.getPath());
8555                    }
8556
8557                    if (packageFile != null) {
8558                        // Remote call to find out default install location
8559                        final String packageFilePath = packageFile.getAbsolutePath();
8560                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8561                                lowThreshold);
8562
8563                        /*
8564                         * If we have too little free space, try to free cache
8565                         * before giving up.
8566                         */
8567                        if (pkgLite.recommendedInstallLocation
8568                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8569                            final long size = mContainerService.calculateInstalledSize(
8570                                    packageFilePath, isForwardLocked());
8571                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8572                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8573                                        flags, lowThreshold);
8574                            }
8575                            /*
8576                             * The cache free must have deleted the file we
8577                             * downloaded to install.
8578                             *
8579                             * TODO: fix the "freeCache" call to not delete
8580                             *       the file we care about.
8581                             */
8582                            if (pkgLite.recommendedInstallLocation
8583                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8584                                pkgLite.recommendedInstallLocation
8585                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8586                            }
8587                        }
8588                    }
8589                } finally {
8590                    mContext.revokeUriPermission(mPackageURI,
8591                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8592                }
8593            }
8594
8595            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8596                int loc = pkgLite.recommendedInstallLocation;
8597                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8598                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8599                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8600                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8601                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8602                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8603                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8604                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8605                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8606                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8607                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8608                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8609                } else {
8610                    // Override with defaults if needed.
8611                    loc = installLocationPolicy(pkgLite, flags);
8612                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8613                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8614                    } else if (!onSd && !onInt) {
8615                        // Override install location with flags
8616                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8617                            // Set the flag to install on external media.
8618                            flags |= PackageManager.INSTALL_EXTERNAL;
8619                            flags &= ~PackageManager.INSTALL_INTERNAL;
8620                        } else {
8621                            // Make sure the flag for installing on external
8622                            // media is unset
8623                            flags |= PackageManager.INSTALL_INTERNAL;
8624                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8625                        }
8626                    }
8627                }
8628            }
8629
8630            final InstallArgs args = createInstallArgs(this);
8631            mArgs = args;
8632
8633            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8634                 /*
8635                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8636                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8637                 */
8638                int userIdentifier = getUser().getIdentifier();
8639                if (userIdentifier == UserHandle.USER_ALL
8640                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8641                    userIdentifier = UserHandle.USER_OWNER;
8642                }
8643
8644                /*
8645                 * Determine if we have any installed package verifiers. If we
8646                 * do, then we'll defer to them to verify the packages.
8647                 */
8648                final int requiredUid = mRequiredVerifierPackage == null ? -1
8649                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8650                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8651                    final Intent verification = new Intent(
8652                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8653                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8654                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8655
8656                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8657                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8658                            0 /* TODO: Which userId? */);
8659
8660                    if (DEBUG_VERIFY) {
8661                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8662                                + verification.toString() + " with " + pkgLite.verifiers.length
8663                                + " optional verifiers");
8664                    }
8665
8666                    final int verificationId = mPendingVerificationToken++;
8667
8668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8669
8670                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8671                            installerPackageName);
8672
8673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8674
8675                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8676                            pkgLite.packageName);
8677
8678                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8679                            pkgLite.versionCode);
8680
8681                    if (verificationParams != null) {
8682                        if (verificationParams.getVerificationURI() != null) {
8683                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8684                                 verificationParams.getVerificationURI());
8685                        }
8686                        if (verificationParams.getOriginatingURI() != null) {
8687                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8688                                  verificationParams.getOriginatingURI());
8689                        }
8690                        if (verificationParams.getReferrer() != null) {
8691                            verification.putExtra(Intent.EXTRA_REFERRER,
8692                                  verificationParams.getReferrer());
8693                        }
8694                        if (verificationParams.getOriginatingUid() >= 0) {
8695                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8696                                  verificationParams.getOriginatingUid());
8697                        }
8698                        if (verificationParams.getInstallerUid() >= 0) {
8699                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8700                                  verificationParams.getInstallerUid());
8701                        }
8702                    }
8703
8704                    final PackageVerificationState verificationState = new PackageVerificationState(
8705                            requiredUid, args);
8706
8707                    mPendingVerification.append(verificationId, verificationState);
8708
8709                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8710                            receivers, verificationState);
8711
8712                    /*
8713                     * If any sufficient verifiers were listed in the package
8714                     * manifest, attempt to ask them.
8715                     */
8716                    if (sufficientVerifiers != null) {
8717                        final int N = sufficientVerifiers.size();
8718                        if (N == 0) {
8719                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8720                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8721                        } else {
8722                            for (int i = 0; i < N; i++) {
8723                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8724
8725                                final Intent sufficientIntent = new Intent(verification);
8726                                sufficientIntent.setComponent(verifierComponent);
8727
8728                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8729                            }
8730                        }
8731                    }
8732
8733                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8734                            mRequiredVerifierPackage, receivers);
8735                    if (ret == PackageManager.INSTALL_SUCCEEDED
8736                            && mRequiredVerifierPackage != null) {
8737                        /*
8738                         * Send the intent to the required verification agent,
8739                         * but only start the verification timeout after the
8740                         * target BroadcastReceivers have run.
8741                         */
8742                        verification.setComponent(requiredVerifierComponent);
8743                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8744                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8745                                new BroadcastReceiver() {
8746                                    @Override
8747                                    public void onReceive(Context context, Intent intent) {
8748                                        final Message msg = mHandler
8749                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8750                                        msg.arg1 = verificationId;
8751                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8752                                    }
8753                                }, null, 0, null, null);
8754
8755                        /*
8756                         * We don't want the copy to proceed until verification
8757                         * succeeds, so null out this field.
8758                         */
8759                        mArgs = null;
8760                    }
8761                } else {
8762                    /*
8763                     * No package verification is enabled, so immediately start
8764                     * the remote call to initiate copy using temporary file.
8765                     */
8766                    ret = args.copyApk(mContainerService, true);
8767                }
8768            }
8769
8770            mRet = ret;
8771        }
8772
8773        @Override
8774        void handleReturnCode() {
8775            // If mArgs is null, then MCS couldn't be reached. When it
8776            // reconnects, it will try again to install. At that point, this
8777            // will succeed.
8778            if (mArgs != null) {
8779                processPendingInstall(mArgs, mRet);
8780
8781                if (mTempPackage != null) {
8782                    if (!mTempPackage.delete()) {
8783                        Slog.w(TAG, "Couldn't delete temporary file: " +
8784                                mTempPackage.getAbsolutePath());
8785                    }
8786                }
8787            }
8788        }
8789
8790        @Override
8791        void handleServiceError() {
8792            mArgs = createInstallArgs(this);
8793            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8794        }
8795
8796        public boolean isForwardLocked() {
8797            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8798        }
8799
8800        public Uri getPackageUri() {
8801            if (mTempPackage != null) {
8802                return Uri.fromFile(mTempPackage);
8803            } else {
8804                return mPackageURI;
8805            }
8806        }
8807    }
8808
8809    /*
8810     * Utility class used in movePackage api.
8811     * srcArgs and targetArgs are not set for invalid flags and make
8812     * sure to do null checks when invoking methods on them.
8813     * We probably want to return ErrorPrams for both failed installs
8814     * and moves.
8815     */
8816    class MoveParams extends HandlerParams {
8817        final IPackageMoveObserver observer;
8818        final int flags;
8819        final String packageName;
8820        final InstallArgs srcArgs;
8821        final InstallArgs targetArgs;
8822        int uid;
8823        int mRet;
8824
8825        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8826                String packageName, String dataDir, String instructionSet,
8827                int uid, UserHandle user) {
8828            super(user);
8829            this.srcArgs = srcArgs;
8830            this.observer = observer;
8831            this.flags = flags;
8832            this.packageName = packageName;
8833            this.uid = uid;
8834            if (srcArgs != null) {
8835                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8836                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8837            } else {
8838                targetArgs = null;
8839            }
8840        }
8841
8842        @Override
8843        public String toString() {
8844            return "MoveParams{"
8845                + Integer.toHexString(System.identityHashCode(this))
8846                + " " + packageName + "}";
8847        }
8848
8849        public void handleStartCopy() throws RemoteException {
8850            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8851            // Check for storage space on target medium
8852            if (!targetArgs.checkFreeStorage(mContainerService)) {
8853                Log.w(TAG, "Insufficient storage to install");
8854                return;
8855            }
8856
8857            mRet = srcArgs.doPreCopy();
8858            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8859                return;
8860            }
8861
8862            mRet = targetArgs.copyApk(mContainerService, false);
8863            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8864                srcArgs.doPostCopy(uid);
8865                return;
8866            }
8867
8868            mRet = srcArgs.doPostCopy(uid);
8869            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8870                return;
8871            }
8872
8873            mRet = targetArgs.doPreInstall(mRet);
8874            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8875                return;
8876            }
8877
8878            if (DEBUG_SD_INSTALL) {
8879                StringBuilder builder = new StringBuilder();
8880                if (srcArgs != null) {
8881                    builder.append("src: ");
8882                    builder.append(srcArgs.getCodePath());
8883                }
8884                if (targetArgs != null) {
8885                    builder.append(" target : ");
8886                    builder.append(targetArgs.getCodePath());
8887                }
8888                Log.i(TAG, builder.toString());
8889            }
8890        }
8891
8892        @Override
8893        void handleReturnCode() {
8894            targetArgs.doPostInstall(mRet, uid);
8895            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8896            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8897                currentStatus = PackageManager.MOVE_SUCCEEDED;
8898            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8899                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8900            }
8901            processPendingMove(this, currentStatus);
8902        }
8903
8904        @Override
8905        void handleServiceError() {
8906            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8907        }
8908    }
8909
8910    /**
8911     * Used during creation of InstallArgs
8912     *
8913     * @param flags package installation flags
8914     * @return true if should be installed on external storage
8915     */
8916    private static boolean installOnSd(int flags) {
8917        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8918            return false;
8919        }
8920        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8921            return true;
8922        }
8923        return false;
8924    }
8925
8926    /**
8927     * Used during creation of InstallArgs
8928     *
8929     * @param flags package installation flags
8930     * @return true if should be installed as forward locked
8931     */
8932    private static boolean installForwardLocked(int flags) {
8933        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8934    }
8935
8936    private InstallArgs createInstallArgs(InstallParams params) {
8937        if (installOnSd(params.flags) || params.isForwardLocked()) {
8938            return new AsecInstallArgs(params);
8939        } else {
8940            return new FileInstallArgs(params);
8941        }
8942    }
8943
8944    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8945            String nativeLibraryPath, String instructionSet) {
8946        final boolean isInAsec;
8947        if (installOnSd(flags)) {
8948            /* Apps on SD card are always in ASEC containers. */
8949            isInAsec = true;
8950        } else if (installForwardLocked(flags)
8951                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8952            /*
8953             * Forward-locked apps are only in ASEC containers if they're the
8954             * new style
8955             */
8956            isInAsec = true;
8957        } else {
8958            isInAsec = false;
8959        }
8960
8961        if (isInAsec) {
8962            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8963                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8964        } else {
8965            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8966                    instructionSet);
8967        }
8968    }
8969
8970    // Used by package mover
8971    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8972            String instructionSet) {
8973        if (installOnSd(flags) || installForwardLocked(flags)) {
8974            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8975                    + AsecInstallArgs.RES_FILE_NAME);
8976            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8977                    installForwardLocked(flags));
8978        } else {
8979            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8980        }
8981    }
8982
8983    static abstract class InstallArgs {
8984        final IPackageInstallObserver observer;
8985        final IPackageInstallObserver2 observer2;
8986        // Always refers to PackageManager flags only
8987        final int flags;
8988        final Uri packageURI;
8989        final String installerPackageName;
8990        final ManifestDigest manifestDigest;
8991        final UserHandle user;
8992        final String instructionSet;
8993
8994        InstallArgs(Uri packageURI,
8995                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8996                int flags, String installerPackageName, ManifestDigest manifestDigest,
8997                UserHandle user, String instructionSet) {
8998            this.packageURI = packageURI;
8999            this.flags = flags;
9000            this.observer = observer;
9001            this.observer2 = observer2;
9002            this.installerPackageName = installerPackageName;
9003            this.manifestDigest = manifestDigest;
9004            this.user = user;
9005            this.instructionSet = instructionSet;
9006        }
9007
9008        abstract void createCopyFile();
9009        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9010        abstract int doPreInstall(int status);
9011        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9012
9013        abstract int doPostInstall(int status, int uid);
9014        abstract String getCodePath();
9015        abstract String getResourcePath();
9016        abstract String getNativeLibraryPath();
9017        // Need installer lock especially for dex file removal.
9018        abstract void cleanUpResourcesLI();
9019        abstract boolean doPostDeleteLI(boolean delete);
9020        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9021
9022        /**
9023         * Called before the source arguments are copied. This is used mostly
9024         * for MoveParams when it needs to read the source file to put it in the
9025         * destination.
9026         */
9027        int doPreCopy() {
9028            return PackageManager.INSTALL_SUCCEEDED;
9029        }
9030
9031        /**
9032         * Called after the source arguments are copied. This is used mostly for
9033         * MoveParams when it needs to read the source file to put it in the
9034         * destination.
9035         *
9036         * @return
9037         */
9038        int doPostCopy(int uid) {
9039            return PackageManager.INSTALL_SUCCEEDED;
9040        }
9041
9042        protected boolean isFwdLocked() {
9043            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9044        }
9045
9046        UserHandle getUser() {
9047            return user;
9048        }
9049    }
9050
9051    class FileInstallArgs extends InstallArgs {
9052        File installDir;
9053        String codeFileName;
9054        String resourceFileName;
9055        String libraryPath;
9056        boolean created = false;
9057
9058        FileInstallArgs(InstallParams params) {
9059            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9060                    params.installerPackageName, params.getManifestDigest(),
9061                    params.getUser(), null /* instruction set */);
9062        }
9063
9064        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9065                String instructionSet) {
9066            super(null, null, null, 0, null, null, null, instructionSet);
9067            File codeFile = new File(fullCodePath);
9068            installDir = codeFile.getParentFile();
9069            codeFileName = fullCodePath;
9070            resourceFileName = fullResourcePath;
9071            libraryPath = nativeLibraryPath;
9072        }
9073
9074        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9075            super(packageURI, null, null, 0, null, null, null, instructionSet);
9076            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9077            String apkName = getNextCodePath(null, pkgName, ".apk");
9078            codeFileName = new File(installDir, apkName + ".apk").getPath();
9079            resourceFileName = getResourcePathFromCodePath();
9080            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9081        }
9082
9083        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9084            final long lowThreshold;
9085
9086            final DeviceStorageMonitorInternal
9087                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9088            if (dsm == null) {
9089                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9090                lowThreshold = 0L;
9091            } else {
9092                if (dsm.isMemoryLow()) {
9093                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9094                    return false;
9095                }
9096
9097                lowThreshold = dsm.getMemoryLowThreshold();
9098            }
9099
9100            try {
9101                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9102                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9103                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9104            } finally {
9105                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9106            }
9107        }
9108
9109        String getCodePath() {
9110            return codeFileName;
9111        }
9112
9113        void createCopyFile() {
9114            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9115            codeFileName = createTempPackageFile(installDir).getPath();
9116            resourceFileName = getResourcePathFromCodePath();
9117            libraryPath = getLibraryPathFromCodePath();
9118            created = true;
9119        }
9120
9121        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9122            if (temp) {
9123                // Generate temp file name
9124                createCopyFile();
9125            }
9126            // Get a ParcelFileDescriptor to write to the output file
9127            File codeFile = new File(codeFileName);
9128            if (!created) {
9129                try {
9130                    codeFile.createNewFile();
9131                    // Set permissions
9132                    if (!setPermissions()) {
9133                        // Failed setting permissions.
9134                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9135                    }
9136                } catch (IOException e) {
9137                   Slog.w(TAG, "Failed to create file " + codeFile);
9138                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9139                }
9140            }
9141            ParcelFileDescriptor out = null;
9142            try {
9143                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9144            } catch (FileNotFoundException e) {
9145                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9146                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9147            }
9148            // Copy the resource now
9149            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9150            try {
9151                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9152                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9153                ret = imcs.copyResource(packageURI, null, out);
9154            } finally {
9155                IoUtils.closeQuietly(out);
9156                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9157            }
9158
9159            if (isFwdLocked()) {
9160                final File destResourceFile = new File(getResourcePath());
9161
9162                // Copy the public files
9163                try {
9164                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9165                } catch (IOException e) {
9166                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9167                            + " forward-locked app.");
9168                    destResourceFile.delete();
9169                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9170                }
9171            }
9172
9173            final File nativeLibraryFile = new File(getNativeLibraryPath());
9174            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9175            if (nativeLibraryFile.exists()) {
9176                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9177                nativeLibraryFile.delete();
9178            }
9179            try {
9180                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
9181                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9182                    return copyRet;
9183                }
9184            } catch (IOException e) {
9185                Slog.e(TAG, "Copying native libraries failed", e);
9186                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9187            }
9188
9189            return ret;
9190        }
9191
9192        int doPreInstall(int status) {
9193            if (status != PackageManager.INSTALL_SUCCEEDED) {
9194                cleanUp();
9195            }
9196            return status;
9197        }
9198
9199        boolean doRename(int status, final String pkgName, String oldCodePath) {
9200            if (status != PackageManager.INSTALL_SUCCEEDED) {
9201                cleanUp();
9202                return false;
9203            } else {
9204                final File oldCodeFile = new File(getCodePath());
9205                final File oldResourceFile = new File(getResourcePath());
9206                final File oldLibraryFile = new File(getNativeLibraryPath());
9207
9208                // Rename APK file based on packageName
9209                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9210                final File newCodeFile = new File(installDir, apkName + ".apk");
9211                if (!oldCodeFile.renameTo(newCodeFile)) {
9212                    return false;
9213                }
9214                codeFileName = newCodeFile.getPath();
9215
9216                // Rename public resource file if it's forward-locked.
9217                final File newResFile = new File(getResourcePathFromCodePath());
9218                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9219                    return false;
9220                }
9221                resourceFileName = newResFile.getPath();
9222
9223                // Rename library path
9224                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9225                if (newLibraryFile.exists()) {
9226                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9227                    newLibraryFile.delete();
9228                }
9229                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9230                    Slog.e(TAG, "Cannot rename native library directory "
9231                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9232                    return false;
9233                }
9234                libraryPath = newLibraryFile.getPath();
9235
9236                // Attempt to set permissions
9237                if (!setPermissions()) {
9238                    return false;
9239                }
9240
9241                if (!SELinux.restorecon(newCodeFile)) {
9242                    return false;
9243                }
9244
9245                return true;
9246            }
9247        }
9248
9249        int doPostInstall(int status, int uid) {
9250            if (status != PackageManager.INSTALL_SUCCEEDED) {
9251                cleanUp();
9252            }
9253            return status;
9254        }
9255
9256        String getResourcePath() {
9257            return resourceFileName;
9258        }
9259
9260        private String getResourcePathFromCodePath() {
9261            final String codePath = getCodePath();
9262            if (isFwdLocked()) {
9263                final StringBuilder sb = new StringBuilder();
9264
9265                sb.append(mAppInstallDir.getPath());
9266                sb.append('/');
9267                sb.append(getApkName(codePath));
9268                sb.append(".zip");
9269
9270                /*
9271                 * If our APK is a temporary file, mark the resource as a
9272                 * temporary file as well so it can be cleaned up after
9273                 * catastrophic failure.
9274                 */
9275                if (codePath.endsWith(".tmp")) {
9276                    sb.append(".tmp");
9277                }
9278
9279                return sb.toString();
9280            } else {
9281                return codePath;
9282            }
9283        }
9284
9285        private String getLibraryPathFromCodePath() {
9286            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9287        }
9288
9289        @Override
9290        String getNativeLibraryPath() {
9291            if (libraryPath == null) {
9292                libraryPath = getLibraryPathFromCodePath();
9293            }
9294            return libraryPath;
9295        }
9296
9297        private boolean cleanUp() {
9298            boolean ret = true;
9299            String sourceDir = getCodePath();
9300            String publicSourceDir = getResourcePath();
9301            if (sourceDir != null) {
9302                File sourceFile = new File(sourceDir);
9303                if (!sourceFile.exists()) {
9304                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9305                    ret = false;
9306                }
9307                // Delete application's code and resources
9308                sourceFile.delete();
9309            }
9310            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9311                final File publicSourceFile = new File(publicSourceDir);
9312                if (!publicSourceFile.exists()) {
9313                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9314                }
9315                if (publicSourceFile.exists()) {
9316                    publicSourceFile.delete();
9317                }
9318            }
9319
9320            if (libraryPath != null) {
9321                File nativeLibraryFile = new File(libraryPath);
9322                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9323                if (!nativeLibraryFile.delete()) {
9324                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9325                }
9326            }
9327
9328            return ret;
9329        }
9330
9331        void cleanUpResourcesLI() {
9332            String sourceDir = getCodePath();
9333            if (cleanUp()) {
9334                if (instructionSet == null) {
9335                    throw new IllegalStateException("instructionSet == null");
9336                }
9337                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9338                if (retCode < 0) {
9339                    Slog.w(TAG, "Couldn't remove dex file for package: "
9340                            +  " at location "
9341                            + sourceDir + ", retcode=" + retCode);
9342                    // we don't consider this to be a failure of the core package deletion
9343                }
9344            }
9345        }
9346
9347        private boolean setPermissions() {
9348            // TODO Do this in a more elegant way later on. for now just a hack
9349            if (!isFwdLocked()) {
9350                final int filePermissions =
9351                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9352                    |FileUtils.S_IROTH;
9353                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9354                if (retCode != 0) {
9355                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9356                            getCodePath()
9357                            + ". The return code was: " + retCode);
9358                    // TODO Define new internal error
9359                    return false;
9360                }
9361                return true;
9362            }
9363            return true;
9364        }
9365
9366        boolean doPostDeleteLI(boolean delete) {
9367            // XXX err, shouldn't we respect the delete flag?
9368            cleanUpResourcesLI();
9369            return true;
9370        }
9371    }
9372
9373    private boolean isAsecExternal(String cid) {
9374        final String asecPath = PackageHelper.getSdFilesystem(cid);
9375        return !asecPath.startsWith(mAsecInternalPath);
9376    }
9377
9378    /**
9379     * Extract the MountService "container ID" from the full code path of an
9380     * .apk.
9381     */
9382    static String cidFromCodePath(String fullCodePath) {
9383        int eidx = fullCodePath.lastIndexOf("/");
9384        String subStr1 = fullCodePath.substring(0, eidx);
9385        int sidx = subStr1.lastIndexOf("/");
9386        return subStr1.substring(sidx+1, eidx);
9387    }
9388
9389    class AsecInstallArgs extends InstallArgs {
9390        static final String RES_FILE_NAME = "pkg.apk";
9391        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9392
9393        String cid;
9394        String packagePath;
9395        String resourcePath;
9396        String libraryPath;
9397
9398        AsecInstallArgs(InstallParams params) {
9399            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9400                    params.installerPackageName, params.getManifestDigest(),
9401                    params.getUser(), null /* instruction set */);
9402        }
9403
9404        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9405                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9406            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9407                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9408                    null, null, null, instructionSet);
9409            // Extract cid from fullCodePath
9410            int eidx = fullCodePath.lastIndexOf("/");
9411            String subStr1 = fullCodePath.substring(0, eidx);
9412            int sidx = subStr1.lastIndexOf("/");
9413            cid = subStr1.substring(sidx+1, eidx);
9414            setCachePath(subStr1);
9415        }
9416
9417        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9418            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9419                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9420                    null, null, null, instructionSet);
9421            this.cid = cid;
9422            setCachePath(PackageHelper.getSdDir(cid));
9423        }
9424
9425        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9426                boolean isExternal, boolean isForwardLocked) {
9427            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9428                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9429                    null, null, null, instructionSet);
9430            this.cid = cid;
9431        }
9432
9433        void createCopyFile() {
9434            cid = getTempContainerId();
9435        }
9436
9437        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9438            try {
9439                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9440                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9441                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
9442            } finally {
9443                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9444            }
9445        }
9446
9447        private final boolean isExternal() {
9448            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9449        }
9450
9451        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9452            if (temp) {
9453                createCopyFile();
9454            } else {
9455                /*
9456                 * Pre-emptively destroy the container since it's destroyed if
9457                 * copying fails due to it existing anyway.
9458                 */
9459                PackageHelper.destroySdDir(cid);
9460            }
9461
9462            final String newCachePath;
9463            try {
9464                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9465                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9466                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9467                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9468            } finally {
9469                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9470            }
9471
9472            if (newCachePath != null) {
9473                setCachePath(newCachePath);
9474                return PackageManager.INSTALL_SUCCEEDED;
9475            } else {
9476                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9477            }
9478        }
9479
9480        @Override
9481        String getCodePath() {
9482            return packagePath;
9483        }
9484
9485        @Override
9486        String getResourcePath() {
9487            return resourcePath;
9488        }
9489
9490        @Override
9491        String getNativeLibraryPath() {
9492            return libraryPath;
9493        }
9494
9495        int doPreInstall(int status) {
9496            if (status != PackageManager.INSTALL_SUCCEEDED) {
9497                // Destroy container
9498                PackageHelper.destroySdDir(cid);
9499            } else {
9500                boolean mounted = PackageHelper.isContainerMounted(cid);
9501                if (!mounted) {
9502                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9503                            Process.SYSTEM_UID);
9504                    if (newCachePath != null) {
9505                        setCachePath(newCachePath);
9506                    } else {
9507                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9508                    }
9509                }
9510            }
9511            return status;
9512        }
9513
9514        boolean doRename(int status, final String pkgName,
9515                String oldCodePath) {
9516            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9517            String newCachePath = null;
9518            if (PackageHelper.isContainerMounted(cid)) {
9519                // Unmount the container
9520                if (!PackageHelper.unMountSdDir(cid)) {
9521                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9522                    return false;
9523                }
9524            }
9525            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9526                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9527                        " which might be stale. Will try to clean up.");
9528                // Clean up the stale container and proceed to recreate.
9529                if (!PackageHelper.destroySdDir(newCacheId)) {
9530                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9531                    return false;
9532                }
9533                // Successfully cleaned up stale container. Try to rename again.
9534                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9535                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9536                            + " inspite of cleaning it up.");
9537                    return false;
9538                }
9539            }
9540            if (!PackageHelper.isContainerMounted(newCacheId)) {
9541                Slog.w(TAG, "Mounting container " + newCacheId);
9542                newCachePath = PackageHelper.mountSdDir(newCacheId,
9543                        getEncryptKey(), Process.SYSTEM_UID);
9544            } else {
9545                newCachePath = PackageHelper.getSdDir(newCacheId);
9546            }
9547            if (newCachePath == null) {
9548                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9549                return false;
9550            }
9551            Log.i(TAG, "Succesfully renamed " + cid +
9552                    " to " + newCacheId +
9553                    " at new path: " + newCachePath);
9554            cid = newCacheId;
9555            setCachePath(newCachePath);
9556            return true;
9557        }
9558
9559        private void setCachePath(String newCachePath) {
9560            File cachePath = new File(newCachePath);
9561            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9562            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9563
9564            if (isFwdLocked()) {
9565                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9566            } else {
9567                resourcePath = packagePath;
9568            }
9569        }
9570
9571        int doPostInstall(int status, int uid) {
9572            if (status != PackageManager.INSTALL_SUCCEEDED) {
9573                cleanUp();
9574            } else {
9575                final int groupOwner;
9576                final String protectedFile;
9577                if (isFwdLocked()) {
9578                    groupOwner = UserHandle.getSharedAppGid(uid);
9579                    protectedFile = RES_FILE_NAME;
9580                } else {
9581                    groupOwner = -1;
9582                    protectedFile = null;
9583                }
9584
9585                if (uid < Process.FIRST_APPLICATION_UID
9586                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9587                    Slog.e(TAG, "Failed to finalize " + cid);
9588                    PackageHelper.destroySdDir(cid);
9589                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9590                }
9591
9592                boolean mounted = PackageHelper.isContainerMounted(cid);
9593                if (!mounted) {
9594                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9595                }
9596            }
9597            return status;
9598        }
9599
9600        private void cleanUp() {
9601            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9602
9603            // Destroy secure container
9604            PackageHelper.destroySdDir(cid);
9605        }
9606
9607        void cleanUpResourcesLI() {
9608            String sourceFile = getCodePath();
9609            // Remove dex file
9610            if (instructionSet == null) {
9611                throw new IllegalStateException("instructionSet == null");
9612            }
9613            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9614            if (retCode < 0) {
9615                Slog.w(TAG, "Couldn't remove dex file for package: "
9616                        + " at location "
9617                        + sourceFile.toString() + ", retcode=" + retCode);
9618                // we don't consider this to be a failure of the core package deletion
9619            }
9620            cleanUp();
9621        }
9622
9623        boolean matchContainer(String app) {
9624            if (cid.startsWith(app)) {
9625                return true;
9626            }
9627            return false;
9628        }
9629
9630        String getPackageName() {
9631            return getAsecPackageName(cid);
9632        }
9633
9634        boolean doPostDeleteLI(boolean delete) {
9635            boolean ret = false;
9636            boolean mounted = PackageHelper.isContainerMounted(cid);
9637            if (mounted) {
9638                // Unmount first
9639                ret = PackageHelper.unMountSdDir(cid);
9640            }
9641            if (ret && delete) {
9642                cleanUpResourcesLI();
9643            }
9644            return ret;
9645        }
9646
9647        @Override
9648        int doPreCopy() {
9649            if (isFwdLocked()) {
9650                if (!PackageHelper.fixSdPermissions(cid,
9651                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9652                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9653                }
9654            }
9655
9656            return PackageManager.INSTALL_SUCCEEDED;
9657        }
9658
9659        @Override
9660        int doPostCopy(int uid) {
9661            if (isFwdLocked()) {
9662                if (uid < Process.FIRST_APPLICATION_UID
9663                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9664                                RES_FILE_NAME)) {
9665                    Slog.e(TAG, "Failed to finalize " + cid);
9666                    PackageHelper.destroySdDir(cid);
9667                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9668                }
9669            }
9670
9671            return PackageManager.INSTALL_SUCCEEDED;
9672        }
9673    };
9674
9675    static String getAsecPackageName(String packageCid) {
9676        int idx = packageCid.lastIndexOf("-");
9677        if (idx == -1) {
9678            return packageCid;
9679        }
9680        return packageCid.substring(0, idx);
9681    }
9682
9683    // Utility method used to create code paths based on package name and available index.
9684    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9685        String idxStr = "";
9686        int idx = 1;
9687        // Fall back to default value of idx=1 if prefix is not
9688        // part of oldCodePath
9689        if (oldCodePath != null) {
9690            String subStr = oldCodePath;
9691            // Drop the suffix right away
9692            if (subStr.endsWith(suffix)) {
9693                subStr = subStr.substring(0, subStr.length() - suffix.length());
9694            }
9695            // If oldCodePath already contains prefix find out the
9696            // ending index to either increment or decrement.
9697            int sidx = subStr.lastIndexOf(prefix);
9698            if (sidx != -1) {
9699                subStr = subStr.substring(sidx + prefix.length());
9700                if (subStr != null) {
9701                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9702                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9703                    }
9704                    try {
9705                        idx = Integer.parseInt(subStr);
9706                        if (idx <= 1) {
9707                            idx++;
9708                        } else {
9709                            idx--;
9710                        }
9711                    } catch(NumberFormatException e) {
9712                    }
9713                }
9714            }
9715        }
9716        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9717        return prefix + idxStr;
9718    }
9719
9720    // Utility method used to ignore ADD/REMOVE events
9721    // by directory observer.
9722    private static boolean ignoreCodePath(String fullPathStr) {
9723        String apkName = getApkName(fullPathStr);
9724        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9725        if (idx != -1 && ((idx+1) < apkName.length())) {
9726            // Make sure the package ends with a numeral
9727            String version = apkName.substring(idx+1);
9728            try {
9729                Integer.parseInt(version);
9730                return true;
9731            } catch (NumberFormatException e) {}
9732        }
9733        return false;
9734    }
9735
9736    // Utility method that returns the relative package path with respect
9737    // to the installation directory. Like say for /data/data/com.test-1.apk
9738    // string com.test-1 is returned.
9739    static String getApkName(String codePath) {
9740        if (codePath == null) {
9741            return null;
9742        }
9743        int sidx = codePath.lastIndexOf("/");
9744        int eidx = codePath.lastIndexOf(".");
9745        if (eidx == -1) {
9746            eidx = codePath.length();
9747        } else if (eidx == 0) {
9748            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9749            return null;
9750        }
9751        return codePath.substring(sidx+1, eidx);
9752    }
9753
9754    class PackageInstalledInfo {
9755        String name;
9756        int uid;
9757        // The set of users that originally had this package installed.
9758        int[] origUsers;
9759        // The set of users that now have this package installed.
9760        int[] newUsers;
9761        PackageParser.Package pkg;
9762        int returnCode;
9763        PackageRemovedInfo removedInfo;
9764
9765        // In some error cases we want to convey more info back to the observer
9766        String origPackage;
9767        String origPermission;
9768    }
9769
9770    /*
9771     * Install a non-existing package.
9772     */
9773    private void installNewPackageLI(PackageParser.Package pkg,
9774            int parseFlags, int scanMode, UserHandle user,
9775            String installerPackageName, PackageInstalledInfo res) {
9776        // Remember this for later, in case we need to rollback this install
9777        String pkgName = pkg.packageName;
9778
9779        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9780        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9781        synchronized(mPackages) {
9782            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9783                // A package with the same name is already installed, though
9784                // it has been renamed to an older name.  The package we
9785                // are trying to install should be installed as an update to
9786                // the existing one, but that has not been requested, so bail.
9787                Slog.w(TAG, "Attempt to re-install " + pkgName
9788                        + " without first uninstalling package running as "
9789                        + mSettings.mRenamedPackages.get(pkgName));
9790                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9791                return;
9792            }
9793            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9794                // Don't allow installation over an existing package with the same name.
9795                Slog.w(TAG, "Attempt to re-install " + pkgName
9796                        + " without first uninstalling.");
9797                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9798                return;
9799            }
9800        }
9801        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9802        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9803                System.currentTimeMillis(), user);
9804        if (newPackage == null) {
9805            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9806            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9807                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9808            }
9809        } else {
9810            updateSettingsLI(newPackage,
9811                    installerPackageName,
9812                    null, null,
9813                    res);
9814            // delete the partially installed application. the data directory will have to be
9815            // restored if it was already existing
9816            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9817                // remove package from internal structures.  Note that we want deletePackageX to
9818                // delete the package data and cache directories that it created in
9819                // scanPackageLocked, unless those directories existed before we even tried to
9820                // install.
9821                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9822                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9823                                res.removedInfo, true);
9824            }
9825        }
9826    }
9827
9828    private void replacePackageLI(PackageParser.Package pkg,
9829            int parseFlags, int scanMode, UserHandle user,
9830            String installerPackageName, PackageInstalledInfo res) {
9831
9832        PackageParser.Package oldPackage;
9833        String pkgName = pkg.packageName;
9834        int[] allUsers;
9835        boolean[] perUserInstalled;
9836
9837        // First find the old package info and check signatures
9838        synchronized(mPackages) {
9839            oldPackage = mPackages.get(pkgName);
9840            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9841            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9842                    != PackageManager.SIGNATURE_MATCH) {
9843                Slog.w(TAG, "New package has a different signature: " + pkgName);
9844                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9845                return;
9846            }
9847
9848            // In case of rollback, remember per-user/profile install state
9849            PackageSetting ps = mSettings.mPackages.get(pkgName);
9850            allUsers = sUserManager.getUserIds();
9851            perUserInstalled = new boolean[allUsers.length];
9852            for (int i = 0; i < allUsers.length; i++) {
9853                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9854            }
9855        }
9856        boolean sysPkg = (isSystemApp(oldPackage));
9857        if (sysPkg) {
9858            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9859                    user, allUsers, perUserInstalled, installerPackageName, res);
9860        } else {
9861            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9862                    user, allUsers, perUserInstalled, installerPackageName, res);
9863        }
9864    }
9865
9866    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9867            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9868            int[] allUsers, boolean[] perUserInstalled,
9869            String installerPackageName, PackageInstalledInfo res) {
9870        PackageParser.Package newPackage = null;
9871        String pkgName = deletedPackage.packageName;
9872        boolean deletedPkg = true;
9873        boolean updatedSettings = false;
9874
9875        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9876                + deletedPackage);
9877        long origUpdateTime;
9878        if (pkg.mExtras != null) {
9879            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9880        } else {
9881            origUpdateTime = 0;
9882        }
9883
9884        // First delete the existing package while retaining the data directory
9885        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9886                res.removedInfo, true)) {
9887            // If the existing package wasn't successfully deleted
9888            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9889            deletedPkg = false;
9890        } else {
9891            // Successfully deleted the old package. Now proceed with re-installation
9892            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9893            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9894                    System.currentTimeMillis(), user);
9895            if (newPackage == null) {
9896                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9897                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9898                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9899                }
9900            } else {
9901                updateSettingsLI(newPackage,
9902                        installerPackageName,
9903                        allUsers, perUserInstalled,
9904                        res);
9905                updatedSettings = true;
9906            }
9907        }
9908
9909        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9910            // remove package from internal structures.  Note that we want deletePackageX to
9911            // delete the package data and cache directories that it created in
9912            // scanPackageLocked, unless those directories existed before we even tried to
9913            // install.
9914            if(updatedSettings) {
9915                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9916                deletePackageLI(
9917                        pkgName, null, true, allUsers, perUserInstalled,
9918                        PackageManager.DELETE_KEEP_DATA,
9919                                res.removedInfo, true);
9920            }
9921            // Since we failed to install the new package we need to restore the old
9922            // package that we deleted.
9923            if(deletedPkg) {
9924                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9925                File restoreFile = new File(deletedPackage.mPath);
9926                // Parse old package
9927                boolean oldOnSd = isExternal(deletedPackage);
9928                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9929                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9930                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9931                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9932                        | SCAN_UPDATE_TIME;
9933                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9934                        origUpdateTime, null) == null) {
9935                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9936                    return;
9937                }
9938                // Restore of old package succeeded. Update permissions.
9939                // writer
9940                synchronized (mPackages) {
9941                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9942                            UPDATE_PERMISSIONS_ALL);
9943                    // can downgrade to reader
9944                    mSettings.writeLPr();
9945                }
9946                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9947            }
9948        }
9949    }
9950
9951    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9952            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9953            int[] allUsers, boolean[] perUserInstalled,
9954            String installerPackageName, PackageInstalledInfo res) {
9955        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9956                + ", old=" + deletedPackage);
9957        PackageParser.Package newPackage = null;
9958        boolean updatedSettings = false;
9959        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9960                PackageParser.PARSE_IS_SYSTEM;
9961        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9962            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9963        }
9964        String packageName = deletedPackage.packageName;
9965        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9966        if (packageName == null) {
9967            Slog.w(TAG, "Attempt to delete null packageName.");
9968            return;
9969        }
9970        PackageParser.Package oldPkg;
9971        PackageSetting oldPkgSetting;
9972        // reader
9973        synchronized (mPackages) {
9974            oldPkg = mPackages.get(packageName);
9975            oldPkgSetting = mSettings.mPackages.get(packageName);
9976            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9977                    (oldPkgSetting == null)) {
9978                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9979                return;
9980            }
9981        }
9982
9983        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9984
9985        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9986        res.removedInfo.removedPackage = packageName;
9987        // Remove existing system package
9988        removePackageLI(oldPkgSetting, true);
9989        // writer
9990        synchronized (mPackages) {
9991            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9992                // We didn't need to disable the .apk as a current system package,
9993                // which means we are replacing another update that is already
9994                // installed.  We need to make sure to delete the older one's .apk.
9995                res.removedInfo.args = createInstallArgs(0,
9996                        deletedPackage.applicationInfo.sourceDir,
9997                        deletedPackage.applicationInfo.publicSourceDir,
9998                        deletedPackage.applicationInfo.nativeLibraryDir,
9999                        getAppInstructionSet(deletedPackage.applicationInfo));
10000            } else {
10001                res.removedInfo.args = null;
10002            }
10003        }
10004
10005        // Successfully disabled the old package. Now proceed with re-installation
10006        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10007        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10008        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
10009        if (newPackage == null) {
10010            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
10011            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10012                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10013            }
10014        } else {
10015            if (newPackage.mExtras != null) {
10016                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10017                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10018                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10019
10020                // is the update attempting to change shared user? that isn't going to work...
10021                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10022                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10023                            + " to " + newPkgSetting.sharedUser);
10024                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10025                    updatedSettings = true;
10026                }
10027            }
10028
10029            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10030                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10031                updatedSettings = true;
10032            }
10033        }
10034
10035        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10036            // Re installation failed. Restore old information
10037            // Remove new pkg information
10038            if (newPackage != null) {
10039                removeInstalledPackageLI(newPackage, true);
10040            }
10041            // Add back the old system package
10042            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
10043            // Restore the old system information in Settings
10044            synchronized(mPackages) {
10045                if (updatedSettings) {
10046                    mSettings.enableSystemPackageLPw(packageName);
10047                    mSettings.setInstallerPackageName(packageName,
10048                            oldPkgSetting.installerPackageName);
10049                }
10050                mSettings.writeLPr();
10051            }
10052        }
10053    }
10054
10055    // Utility method used to move dex files during install.
10056    private int moveDexFilesLI(PackageParser.Package newPackage) {
10057        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10058            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10059            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
10060                                             instructionSet);
10061            if (retCode != 0) {
10062                /*
10063                 * Programs may be lazily run through dexopt, so the
10064                 * source may not exist. However, something seems to
10065                 * have gone wrong, so note that dexopt needs to be
10066                 * run again and remove the source file. In addition,
10067                 * remove the target to make sure there isn't a stale
10068                 * file from a previous version of the package.
10069                 */
10070                newPackage.mDexOptNeeded = true;
10071                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
10072                mInstaller.rmdex(newPackage.mPath, instructionSet);
10073            }
10074        }
10075        return PackageManager.INSTALL_SUCCEEDED;
10076    }
10077
10078    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10079            int[] allUsers, boolean[] perUserInstalled,
10080            PackageInstalledInfo res) {
10081        String pkgName = newPackage.packageName;
10082        synchronized (mPackages) {
10083            //write settings. the installStatus will be incomplete at this stage.
10084            //note that the new package setting would have already been
10085            //added to mPackages. It hasn't been persisted yet.
10086            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10087            mSettings.writeLPr();
10088        }
10089
10090        if ((res.returnCode = moveDexFilesLI(newPackage))
10091                != PackageManager.INSTALL_SUCCEEDED) {
10092            // Discontinue if moving dex files failed.
10093            return;
10094        }
10095
10096        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
10097
10098        synchronized (mPackages) {
10099            updatePermissionsLPw(newPackage.packageName, newPackage,
10100                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10101                            ? UPDATE_PERMISSIONS_ALL : 0));
10102            // For system-bundled packages, we assume that installing an upgraded version
10103            // of the package implies that the user actually wants to run that new code,
10104            // so we enable the package.
10105            if (isSystemApp(newPackage)) {
10106                // NB: implicit assumption that system package upgrades apply to all users
10107                if (DEBUG_INSTALL) {
10108                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10109                }
10110                PackageSetting ps = mSettings.mPackages.get(pkgName);
10111                if (ps != null) {
10112                    if (res.origUsers != null) {
10113                        for (int userHandle : res.origUsers) {
10114                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10115                                    userHandle, installerPackageName);
10116                        }
10117                    }
10118                    // Also convey the prior install/uninstall state
10119                    if (allUsers != null && perUserInstalled != null) {
10120                        for (int i = 0; i < allUsers.length; i++) {
10121                            if (DEBUG_INSTALL) {
10122                                Slog.d(TAG, "    user " + allUsers[i]
10123                                        + " => " + perUserInstalled[i]);
10124                            }
10125                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10126                        }
10127                        // these install state changes will be persisted in the
10128                        // upcoming call to mSettings.writeLPr().
10129                    }
10130                }
10131            }
10132            res.name = pkgName;
10133            res.uid = newPackage.applicationInfo.uid;
10134            res.pkg = newPackage;
10135            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10136            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10137            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10138            //to update install status
10139            mSettings.writeLPr();
10140        }
10141    }
10142
10143    private void installPackageLI(InstallArgs args,
10144            boolean newInstall, PackageInstalledInfo res) {
10145        int pFlags = args.flags;
10146        String installerPackageName = args.installerPackageName;
10147        File tmpPackageFile = new File(args.getCodePath());
10148        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10149        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10150        boolean replace = false;
10151        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10152                | (newInstall ? SCAN_NEW_INSTALL : 0);
10153        // Result object to be returned
10154        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10155
10156        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10157        // Retrieve PackageSettings and parse package
10158        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10159                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10160                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10161        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10162        pp.setSeparateProcesses(mSeparateProcesses);
10163        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10164                null, mMetrics, parseFlags);
10165        if (pkg == null) {
10166            res.returnCode = pp.getParseError();
10167            return;
10168        }
10169        String pkgName = res.name = pkg.packageName;
10170        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10171            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10172                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10173                return;
10174            }
10175        }
10176        if (!pp.collectCertificates(pkg, parseFlags)) {
10177            res.returnCode = pp.getParseError();
10178            return;
10179        }
10180
10181        /* If the installer passed in a manifest digest, compare it now. */
10182        if (args.manifestDigest != null) {
10183            if (DEBUG_INSTALL) {
10184                final String parsedManifest = pkg.manifestDigest == null ? "null"
10185                        : pkg.manifestDigest.toString();
10186                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10187                        + parsedManifest);
10188            }
10189
10190            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10191                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10192                return;
10193            }
10194        } else if (DEBUG_INSTALL) {
10195            final String parsedManifest = pkg.manifestDigest == null
10196                    ? "null" : pkg.manifestDigest.toString();
10197            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10198        }
10199
10200        // Get rid of all references to package scan path via parser.
10201        pp = null;
10202        String oldCodePath = null;
10203        boolean systemApp = false;
10204        synchronized (mPackages) {
10205            // Check whether the newly-scanned package wants to define an already-defined perm
10206            int N = pkg.permissions.size();
10207            for (int i = 0; i < N; i++) {
10208                PackageParser.Permission perm = pkg.permissions.get(i);
10209                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10210                if (bp != null) {
10211                    // If the defining package is signed with our cert, it's okay.  This
10212                    // also includes the "updating the same package" case, of course.
10213                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10214                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10215                        Slog.w(TAG, "Package " + pkg.packageName
10216                                + " attempting to redeclare permission " + perm.info.name
10217                                + " already owned by " + bp.sourcePackage);
10218                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10219                        res.origPermission = perm.info.name;
10220                        res.origPackage = bp.sourcePackage;
10221                        return;
10222                    }
10223                }
10224            }
10225
10226            // Check if installing already existing package
10227            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10228                String oldName = mSettings.mRenamedPackages.get(pkgName);
10229                if (pkg.mOriginalPackages != null
10230                        && pkg.mOriginalPackages.contains(oldName)
10231                        && mPackages.containsKey(oldName)) {
10232                    // This package is derived from an original package,
10233                    // and this device has been updating from that original
10234                    // name.  We must continue using the original name, so
10235                    // rename the new package here.
10236                    pkg.setPackageName(oldName);
10237                    pkgName = pkg.packageName;
10238                    replace = true;
10239                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10240                            + oldName + " pkgName=" + pkgName);
10241                } else if (mPackages.containsKey(pkgName)) {
10242                    // This package, under its official name, already exists
10243                    // on the device; we should replace it.
10244                    replace = true;
10245                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10246                }
10247            }
10248            PackageSetting ps = mSettings.mPackages.get(pkgName);
10249            if (ps != null) {
10250                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10251                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10252                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10253                    systemApp = (ps.pkg.applicationInfo.flags &
10254                            ApplicationInfo.FLAG_SYSTEM) != 0;
10255                }
10256                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10257            }
10258        }
10259
10260        if (systemApp && onSd) {
10261            // Disable updates to system apps on sdcard
10262            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10263            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10264            return;
10265        }
10266
10267        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10268            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10269            return;
10270        }
10271        // Set application objects path explicitly after the rename
10272        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10273        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10274        if (replace) {
10275            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10276                    installerPackageName, res);
10277        } else {
10278            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10279                    installerPackageName, res);
10280        }
10281        synchronized (mPackages) {
10282            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10283            if (ps != null) {
10284                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10285            }
10286        }
10287    }
10288
10289    private static boolean isForwardLocked(PackageParser.Package pkg) {
10290        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10291    }
10292
10293
10294    private boolean isForwardLocked(PackageSetting ps) {
10295        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10296    }
10297
10298    private static boolean isExternal(PackageParser.Package pkg) {
10299        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10300    }
10301
10302    private static boolean isExternal(PackageSetting ps) {
10303        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10304    }
10305
10306    private static boolean isSystemApp(PackageParser.Package pkg) {
10307        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10308    }
10309
10310    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10311        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10312    }
10313
10314    private static boolean isSystemApp(ApplicationInfo info) {
10315        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10316    }
10317
10318    private static boolean isSystemApp(PackageSetting ps) {
10319        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10320    }
10321
10322    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10323        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10324    }
10325
10326    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10327        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10328    }
10329
10330    private int packageFlagsToInstallFlags(PackageSetting ps) {
10331        int installFlags = 0;
10332        if (isExternal(ps)) {
10333            installFlags |= PackageManager.INSTALL_EXTERNAL;
10334        }
10335        if (isForwardLocked(ps)) {
10336            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10337        }
10338        return installFlags;
10339    }
10340
10341    private void deleteTempPackageFiles() {
10342        final FilenameFilter filter = new FilenameFilter() {
10343            public boolean accept(File dir, String name) {
10344                return name.startsWith("vmdl") && name.endsWith(".tmp");
10345            }
10346        };
10347        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10348        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10349    }
10350
10351    private static final void deleteTempPackageFilesInDirectory(File directory,
10352            FilenameFilter filter) {
10353        final String[] tmpFilesList = directory.list(filter);
10354        if (tmpFilesList == null) {
10355            return;
10356        }
10357        for (int i = 0; i < tmpFilesList.length; i++) {
10358            final File tmpFile = new File(directory, tmpFilesList[i]);
10359            tmpFile.delete();
10360        }
10361    }
10362
10363    private File createTempPackageFile(File installDir) {
10364        File tmpPackageFile;
10365        try {
10366            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10367        } catch (IOException e) {
10368            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10369            return null;
10370        }
10371        try {
10372            FileUtils.setPermissions(
10373                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10374                    -1, -1);
10375            if (!SELinux.restorecon(tmpPackageFile)) {
10376                return null;
10377            }
10378        } catch (IOException e) {
10379            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10380            return null;
10381        }
10382        return tmpPackageFile;
10383    }
10384
10385    @Override
10386    public void deletePackageAsUser(final String packageName,
10387                                    final IPackageDeleteObserver observer,
10388                                    final int userId, final int flags) {
10389        mContext.enforceCallingOrSelfPermission(
10390                android.Manifest.permission.DELETE_PACKAGES, null);
10391        final int uid = Binder.getCallingUid();
10392        if (UserHandle.getUserId(uid) != userId) {
10393            mContext.enforceCallingPermission(
10394                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10395                    "deletePackage for user " + userId);
10396        }
10397        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10398            try {
10399                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10400            } catch (RemoteException re) {
10401            }
10402            return;
10403        }
10404
10405        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10406        // Queue up an async operation since the package deletion may take a little while.
10407        mHandler.post(new Runnable() {
10408            public void run() {
10409                mHandler.removeCallbacks(this);
10410                final int returnCode = deletePackageX(packageName, userId, flags);
10411                if (observer != null) {
10412                    try {
10413                        observer.packageDeleted(packageName, returnCode);
10414                    } catch (RemoteException e) {
10415                        Log.i(TAG, "Observer no longer exists.");
10416                    } //end catch
10417                } //end if
10418            } //end run
10419        });
10420    }
10421
10422    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10423        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10424                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10425        try {
10426            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10427                    || dpm.isDeviceOwner(packageName))) {
10428                return true;
10429            }
10430        } catch (RemoteException e) {
10431        }
10432        return false;
10433    }
10434
10435    /**
10436     *  This method is an internal method that could be get invoked either
10437     *  to delete an installed package or to clean up a failed installation.
10438     *  After deleting an installed package, a broadcast is sent to notify any
10439     *  listeners that the package has been installed. For cleaning up a failed
10440     *  installation, the broadcast is not necessary since the package's
10441     *  installation wouldn't have sent the initial broadcast either
10442     *  The key steps in deleting a package are
10443     *  deleting the package information in internal structures like mPackages,
10444     *  deleting the packages base directories through installd
10445     *  updating mSettings to reflect current status
10446     *  persisting settings for later use
10447     *  sending a broadcast if necessary
10448     */
10449    private int deletePackageX(String packageName, int userId, int flags) {
10450        final PackageRemovedInfo info = new PackageRemovedInfo();
10451        final boolean res;
10452
10453        if (isPackageDeviceAdmin(packageName, userId)) {
10454            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10455            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10456        }
10457
10458        boolean removedForAllUsers = false;
10459        boolean systemUpdate = false;
10460
10461        // for the uninstall-updates case and restricted profiles, remember the per-
10462        // userhandle installed state
10463        int[] allUsers;
10464        boolean[] perUserInstalled;
10465        synchronized (mPackages) {
10466            PackageSetting ps = mSettings.mPackages.get(packageName);
10467            allUsers = sUserManager.getUserIds();
10468            perUserInstalled = new boolean[allUsers.length];
10469            for (int i = 0; i < allUsers.length; i++) {
10470                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10471            }
10472        }
10473
10474        synchronized (mInstallLock) {
10475            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10476            res = deletePackageLI(packageName,
10477                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10478                            ? UserHandle.ALL : new UserHandle(userId),
10479                    true, allUsers, perUserInstalled,
10480                    flags | REMOVE_CHATTY, info, true);
10481            systemUpdate = info.isRemovedPackageSystemUpdate;
10482            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10483                removedForAllUsers = true;
10484            }
10485            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10486                    + " removedForAllUsers=" + removedForAllUsers);
10487        }
10488
10489        if (res) {
10490            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10491
10492            // If the removed package was a system update, the old system package
10493            // was re-enabled; we need to broadcast this information
10494            if (systemUpdate) {
10495                Bundle extras = new Bundle(1);
10496                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10497                        ? info.removedAppId : info.uid);
10498                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10499
10500                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10501                        extras, null, null, null);
10502                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10503                        extras, null, null, null);
10504                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10505                        null, packageName, null, null);
10506            }
10507        }
10508        // Force a gc here.
10509        Runtime.getRuntime().gc();
10510        // Delete the resources here after sending the broadcast to let
10511        // other processes clean up before deleting resources.
10512        if (info.args != null) {
10513            synchronized (mInstallLock) {
10514                info.args.doPostDeleteLI(true);
10515            }
10516        }
10517
10518        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10519    }
10520
10521    static class PackageRemovedInfo {
10522        String removedPackage;
10523        int uid = -1;
10524        int removedAppId = -1;
10525        int[] removedUsers = null;
10526        boolean isRemovedPackageSystemUpdate = false;
10527        // Clean up resources deleted packages.
10528        InstallArgs args = null;
10529
10530        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10531            Bundle extras = new Bundle(1);
10532            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10533            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10534            if (replacing) {
10535                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10536            }
10537            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10538            if (removedPackage != null) {
10539                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10540                        extras, null, null, removedUsers);
10541                if (fullRemove && !replacing) {
10542                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10543                            extras, null, null, removedUsers);
10544                }
10545            }
10546            if (removedAppId >= 0) {
10547                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10548                        removedUsers);
10549            }
10550        }
10551    }
10552
10553    /*
10554     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10555     * flag is not set, the data directory is removed as well.
10556     * make sure this flag is set for partially installed apps. If not its meaningless to
10557     * delete a partially installed application.
10558     */
10559    private void removePackageDataLI(PackageSetting ps,
10560            int[] allUserHandles, boolean[] perUserInstalled,
10561            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10562        String packageName = ps.name;
10563        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10564        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10565        // Retrieve object to delete permissions for shared user later on
10566        final PackageSetting deletedPs;
10567        // reader
10568        synchronized (mPackages) {
10569            deletedPs = mSettings.mPackages.get(packageName);
10570            if (outInfo != null) {
10571                outInfo.removedPackage = packageName;
10572                outInfo.removedUsers = deletedPs != null
10573                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10574                        : null;
10575            }
10576        }
10577        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10578            removeDataDirsLI(packageName);
10579            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10580        }
10581        // writer
10582        synchronized (mPackages) {
10583            if (deletedPs != null) {
10584                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10585                    if (outInfo != null) {
10586                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10587                    }
10588                    if (deletedPs != null) {
10589                        updatePermissionsLPw(deletedPs.name, null, 0);
10590                        if (deletedPs.sharedUser != null) {
10591                            // remove permissions associated with package
10592                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10593                        }
10594                    }
10595                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10596                }
10597                // make sure to preserve per-user disabled state if this removal was just
10598                // a downgrade of a system app to the factory package
10599                if (allUserHandles != null && perUserInstalled != null) {
10600                    if (DEBUG_REMOVE) {
10601                        Slog.d(TAG, "Propagating install state across downgrade");
10602                    }
10603                    for (int i = 0; i < allUserHandles.length; i++) {
10604                        if (DEBUG_REMOVE) {
10605                            Slog.d(TAG, "    user " + allUserHandles[i]
10606                                    + " => " + perUserInstalled[i]);
10607                        }
10608                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10609                    }
10610                }
10611            }
10612            // can downgrade to reader
10613            if (writeSettings) {
10614                // Save settings now
10615                mSettings.writeLPr();
10616            }
10617        }
10618        if (outInfo != null) {
10619            // A user ID was deleted here. Go through all users and remove it
10620            // from KeyStore.
10621            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10622        }
10623    }
10624
10625    static boolean locationIsPrivileged(File path) {
10626        try {
10627            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10628                    .getCanonicalPath();
10629            return path.getCanonicalPath().startsWith(privilegedAppDir);
10630        } catch (IOException e) {
10631            Slog.e(TAG, "Unable to access code path " + path);
10632        }
10633        return false;
10634    }
10635
10636    /*
10637     * Tries to delete system package.
10638     */
10639    private boolean deleteSystemPackageLI(PackageSetting newPs,
10640            int[] allUserHandles, boolean[] perUserInstalled,
10641            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10642        final boolean applyUserRestrictions
10643                = (allUserHandles != null) && (perUserInstalled != null);
10644        PackageSetting disabledPs = null;
10645        // Confirm if the system package has been updated
10646        // An updated system app can be deleted. This will also have to restore
10647        // the system pkg from system partition
10648        // reader
10649        synchronized (mPackages) {
10650            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10651        }
10652        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10653                + " disabledPs=" + disabledPs);
10654        if (disabledPs == null) {
10655            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10656            return false;
10657        } else if (DEBUG_REMOVE) {
10658            Slog.d(TAG, "Deleting system pkg from data partition");
10659        }
10660        if (DEBUG_REMOVE) {
10661            if (applyUserRestrictions) {
10662                Slog.d(TAG, "Remembering install states:");
10663                for (int i = 0; i < allUserHandles.length; i++) {
10664                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10665                }
10666            }
10667        }
10668        // Delete the updated package
10669        outInfo.isRemovedPackageSystemUpdate = true;
10670        if (disabledPs.versionCode < newPs.versionCode) {
10671            // Delete data for downgrades
10672            flags &= ~PackageManager.DELETE_KEEP_DATA;
10673        } else {
10674            // Preserve data by setting flag
10675            flags |= PackageManager.DELETE_KEEP_DATA;
10676        }
10677        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10678                allUserHandles, perUserInstalled, outInfo, writeSettings);
10679        if (!ret) {
10680            return false;
10681        }
10682        // writer
10683        synchronized (mPackages) {
10684            // Reinstate the old system package
10685            mSettings.enableSystemPackageLPw(newPs.name);
10686            // Remove any native libraries from the upgraded package.
10687            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10688        }
10689        // Install the system package
10690        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10691        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10692        if (locationIsPrivileged(disabledPs.codePath)) {
10693            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10694        }
10695        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10696                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10697
10698        if (newPkg == null) {
10699            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10700                    + " with error:" + mLastScanError);
10701            return false;
10702        }
10703        // writer
10704        synchronized (mPackages) {
10705            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10706            setInternalAppNativeLibraryPath(newPkg, ps);
10707            updatePermissionsLPw(newPkg.packageName, newPkg,
10708                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10709            if (applyUserRestrictions) {
10710                if (DEBUG_REMOVE) {
10711                    Slog.d(TAG, "Propagating install state across reinstall");
10712                }
10713                for (int i = 0; i < allUserHandles.length; i++) {
10714                    if (DEBUG_REMOVE) {
10715                        Slog.d(TAG, "    user " + allUserHandles[i]
10716                                + " => " + perUserInstalled[i]);
10717                    }
10718                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10719                }
10720                // Regardless of writeSettings we need to ensure that this restriction
10721                // state propagation is persisted
10722                mSettings.writeAllUsersPackageRestrictionsLPr();
10723            }
10724            // can downgrade to reader here
10725            if (writeSettings) {
10726                mSettings.writeLPr();
10727            }
10728        }
10729        return true;
10730    }
10731
10732    private boolean deleteInstalledPackageLI(PackageSetting ps,
10733            boolean deleteCodeAndResources, int flags,
10734            int[] allUserHandles, boolean[] perUserInstalled,
10735            PackageRemovedInfo outInfo, boolean writeSettings) {
10736        if (outInfo != null) {
10737            outInfo.uid = ps.appId;
10738        }
10739
10740        // Delete package data from internal structures and also remove data if flag is set
10741        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10742
10743        // Delete application code and resources
10744        if (deleteCodeAndResources && (outInfo != null)) {
10745            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10746                    ps.resourcePathString, ps.nativeLibraryPathString,
10747                    getAppInstructionSetFromSettings(ps));
10748        }
10749        return true;
10750    }
10751
10752    /*
10753     * This method handles package deletion in general
10754     */
10755    private boolean deletePackageLI(String packageName, UserHandle user,
10756            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10757            int flags, PackageRemovedInfo outInfo,
10758            boolean writeSettings) {
10759        if (packageName == null) {
10760            Slog.w(TAG, "Attempt to delete null packageName.");
10761            return false;
10762        }
10763        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10764        PackageSetting ps;
10765        boolean dataOnly = false;
10766        int removeUser = -1;
10767        int appId = -1;
10768        synchronized (mPackages) {
10769            ps = mSettings.mPackages.get(packageName);
10770            if (ps == null) {
10771                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10772                return false;
10773            }
10774            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10775                    && user.getIdentifier() != UserHandle.USER_ALL) {
10776                // The caller is asking that the package only be deleted for a single
10777                // user.  To do this, we just mark its uninstalled state and delete
10778                // its data.  If this is a system app, we only allow this to happen if
10779                // they have set the special DELETE_SYSTEM_APP which requests different
10780                // semantics than normal for uninstalling system apps.
10781                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10782                ps.setUserState(user.getIdentifier(),
10783                        COMPONENT_ENABLED_STATE_DEFAULT,
10784                        false, //installed
10785                        true,  //stopped
10786                        true,  //notLaunched
10787                        false, //blocked
10788                        null, null, null);
10789                if (!isSystemApp(ps)) {
10790                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10791                        // Other user still have this package installed, so all
10792                        // we need to do is clear this user's data and save that
10793                        // it is uninstalled.
10794                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10795                        removeUser = user.getIdentifier();
10796                        appId = ps.appId;
10797                        mSettings.writePackageRestrictionsLPr(removeUser);
10798                    } else {
10799                        // We need to set it back to 'installed' so the uninstall
10800                        // broadcasts will be sent correctly.
10801                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10802                        ps.setInstalled(true, user.getIdentifier());
10803                    }
10804                } else {
10805                    // This is a system app, so we assume that the
10806                    // other users still have this package installed, so all
10807                    // we need to do is clear this user's data and save that
10808                    // it is uninstalled.
10809                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10810                    removeUser = user.getIdentifier();
10811                    appId = ps.appId;
10812                    mSettings.writePackageRestrictionsLPr(removeUser);
10813                }
10814            }
10815        }
10816
10817        if (removeUser >= 0) {
10818            // From above, we determined that we are deleting this only
10819            // for a single user.  Continue the work here.
10820            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10821            if (outInfo != null) {
10822                outInfo.removedPackage = packageName;
10823                outInfo.removedAppId = appId;
10824                outInfo.removedUsers = new int[] {removeUser};
10825            }
10826            mInstaller.clearUserData(packageName, removeUser);
10827            removeKeystoreDataIfNeeded(removeUser, appId);
10828            schedulePackageCleaning(packageName, removeUser, false);
10829            return true;
10830        }
10831
10832        if (dataOnly) {
10833            // Delete application data first
10834            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10835            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10836            return true;
10837        }
10838
10839        boolean ret = false;
10840        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10841        if (isSystemApp(ps)) {
10842            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10843            // When an updated system application is deleted we delete the existing resources as well and
10844            // fall back to existing code in system partition
10845            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10846                    flags, outInfo, writeSettings);
10847        } else {
10848            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10849            // Kill application pre-emptively especially for apps on sd.
10850            killApplication(packageName, ps.appId, "uninstall pkg");
10851            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10852                    allUserHandles, perUserInstalled,
10853                    outInfo, writeSettings);
10854        }
10855
10856        return ret;
10857    }
10858
10859    private final class ClearStorageConnection implements ServiceConnection {
10860        IMediaContainerService mContainerService;
10861
10862        @Override
10863        public void onServiceConnected(ComponentName name, IBinder service) {
10864            synchronized (this) {
10865                mContainerService = IMediaContainerService.Stub.asInterface(service);
10866                notifyAll();
10867            }
10868        }
10869
10870        @Override
10871        public void onServiceDisconnected(ComponentName name) {
10872        }
10873    }
10874
10875    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10876        final boolean mounted;
10877        if (Environment.isExternalStorageEmulated()) {
10878            mounted = true;
10879        } else {
10880            final String status = Environment.getExternalStorageState();
10881
10882            mounted = status.equals(Environment.MEDIA_MOUNTED)
10883                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10884        }
10885
10886        if (!mounted) {
10887            return;
10888        }
10889
10890        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10891        int[] users;
10892        if (userId == UserHandle.USER_ALL) {
10893            users = sUserManager.getUserIds();
10894        } else {
10895            users = new int[] { userId };
10896        }
10897        final ClearStorageConnection conn = new ClearStorageConnection();
10898        if (mContext.bindServiceAsUser(
10899                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10900            try {
10901                for (int curUser : users) {
10902                    long timeout = SystemClock.uptimeMillis() + 5000;
10903                    synchronized (conn) {
10904                        long now = SystemClock.uptimeMillis();
10905                        while (conn.mContainerService == null && now < timeout) {
10906                            try {
10907                                conn.wait(timeout - now);
10908                            } catch (InterruptedException e) {
10909                            }
10910                        }
10911                    }
10912                    if (conn.mContainerService == null) {
10913                        return;
10914                    }
10915
10916                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10917                    clearDirectory(conn.mContainerService,
10918                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10919                    if (allData) {
10920                        clearDirectory(conn.mContainerService,
10921                                userEnv.buildExternalStorageAppDataDirs(packageName));
10922                        clearDirectory(conn.mContainerService,
10923                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10924                    }
10925                }
10926            } finally {
10927                mContext.unbindService(conn);
10928            }
10929        }
10930    }
10931
10932    @Override
10933    public void clearApplicationUserData(final String packageName,
10934            final IPackageDataObserver observer, final int userId) {
10935        mContext.enforceCallingOrSelfPermission(
10936                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10938        // Queue up an async operation since the package deletion may take a little while.
10939        mHandler.post(new Runnable() {
10940            public void run() {
10941                mHandler.removeCallbacks(this);
10942                final boolean succeeded;
10943                synchronized (mInstallLock) {
10944                    succeeded = clearApplicationUserDataLI(packageName, userId);
10945                }
10946                clearExternalStorageDataSync(packageName, userId, true);
10947                if (succeeded) {
10948                    // invoke DeviceStorageMonitor's update method to clear any notifications
10949                    DeviceStorageMonitorInternal
10950                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10951                    if (dsm != null) {
10952                        dsm.checkMemory();
10953                    }
10954                }
10955                if(observer != null) {
10956                    try {
10957                        observer.onRemoveCompleted(packageName, succeeded);
10958                    } catch (RemoteException e) {
10959                        Log.i(TAG, "Observer no longer exists.");
10960                    }
10961                } //end if observer
10962            } //end run
10963        });
10964    }
10965
10966    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10967        if (packageName == null) {
10968            Slog.w(TAG, "Attempt to delete null packageName.");
10969            return false;
10970        }
10971        PackageParser.Package p;
10972        boolean dataOnly = false;
10973        final int appId;
10974        synchronized (mPackages) {
10975            p = mPackages.get(packageName);
10976            if (p == null) {
10977                dataOnly = true;
10978                PackageSetting ps = mSettings.mPackages.get(packageName);
10979                if ((ps == null) || (ps.pkg == null)) {
10980                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10981                    return false;
10982                }
10983                p = ps.pkg;
10984            }
10985            if (!dataOnly) {
10986                // need to check this only for fully installed applications
10987                if (p == null) {
10988                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10989                    return false;
10990                }
10991                final ApplicationInfo applicationInfo = p.applicationInfo;
10992                if (applicationInfo == null) {
10993                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10994                    return false;
10995                }
10996            }
10997            if (p != null && p.applicationInfo != null) {
10998                appId = p.applicationInfo.uid;
10999            } else {
11000                appId = -1;
11001            }
11002        }
11003        int retCode = mInstaller.clearUserData(packageName, userId);
11004        if (retCode < 0) {
11005            Slog.w(TAG, "Couldn't remove cache files for package: "
11006                    + packageName);
11007            return false;
11008        }
11009        removeKeystoreDataIfNeeded(userId, appId);
11010        return true;
11011    }
11012
11013    /**
11014     * Remove entries from the keystore daemon. Will only remove it if the
11015     * {@code appId} is valid.
11016     */
11017    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11018        if (appId < 0) {
11019            return;
11020        }
11021
11022        final KeyStore keyStore = KeyStore.getInstance();
11023        if (keyStore != null) {
11024            if (userId == UserHandle.USER_ALL) {
11025                for (final int individual : sUserManager.getUserIds()) {
11026                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11027                }
11028            } else {
11029                keyStore.clearUid(UserHandle.getUid(userId, appId));
11030            }
11031        } else {
11032            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11033        }
11034    }
11035
11036    @Override
11037    public void deleteApplicationCacheFiles(final String packageName,
11038            final IPackageDataObserver observer) {
11039        mContext.enforceCallingOrSelfPermission(
11040                android.Manifest.permission.DELETE_CACHE_FILES, null);
11041        // Queue up an async operation since the package deletion may take a little while.
11042        final int userId = UserHandle.getCallingUserId();
11043        mHandler.post(new Runnable() {
11044            public void run() {
11045                mHandler.removeCallbacks(this);
11046                final boolean succeded;
11047                synchronized (mInstallLock) {
11048                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11049                }
11050                clearExternalStorageDataSync(packageName, userId, false);
11051                if(observer != null) {
11052                    try {
11053                        observer.onRemoveCompleted(packageName, succeded);
11054                    } catch (RemoteException e) {
11055                        Log.i(TAG, "Observer no longer exists.");
11056                    }
11057                } //end if observer
11058            } //end run
11059        });
11060    }
11061
11062    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11063        if (packageName == null) {
11064            Slog.w(TAG, "Attempt to delete null packageName.");
11065            return false;
11066        }
11067        PackageParser.Package p;
11068        synchronized (mPackages) {
11069            p = mPackages.get(packageName);
11070        }
11071        if (p == null) {
11072            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11073            return false;
11074        }
11075        final ApplicationInfo applicationInfo = p.applicationInfo;
11076        if (applicationInfo == null) {
11077            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11078            return false;
11079        }
11080        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11081        if (retCode < 0) {
11082            Slog.w(TAG, "Couldn't remove cache files for package: "
11083                       + packageName + " u" + userId);
11084            return false;
11085        }
11086        return true;
11087    }
11088
11089    @Override
11090    public void getPackageSizeInfo(final String packageName, int userHandle,
11091            final IPackageStatsObserver observer) {
11092        mContext.enforceCallingOrSelfPermission(
11093                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11094        if (packageName == null) {
11095            throw new IllegalArgumentException("Attempt to get size of null packageName");
11096        }
11097
11098        PackageStats stats = new PackageStats(packageName, userHandle);
11099
11100        /*
11101         * Queue up an async operation since the package measurement may take a
11102         * little while.
11103         */
11104        Message msg = mHandler.obtainMessage(INIT_COPY);
11105        msg.obj = new MeasureParams(stats, observer);
11106        mHandler.sendMessage(msg);
11107    }
11108
11109    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11110            PackageStats pStats) {
11111        if (packageName == null) {
11112            Slog.w(TAG, "Attempt to get size of null packageName.");
11113            return false;
11114        }
11115        PackageParser.Package p;
11116        boolean dataOnly = false;
11117        String libDirPath = null;
11118        String asecPath = null;
11119        PackageSetting ps = null;
11120        synchronized (mPackages) {
11121            p = mPackages.get(packageName);
11122            ps = mSettings.mPackages.get(packageName);
11123            if(p == null) {
11124                dataOnly = true;
11125                if((ps == null) || (ps.pkg == null)) {
11126                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11127                    return false;
11128                }
11129                p = ps.pkg;
11130            }
11131            if (ps != null) {
11132                libDirPath = ps.nativeLibraryPathString;
11133            }
11134            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11135                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11136                if (secureContainerId != null) {
11137                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11138                }
11139            }
11140        }
11141        String publicSrcDir = null;
11142        if(!dataOnly) {
11143            final ApplicationInfo applicationInfo = p.applicationInfo;
11144            if (applicationInfo == null) {
11145                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11146                return false;
11147            }
11148            if (isForwardLocked(p)) {
11149                publicSrcDir = applicationInfo.publicSourceDir;
11150            }
11151        }
11152        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
11153                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11154                pStats);
11155        if (res < 0) {
11156            return false;
11157        }
11158
11159        // Fix-up for forward-locked applications in ASEC containers.
11160        if (!isExternal(p)) {
11161            pStats.codeSize += pStats.externalCodeSize;
11162            pStats.externalCodeSize = 0L;
11163        }
11164
11165        return true;
11166    }
11167
11168
11169    @Override
11170    public void addPackageToPreferred(String packageName) {
11171        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11172    }
11173
11174    @Override
11175    public void removePackageFromPreferred(String packageName) {
11176        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11177    }
11178
11179    @Override
11180    public List<PackageInfo> getPreferredPackages(int flags) {
11181        return new ArrayList<PackageInfo>();
11182    }
11183
11184    private int getUidTargetSdkVersionLockedLPr(int uid) {
11185        Object obj = mSettings.getUserIdLPr(uid);
11186        if (obj instanceof SharedUserSetting) {
11187            final SharedUserSetting sus = (SharedUserSetting) obj;
11188            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11189            final Iterator<PackageSetting> it = sus.packages.iterator();
11190            while (it.hasNext()) {
11191                final PackageSetting ps = it.next();
11192                if (ps.pkg != null) {
11193                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11194                    if (v < vers) vers = v;
11195                }
11196            }
11197            return vers;
11198        } else if (obj instanceof PackageSetting) {
11199            final PackageSetting ps = (PackageSetting) obj;
11200            if (ps.pkg != null) {
11201                return ps.pkg.applicationInfo.targetSdkVersion;
11202            }
11203        }
11204        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11205    }
11206
11207    @Override
11208    public void addPreferredActivity(IntentFilter filter, int match,
11209            ComponentName[] set, ComponentName activity, int userId) {
11210        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11211    }
11212
11213    private void addPreferredActivityInternal(IntentFilter filter, int match,
11214            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11215        // writer
11216        int callingUid = Binder.getCallingUid();
11217        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11218        if (filter.countActions() == 0) {
11219            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11220            return;
11221        }
11222        synchronized (mPackages) {
11223            if (mContext.checkCallingOrSelfPermission(
11224                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11225                    != PackageManager.PERMISSION_GRANTED) {
11226                if (getUidTargetSdkVersionLockedLPr(callingUid)
11227                        < Build.VERSION_CODES.FROYO) {
11228                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11229                            + callingUid);
11230                    return;
11231                }
11232                mContext.enforceCallingOrSelfPermission(
11233                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11234            }
11235
11236            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11237            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11238            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11239                    new PreferredActivity(filter, match, set, activity, always));
11240            mSettings.writePackageRestrictionsLPr(userId);
11241        }
11242    }
11243
11244    @Override
11245    public void replacePreferredActivity(IntentFilter filter, int match,
11246            ComponentName[] set, ComponentName activity) {
11247        if (filter.countActions() != 1) {
11248            throw new IllegalArgumentException(
11249                    "replacePreferredActivity expects filter to have only 1 action.");
11250        }
11251        if (filter.countDataAuthorities() != 0
11252                || filter.countDataPaths() != 0
11253                || filter.countDataSchemes() > 1
11254                || filter.countDataTypes() != 0) {
11255            throw new IllegalArgumentException(
11256                    "replacePreferredActivity expects filter to have no data authorities, " +
11257                    "paths, or types; and at most one scheme.");
11258        }
11259        synchronized (mPackages) {
11260            if (mContext.checkCallingOrSelfPermission(
11261                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11262                    != PackageManager.PERMISSION_GRANTED) {
11263                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11264                        < Build.VERSION_CODES.FROYO) {
11265                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11266                            + Binder.getCallingUid());
11267                    return;
11268                }
11269                mContext.enforceCallingOrSelfPermission(
11270                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11271            }
11272
11273            final int callingUserId = UserHandle.getCallingUserId();
11274            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11275            if (pir != null) {
11276                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11277                if (filter.countDataSchemes() == 1) {
11278                    Uri.Builder builder = new Uri.Builder();
11279                    builder.scheme(filter.getDataScheme(0));
11280                    intent.setData(builder.build());
11281                }
11282                List<PreferredActivity> matches = pir.queryIntent(
11283                        intent, null, true, callingUserId);
11284                if (DEBUG_PREFERRED) {
11285                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11286                }
11287                for (int i = 0; i < matches.size(); i++) {
11288                    PreferredActivity pa = matches.get(i);
11289                    if (DEBUG_PREFERRED) {
11290                        Slog.i(TAG, "Removing preferred activity "
11291                                + pa.mPref.mComponent + ":");
11292                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11293                    }
11294                    pir.removeFilter(pa);
11295                }
11296            }
11297            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11298        }
11299    }
11300
11301    @Override
11302    public void clearPackagePreferredActivities(String packageName) {
11303        final int uid = Binder.getCallingUid();
11304        // writer
11305        synchronized (mPackages) {
11306            PackageParser.Package pkg = mPackages.get(packageName);
11307            if (pkg == null || pkg.applicationInfo.uid != uid) {
11308                if (mContext.checkCallingOrSelfPermission(
11309                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11310                        != PackageManager.PERMISSION_GRANTED) {
11311                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11312                            < Build.VERSION_CODES.FROYO) {
11313                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11314                                + Binder.getCallingUid());
11315                        return;
11316                    }
11317                    mContext.enforceCallingOrSelfPermission(
11318                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11319                }
11320            }
11321
11322            int user = UserHandle.getCallingUserId();
11323            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11324                mSettings.writePackageRestrictionsLPr(user);
11325                scheduleWriteSettingsLocked();
11326            }
11327        }
11328    }
11329
11330    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11331    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11332        ArrayList<PreferredActivity> removed = null;
11333        boolean changed = false;
11334        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11335            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11336            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11337            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11338                continue;
11339            }
11340            Iterator<PreferredActivity> it = pir.filterIterator();
11341            while (it.hasNext()) {
11342                PreferredActivity pa = it.next();
11343                // Mark entry for removal only if it matches the package name
11344                // and the entry is of type "always".
11345                if (packageName == null ||
11346                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11347                                && pa.mPref.mAlways)) {
11348                    if (removed == null) {
11349                        removed = new ArrayList<PreferredActivity>();
11350                    }
11351                    removed.add(pa);
11352                }
11353            }
11354            if (removed != null) {
11355                for (int j=0; j<removed.size(); j++) {
11356                    PreferredActivity pa = removed.get(j);
11357                    pir.removeFilter(pa);
11358                }
11359                changed = true;
11360            }
11361        }
11362        return changed;
11363    }
11364
11365    @Override
11366    public void resetPreferredActivities(int userId) {
11367        mContext.enforceCallingOrSelfPermission(
11368                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11369        // writer
11370        synchronized (mPackages) {
11371            int user = UserHandle.getCallingUserId();
11372            clearPackagePreferredActivitiesLPw(null, user);
11373            mSettings.readDefaultPreferredAppsLPw(this, user);
11374            mSettings.writePackageRestrictionsLPr(user);
11375            scheduleWriteSettingsLocked();
11376        }
11377    }
11378
11379    @Override
11380    public int getPreferredActivities(List<IntentFilter> outFilters,
11381            List<ComponentName> outActivities, String packageName) {
11382
11383        int num = 0;
11384        final int userId = UserHandle.getCallingUserId();
11385        // reader
11386        synchronized (mPackages) {
11387            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11388            if (pir != null) {
11389                final Iterator<PreferredActivity> it = pir.filterIterator();
11390                while (it.hasNext()) {
11391                    final PreferredActivity pa = it.next();
11392                    if (packageName == null
11393                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11394                                    && pa.mPref.mAlways)) {
11395                        if (outFilters != null) {
11396                            outFilters.add(new IntentFilter(pa));
11397                        }
11398                        if (outActivities != null) {
11399                            outActivities.add(pa.mPref.mComponent);
11400                        }
11401                    }
11402                }
11403            }
11404        }
11405
11406        return num;
11407    }
11408
11409    @Override
11410    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11411            int userId) {
11412        int callingUid = Binder.getCallingUid();
11413        if (callingUid != Process.SYSTEM_UID) {
11414            throw new SecurityException(
11415                    "addPersistentPreferredActivity can only be run by the system");
11416        }
11417        if (filter.countActions() == 0) {
11418            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11419            return;
11420        }
11421        synchronized (mPackages) {
11422            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11423                    " :");
11424            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11425            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11426                    new PersistentPreferredActivity(filter, activity));
11427            mSettings.writePackageRestrictionsLPr(userId);
11428        }
11429    }
11430
11431    @Override
11432    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11433        int callingUid = Binder.getCallingUid();
11434        if (callingUid != Process.SYSTEM_UID) {
11435            throw new SecurityException(
11436                    "clearPackagePersistentPreferredActivities can only be run by the system");
11437        }
11438        ArrayList<PersistentPreferredActivity> removed = null;
11439        boolean changed = false;
11440        synchronized (mPackages) {
11441            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11442                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11443                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11444                        .valueAt(i);
11445                if (userId != thisUserId) {
11446                    continue;
11447                }
11448                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11449                while (it.hasNext()) {
11450                    PersistentPreferredActivity ppa = it.next();
11451                    // Mark entry for removal only if it matches the package name.
11452                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11453                        if (removed == null) {
11454                            removed = new ArrayList<PersistentPreferredActivity>();
11455                        }
11456                        removed.add(ppa);
11457                    }
11458                }
11459                if (removed != null) {
11460                    for (int j=0; j<removed.size(); j++) {
11461                        PersistentPreferredActivity ppa = removed.get(j);
11462                        ppir.removeFilter(ppa);
11463                    }
11464                    changed = true;
11465                }
11466            }
11467
11468            if (changed) {
11469                mSettings.writePackageRestrictionsLPr(userId);
11470            }
11471        }
11472    }
11473
11474    @Override
11475    public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig,
11476            int userIdDest) {
11477        mContext.enforceCallingOrSelfPermission(
11478                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11479        if (filter.countActions() == 0) {
11480            Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions");
11481            return;
11482        }
11483        synchronized (mPackages) {
11484            mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter(
11485                    new ForwardingIntentFilter(filter, removable, userIdDest));
11486            mSettings.writePackageRestrictionsLPr(userIdOrig);
11487        }
11488    }
11489
11490    @Override
11491    public void clearForwardingIntentFilters(int userIdOrig) {
11492        mContext.enforceCallingOrSelfPermission(
11493                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11494        synchronized (mPackages) {
11495            ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig);
11496            HashSet<ForwardingIntentFilter> set =
11497                    new HashSet<ForwardingIntentFilter>(fir.filterSet());
11498            for (ForwardingIntentFilter fif : set) {
11499                if (fif.isRemovable()) fir.removeFilter(fif);
11500            }
11501            mSettings.writePackageRestrictionsLPr(userIdOrig);
11502        }
11503    }
11504
11505    @Override
11506    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11507        Intent intent = new Intent(Intent.ACTION_MAIN);
11508        intent.addCategory(Intent.CATEGORY_HOME);
11509
11510        final int callingUserId = UserHandle.getCallingUserId();
11511        List<ResolveInfo> list = queryIntentActivities(intent, null,
11512                PackageManager.GET_META_DATA, callingUserId);
11513        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11514                true, false, false, callingUserId);
11515
11516        allHomeCandidates.clear();
11517        if (list != null) {
11518            for (ResolveInfo ri : list) {
11519                allHomeCandidates.add(ri);
11520            }
11521        }
11522        return (preferred == null || preferred.activityInfo == null)
11523                ? null
11524                : new ComponentName(preferred.activityInfo.packageName,
11525                        preferred.activityInfo.name);
11526    }
11527
11528    @Override
11529    public void setApplicationEnabledSetting(String appPackageName,
11530            int newState, int flags, int userId, String callingPackage) {
11531        if (!sUserManager.exists(userId)) return;
11532        if (callingPackage == null) {
11533            callingPackage = Integer.toString(Binder.getCallingUid());
11534        }
11535        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11536    }
11537
11538    @Override
11539    public void setComponentEnabledSetting(ComponentName componentName,
11540            int newState, int flags, int userId) {
11541        if (!sUserManager.exists(userId)) return;
11542        setEnabledSetting(componentName.getPackageName(),
11543                componentName.getClassName(), newState, flags, userId, null);
11544    }
11545
11546    private void setEnabledSetting(final String packageName, String className, int newState,
11547            final int flags, int userId, String callingPackage) {
11548        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11549              || newState == COMPONENT_ENABLED_STATE_ENABLED
11550              || newState == COMPONENT_ENABLED_STATE_DISABLED
11551              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11552              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11553            throw new IllegalArgumentException("Invalid new component state: "
11554                    + newState);
11555        }
11556        PackageSetting pkgSetting;
11557        final int uid = Binder.getCallingUid();
11558        final int permission = mContext.checkCallingOrSelfPermission(
11559                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11560        enforceCrossUserPermission(uid, userId, false, "set enabled");
11561        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11562        boolean sendNow = false;
11563        boolean isApp = (className == null);
11564        String componentName = isApp ? packageName : className;
11565        int packageUid = -1;
11566        ArrayList<String> components;
11567
11568        // writer
11569        synchronized (mPackages) {
11570            pkgSetting = mSettings.mPackages.get(packageName);
11571            if (pkgSetting == null) {
11572                if (className == null) {
11573                    throw new IllegalArgumentException(
11574                            "Unknown package: " + packageName);
11575                }
11576                throw new IllegalArgumentException(
11577                        "Unknown component: " + packageName
11578                        + "/" + className);
11579            }
11580            // Allow root and verify that userId is not being specified by a different user
11581            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11582                throw new SecurityException(
11583                        "Permission Denial: attempt to change component state from pid="
11584                        + Binder.getCallingPid()
11585                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11586            }
11587            if (className == null) {
11588                // We're dealing with an application/package level state change
11589                if (pkgSetting.getEnabled(userId) == newState) {
11590                    // Nothing to do
11591                    return;
11592                }
11593                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11594                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11595                    // Don't care about who enables an app.
11596                    callingPackage = null;
11597                }
11598                pkgSetting.setEnabled(newState, userId, callingPackage);
11599                // pkgSetting.pkg.mSetEnabled = newState;
11600            } else {
11601                // We're dealing with a component level state change
11602                // First, verify that this is a valid class name.
11603                PackageParser.Package pkg = pkgSetting.pkg;
11604                if (pkg == null || !pkg.hasComponentClassName(className)) {
11605                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11606                        throw new IllegalArgumentException("Component class " + className
11607                                + " does not exist in " + packageName);
11608                    } else {
11609                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11610                                + className + " does not exist in " + packageName);
11611                    }
11612                }
11613                switch (newState) {
11614                case COMPONENT_ENABLED_STATE_ENABLED:
11615                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11616                        return;
11617                    }
11618                    break;
11619                case COMPONENT_ENABLED_STATE_DISABLED:
11620                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11621                        return;
11622                    }
11623                    break;
11624                case COMPONENT_ENABLED_STATE_DEFAULT:
11625                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11626                        return;
11627                    }
11628                    break;
11629                default:
11630                    Slog.e(TAG, "Invalid new component state: " + newState);
11631                    return;
11632                }
11633            }
11634            mSettings.writePackageRestrictionsLPr(userId);
11635            components = mPendingBroadcasts.get(userId, packageName);
11636            final boolean newPackage = components == null;
11637            if (newPackage) {
11638                components = new ArrayList<String>();
11639            }
11640            if (!components.contains(componentName)) {
11641                components.add(componentName);
11642            }
11643            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11644                sendNow = true;
11645                // Purge entry from pending broadcast list if another one exists already
11646                // since we are sending one right away.
11647                mPendingBroadcasts.remove(userId, packageName);
11648            } else {
11649                if (newPackage) {
11650                    mPendingBroadcasts.put(userId, packageName, components);
11651                }
11652                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11653                    // Schedule a message
11654                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11655                }
11656            }
11657        }
11658
11659        long callingId = Binder.clearCallingIdentity();
11660        try {
11661            if (sendNow) {
11662                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11663                sendPackageChangedBroadcast(packageName,
11664                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11665            }
11666        } finally {
11667            Binder.restoreCallingIdentity(callingId);
11668        }
11669    }
11670
11671    private void sendPackageChangedBroadcast(String packageName,
11672            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11673        if (DEBUG_INSTALL)
11674            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11675                    + componentNames);
11676        Bundle extras = new Bundle(4);
11677        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11678        String nameList[] = new String[componentNames.size()];
11679        componentNames.toArray(nameList);
11680        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11681        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11682        extras.putInt(Intent.EXTRA_UID, packageUid);
11683        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11684                new int[] {UserHandle.getUserId(packageUid)});
11685    }
11686
11687    @Override
11688    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11689        if (!sUserManager.exists(userId)) return;
11690        final int uid = Binder.getCallingUid();
11691        final int permission = mContext.checkCallingOrSelfPermission(
11692                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11693        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11694        enforceCrossUserPermission(uid, userId, true, "stop package");
11695        // writer
11696        synchronized (mPackages) {
11697            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11698                    uid, userId)) {
11699                scheduleWritePackageRestrictionsLocked(userId);
11700            }
11701        }
11702    }
11703
11704    @Override
11705    public String getInstallerPackageName(String packageName) {
11706        // reader
11707        synchronized (mPackages) {
11708            return mSettings.getInstallerPackageNameLPr(packageName);
11709        }
11710    }
11711
11712    @Override
11713    public int getApplicationEnabledSetting(String packageName, int userId) {
11714        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11715        int uid = Binder.getCallingUid();
11716        enforceCrossUserPermission(uid, userId, false, "get enabled");
11717        // reader
11718        synchronized (mPackages) {
11719            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11720        }
11721    }
11722
11723    @Override
11724    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11725        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11726        int uid = Binder.getCallingUid();
11727        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11728        // reader
11729        synchronized (mPackages) {
11730            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11731        }
11732    }
11733
11734    @Override
11735    public void enterSafeMode() {
11736        enforceSystemOrRoot("Only the system can request entering safe mode");
11737
11738        if (!mSystemReady) {
11739            mSafeMode = true;
11740        }
11741    }
11742
11743    @Override
11744    public void systemReady() {
11745        mSystemReady = true;
11746
11747        // Read the compatibilty setting when the system is ready.
11748        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11749                mContext.getContentResolver(),
11750                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11751        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11752        if (DEBUG_SETTINGS) {
11753            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11754        }
11755
11756        synchronized (mPackages) {
11757            // Verify that all of the preferred activity components actually
11758            // exist.  It is possible for applications to be updated and at
11759            // that point remove a previously declared activity component that
11760            // had been set as a preferred activity.  We try to clean this up
11761            // the next time we encounter that preferred activity, but it is
11762            // possible for the user flow to never be able to return to that
11763            // situation so here we do a sanity check to make sure we haven't
11764            // left any junk around.
11765            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11766            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11767                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11768                removed.clear();
11769                for (PreferredActivity pa : pir.filterSet()) {
11770                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11771                        removed.add(pa);
11772                    }
11773                }
11774                if (removed.size() > 0) {
11775                    for (int r=0; r<removed.size(); r++) {
11776                        PreferredActivity pa = removed.get(r);
11777                        Slog.w(TAG, "Removing dangling preferred activity: "
11778                                + pa.mPref.mComponent);
11779                        pir.removeFilter(pa);
11780                    }
11781                    mSettings.writePackageRestrictionsLPr(
11782                            mSettings.mPreferredActivities.keyAt(i));
11783                }
11784            }
11785        }
11786        sUserManager.systemReady();
11787    }
11788
11789    @Override
11790    public boolean isSafeMode() {
11791        return mSafeMode;
11792    }
11793
11794    @Override
11795    public boolean hasSystemUidErrors() {
11796        return mHasSystemUidErrors;
11797    }
11798
11799    static String arrayToString(int[] array) {
11800        StringBuffer buf = new StringBuffer(128);
11801        buf.append('[');
11802        if (array != null) {
11803            for (int i=0; i<array.length; i++) {
11804                if (i > 0) buf.append(", ");
11805                buf.append(array[i]);
11806            }
11807        }
11808        buf.append(']');
11809        return buf.toString();
11810    }
11811
11812    static class DumpState {
11813        public static final int DUMP_LIBS = 1 << 0;
11814
11815        public static final int DUMP_FEATURES = 1 << 1;
11816
11817        public static final int DUMP_RESOLVERS = 1 << 2;
11818
11819        public static final int DUMP_PERMISSIONS = 1 << 3;
11820
11821        public static final int DUMP_PACKAGES = 1 << 4;
11822
11823        public static final int DUMP_SHARED_USERS = 1 << 5;
11824
11825        public static final int DUMP_MESSAGES = 1 << 6;
11826
11827        public static final int DUMP_PROVIDERS = 1 << 7;
11828
11829        public static final int DUMP_VERIFIERS = 1 << 8;
11830
11831        public static final int DUMP_PREFERRED = 1 << 9;
11832
11833        public static final int DUMP_PREFERRED_XML = 1 << 10;
11834
11835        public static final int DUMP_KEYSETS = 1 << 11;
11836
11837        public static final int DUMP_VERSION = 1 << 12;
11838
11839        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11840
11841        private int mTypes;
11842
11843        private int mOptions;
11844
11845        private boolean mTitlePrinted;
11846
11847        private SharedUserSetting mSharedUser;
11848
11849        public boolean isDumping(int type) {
11850            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11851                return true;
11852            }
11853
11854            return (mTypes & type) != 0;
11855        }
11856
11857        public void setDump(int type) {
11858            mTypes |= type;
11859        }
11860
11861        public boolean isOptionEnabled(int option) {
11862            return (mOptions & option) != 0;
11863        }
11864
11865        public void setOptionEnabled(int option) {
11866            mOptions |= option;
11867        }
11868
11869        public boolean onTitlePrinted() {
11870            final boolean printed = mTitlePrinted;
11871            mTitlePrinted = true;
11872            return printed;
11873        }
11874
11875        public boolean getTitlePrinted() {
11876            return mTitlePrinted;
11877        }
11878
11879        public void setTitlePrinted(boolean enabled) {
11880            mTitlePrinted = enabled;
11881        }
11882
11883        public SharedUserSetting getSharedUser() {
11884            return mSharedUser;
11885        }
11886
11887        public void setSharedUser(SharedUserSetting user) {
11888            mSharedUser = user;
11889        }
11890    }
11891
11892    @Override
11893    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11894        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11895                != PackageManager.PERMISSION_GRANTED) {
11896            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11897                    + Binder.getCallingPid()
11898                    + ", uid=" + Binder.getCallingUid()
11899                    + " without permission "
11900                    + android.Manifest.permission.DUMP);
11901            return;
11902        }
11903
11904        DumpState dumpState = new DumpState();
11905        boolean fullPreferred = false;
11906        boolean checkin = false;
11907
11908        String packageName = null;
11909
11910        int opti = 0;
11911        while (opti < args.length) {
11912            String opt = args[opti];
11913            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11914                break;
11915            }
11916            opti++;
11917            if ("-a".equals(opt)) {
11918                // Right now we only know how to print all.
11919            } else if ("-h".equals(opt)) {
11920                pw.println("Package manager dump options:");
11921                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11922                pw.println("    --checkin: dump for a checkin");
11923                pw.println("    -f: print details of intent filters");
11924                pw.println("    -h: print this help");
11925                pw.println("  cmd may be one of:");
11926                pw.println("    l[ibraries]: list known shared libraries");
11927                pw.println("    f[ibraries]: list device features");
11928                pw.println("    k[eysets]: print known keysets");
11929                pw.println("    r[esolvers]: dump intent resolvers");
11930                pw.println("    perm[issions]: dump permissions");
11931                pw.println("    pref[erred]: print preferred package settings");
11932                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11933                pw.println("    prov[iders]: dump content providers");
11934                pw.println("    p[ackages]: dump installed packages");
11935                pw.println("    s[hared-users]: dump shared user IDs");
11936                pw.println("    m[essages]: print collected runtime messages");
11937                pw.println("    v[erifiers]: print package verifier info");
11938                pw.println("    version: print database version info");
11939                pw.println("    write: write current settings now");
11940                pw.println("    <package.name>: info about given package");
11941                return;
11942            } else if ("--checkin".equals(opt)) {
11943                checkin = true;
11944            } else if ("-f".equals(opt)) {
11945                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11946            } else {
11947                pw.println("Unknown argument: " + opt + "; use -h for help");
11948            }
11949        }
11950
11951        // Is the caller requesting to dump a particular piece of data?
11952        if (opti < args.length) {
11953            String cmd = args[opti];
11954            opti++;
11955            // Is this a package name?
11956            if ("android".equals(cmd) || cmd.contains(".")) {
11957                packageName = cmd;
11958                // When dumping a single package, we always dump all of its
11959                // filter information since the amount of data will be reasonable.
11960                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11961            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11962                dumpState.setDump(DumpState.DUMP_LIBS);
11963            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11964                dumpState.setDump(DumpState.DUMP_FEATURES);
11965            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11966                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11967            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11968                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11969            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11970                dumpState.setDump(DumpState.DUMP_PREFERRED);
11971            } else if ("preferred-xml".equals(cmd)) {
11972                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11973                if (opti < args.length && "--full".equals(args[opti])) {
11974                    fullPreferred = true;
11975                    opti++;
11976                }
11977            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11978                dumpState.setDump(DumpState.DUMP_PACKAGES);
11979            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11980                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11981            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11982                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11983            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11984                dumpState.setDump(DumpState.DUMP_MESSAGES);
11985            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11986                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11987            } else if ("version".equals(cmd)) {
11988                dumpState.setDump(DumpState.DUMP_VERSION);
11989            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11990                dumpState.setDump(DumpState.DUMP_KEYSETS);
11991            } else if ("write".equals(cmd)) {
11992                synchronized (mPackages) {
11993                    mSettings.writeLPr();
11994                    pw.println("Settings written.");
11995                    return;
11996                }
11997            }
11998        }
11999
12000        if (checkin) {
12001            pw.println("vers,1");
12002        }
12003
12004        // reader
12005        synchronized (mPackages) {
12006            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12007                if (!checkin) {
12008                    if (dumpState.onTitlePrinted())
12009                        pw.println();
12010                    pw.println("Database versions:");
12011                    pw.print("  SDK Version:");
12012                    pw.print(" internal=");
12013                    pw.print(mSettings.mInternalSdkPlatform);
12014                    pw.print(" external=");
12015                    pw.println(mSettings.mExternalSdkPlatform);
12016                    pw.print("  DB Version:");
12017                    pw.print(" internal=");
12018                    pw.print(mSettings.mInternalDatabaseVersion);
12019                    pw.print(" external=");
12020                    pw.println(mSettings.mExternalDatabaseVersion);
12021                }
12022            }
12023
12024            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12025                if (!checkin) {
12026                    if (dumpState.onTitlePrinted())
12027                        pw.println();
12028                    pw.println("Verifiers:");
12029                    pw.print("  Required: ");
12030                    pw.print(mRequiredVerifierPackage);
12031                    pw.print(" (uid=");
12032                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12033                    pw.println(")");
12034                } else if (mRequiredVerifierPackage != null) {
12035                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12036                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12037                }
12038            }
12039
12040            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12041                boolean printedHeader = false;
12042                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12043                while (it.hasNext()) {
12044                    String name = it.next();
12045                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12046                    if (!checkin) {
12047                        if (!printedHeader) {
12048                            if (dumpState.onTitlePrinted())
12049                                pw.println();
12050                            pw.println("Libraries:");
12051                            printedHeader = true;
12052                        }
12053                        pw.print("  ");
12054                    } else {
12055                        pw.print("lib,");
12056                    }
12057                    pw.print(name);
12058                    if (!checkin) {
12059                        pw.print(" -> ");
12060                    }
12061                    if (ent.path != null) {
12062                        if (!checkin) {
12063                            pw.print("(jar) ");
12064                            pw.print(ent.path);
12065                        } else {
12066                            pw.print(",jar,");
12067                            pw.print(ent.path);
12068                        }
12069                    } else {
12070                        if (!checkin) {
12071                            pw.print("(apk) ");
12072                            pw.print(ent.apk);
12073                        } else {
12074                            pw.print(",apk,");
12075                            pw.print(ent.apk);
12076                        }
12077                    }
12078                    pw.println();
12079                }
12080            }
12081
12082            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12083                if (dumpState.onTitlePrinted())
12084                    pw.println();
12085                if (!checkin) {
12086                    pw.println("Features:");
12087                }
12088                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12089                while (it.hasNext()) {
12090                    String name = it.next();
12091                    if (!checkin) {
12092                        pw.print("  ");
12093                    } else {
12094                        pw.print("feat,");
12095                    }
12096                    pw.println(name);
12097                }
12098            }
12099
12100            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12101                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12102                        : "Activity Resolver Table:", "  ", packageName,
12103                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12104                    dumpState.setTitlePrinted(true);
12105                }
12106                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12107                        : "Receiver Resolver Table:", "  ", packageName,
12108                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12109                    dumpState.setTitlePrinted(true);
12110                }
12111                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12112                        : "Service Resolver Table:", "  ", packageName,
12113                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12114                    dumpState.setTitlePrinted(true);
12115                }
12116                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12117                        : "Provider Resolver Table:", "  ", packageName,
12118                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12119                    dumpState.setTitlePrinted(true);
12120                }
12121            }
12122
12123            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12124                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12125                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12126                    int user = mSettings.mPreferredActivities.keyAt(i);
12127                    if (pir.dump(pw,
12128                            dumpState.getTitlePrinted()
12129                                ? "\nPreferred Activities User " + user + ":"
12130                                : "Preferred Activities User " + user + ":", "  ",
12131                            packageName, true)) {
12132                        dumpState.setTitlePrinted(true);
12133                    }
12134                }
12135            }
12136
12137            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12138                pw.flush();
12139                FileOutputStream fout = new FileOutputStream(fd);
12140                BufferedOutputStream str = new BufferedOutputStream(fout);
12141                XmlSerializer serializer = new FastXmlSerializer();
12142                try {
12143                    serializer.setOutput(str, "utf-8");
12144                    serializer.startDocument(null, true);
12145                    serializer.setFeature(
12146                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12147                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12148                    serializer.endDocument();
12149                    serializer.flush();
12150                } catch (IllegalArgumentException e) {
12151                    pw.println("Failed writing: " + e);
12152                } catch (IllegalStateException e) {
12153                    pw.println("Failed writing: " + e);
12154                } catch (IOException e) {
12155                    pw.println("Failed writing: " + e);
12156                }
12157            }
12158
12159            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12160                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12161            }
12162
12163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12164                boolean printedSomething = false;
12165                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12166                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12167                        continue;
12168                    }
12169                    if (!printedSomething) {
12170                        if (dumpState.onTitlePrinted())
12171                            pw.println();
12172                        pw.println("Registered ContentProviders:");
12173                        printedSomething = true;
12174                    }
12175                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12176                    pw.print("    "); pw.println(p.toString());
12177                }
12178                printedSomething = false;
12179                for (Map.Entry<String, PackageParser.Provider> entry :
12180                        mProvidersByAuthority.entrySet()) {
12181                    PackageParser.Provider p = entry.getValue();
12182                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12183                        continue;
12184                    }
12185                    if (!printedSomething) {
12186                        if (dumpState.onTitlePrinted())
12187                            pw.println();
12188                        pw.println("ContentProvider Authorities:");
12189                        printedSomething = true;
12190                    }
12191                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12192                    pw.print("    "); pw.println(p.toString());
12193                    if (p.info != null && p.info.applicationInfo != null) {
12194                        final String appInfo = p.info.applicationInfo.toString();
12195                        pw.print("      applicationInfo="); pw.println(appInfo);
12196                    }
12197                }
12198            }
12199
12200            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12201                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12202            }
12203
12204            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12205                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12206            }
12207
12208            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12209                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12210            }
12211
12212            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12213                if (dumpState.onTitlePrinted())
12214                    pw.println();
12215                mSettings.dumpReadMessagesLPr(pw, dumpState);
12216
12217                pw.println();
12218                pw.println("Package warning messages:");
12219                final File fname = getSettingsProblemFile();
12220                FileInputStream in = null;
12221                try {
12222                    in = new FileInputStream(fname);
12223                    final int avail = in.available();
12224                    final byte[] data = new byte[avail];
12225                    in.read(data);
12226                    pw.print(new String(data));
12227                } catch (FileNotFoundException e) {
12228                } catch (IOException e) {
12229                } finally {
12230                    if (in != null) {
12231                        try {
12232                            in.close();
12233                        } catch (IOException e) {
12234                        }
12235                    }
12236                }
12237            }
12238        }
12239    }
12240
12241    // ------- apps on sdcard specific code -------
12242    static final boolean DEBUG_SD_INSTALL = false;
12243
12244    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12245
12246    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12247
12248    private boolean mMediaMounted = false;
12249
12250    private String getEncryptKey() {
12251        try {
12252            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12253                    SD_ENCRYPTION_KEYSTORE_NAME);
12254            if (sdEncKey == null) {
12255                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12256                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12257                if (sdEncKey == null) {
12258                    Slog.e(TAG, "Failed to create encryption keys");
12259                    return null;
12260                }
12261            }
12262            return sdEncKey;
12263        } catch (NoSuchAlgorithmException nsae) {
12264            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12265            return null;
12266        } catch (IOException ioe) {
12267            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12268            return null;
12269        }
12270
12271    }
12272
12273    /* package */static String getTempContainerId() {
12274        int tmpIdx = 1;
12275        String list[] = PackageHelper.getSecureContainerList();
12276        if (list != null) {
12277            for (final String name : list) {
12278                // Ignore null and non-temporary container entries
12279                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12280                    continue;
12281                }
12282
12283                String subStr = name.substring(mTempContainerPrefix.length());
12284                try {
12285                    int cid = Integer.parseInt(subStr);
12286                    if (cid >= tmpIdx) {
12287                        tmpIdx = cid + 1;
12288                    }
12289                } catch (NumberFormatException e) {
12290                }
12291            }
12292        }
12293        return mTempContainerPrefix + tmpIdx;
12294    }
12295
12296    /*
12297     * Update media status on PackageManager.
12298     */
12299    @Override
12300    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12301        int callingUid = Binder.getCallingUid();
12302        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12303            throw new SecurityException("Media status can only be updated by the system");
12304        }
12305        // reader; this apparently protects mMediaMounted, but should probably
12306        // be a different lock in that case.
12307        synchronized (mPackages) {
12308            Log.i(TAG, "Updating external media status from "
12309                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12310                    + (mediaStatus ? "mounted" : "unmounted"));
12311            if (DEBUG_SD_INSTALL)
12312                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12313                        + ", mMediaMounted=" + mMediaMounted);
12314            if (mediaStatus == mMediaMounted) {
12315                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12316                        : 0, -1);
12317                mHandler.sendMessage(msg);
12318                return;
12319            }
12320            mMediaMounted = mediaStatus;
12321        }
12322        // Queue up an async operation since the package installation may take a
12323        // little while.
12324        mHandler.post(new Runnable() {
12325            public void run() {
12326                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12327            }
12328        });
12329    }
12330
12331    /**
12332     * Called by MountService when the initial ASECs to scan are available.
12333     * Should block until all the ASEC containers are finished being scanned.
12334     */
12335    public void scanAvailableAsecs() {
12336        updateExternalMediaStatusInner(true, false, false);
12337        if (mShouldRestoreconData) {
12338            SELinuxMMAC.setRestoreconDone();
12339            mShouldRestoreconData = false;
12340        }
12341    }
12342
12343    /*
12344     * Collect information of applications on external media, map them against
12345     * existing containers and update information based on current mount status.
12346     * Please note that we always have to report status if reportStatus has been
12347     * set to true especially when unloading packages.
12348     */
12349    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12350            boolean externalStorage) {
12351        // Collection of uids
12352        int uidArr[] = null;
12353        // Collection of stale containers
12354        HashSet<String> removeCids = new HashSet<String>();
12355        // Collection of packages on external media with valid containers.
12356        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12357        // Get list of secure containers.
12358        final String list[] = PackageHelper.getSecureContainerList();
12359        if (list == null || list.length == 0) {
12360            Log.i(TAG, "No secure containers on sdcard");
12361        } else {
12362            // Process list of secure containers and categorize them
12363            // as active or stale based on their package internal state.
12364            int uidList[] = new int[list.length];
12365            int num = 0;
12366            // reader
12367            synchronized (mPackages) {
12368                for (String cid : list) {
12369                    if (DEBUG_SD_INSTALL)
12370                        Log.i(TAG, "Processing container " + cid);
12371                    String pkgName = getAsecPackageName(cid);
12372                    if (pkgName == null) {
12373                        if (DEBUG_SD_INSTALL)
12374                            Log.i(TAG, "Container : " + cid + " stale");
12375                        removeCids.add(cid);
12376                        continue;
12377                    }
12378                    if (DEBUG_SD_INSTALL)
12379                        Log.i(TAG, "Looking for pkg : " + pkgName);
12380
12381                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12382                    if (ps == null) {
12383                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12384                        removeCids.add(cid);
12385                        continue;
12386                    }
12387
12388                    /*
12389                     * Skip packages that are not external if we're unmounting
12390                     * external storage.
12391                     */
12392                    if (externalStorage && !isMounted && !isExternal(ps)) {
12393                        continue;
12394                    }
12395
12396                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12397                            getAppInstructionSetFromSettings(ps),
12398                            isForwardLocked(ps));
12399                    // The package status is changed only if the code path
12400                    // matches between settings and the container id.
12401                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12402                        if (DEBUG_SD_INSTALL) {
12403                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12404                                    + " at code path: " + ps.codePathString);
12405                        }
12406
12407                        // We do have a valid package installed on sdcard
12408                        processCids.put(args, ps.codePathString);
12409                        final int uid = ps.appId;
12410                        if (uid != -1) {
12411                            uidList[num++] = uid;
12412                        }
12413                    } else {
12414                        Log.i(TAG, "Deleting stale container for " + cid);
12415                        removeCids.add(cid);
12416                    }
12417                }
12418            }
12419
12420            if (num > 0) {
12421                // Sort uid list
12422                Arrays.sort(uidList, 0, num);
12423                // Throw away duplicates
12424                uidArr = new int[num];
12425                uidArr[0] = uidList[0];
12426                int di = 0;
12427                for (int i = 1; i < num; i++) {
12428                    if (uidList[i - 1] != uidList[i]) {
12429                        uidArr[di++] = uidList[i];
12430                    }
12431                }
12432            }
12433        }
12434        // Process packages with valid entries.
12435        if (isMounted) {
12436            if (DEBUG_SD_INSTALL)
12437                Log.i(TAG, "Loading packages");
12438            loadMediaPackages(processCids, uidArr, removeCids);
12439            startCleaningPackages();
12440        } else {
12441            if (DEBUG_SD_INSTALL)
12442                Log.i(TAG, "Unloading packages");
12443            unloadMediaPackages(processCids, uidArr, reportStatus);
12444        }
12445    }
12446
12447   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12448           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12449        int size = pkgList.size();
12450        if (size > 0) {
12451            // Send broadcasts here
12452            Bundle extras = new Bundle();
12453            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12454                    .toArray(new String[size]));
12455            if (uidArr != null) {
12456                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12457            }
12458            if (replacing) {
12459                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12460            }
12461            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12462                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12463            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12464        }
12465    }
12466
12467   /*
12468     * Look at potentially valid container ids from processCids If package
12469     * information doesn't match the one on record or package scanning fails,
12470     * the cid is added to list of removeCids. We currently don't delete stale
12471     * containers.
12472     */
12473   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12474            HashSet<String> removeCids) {
12475        ArrayList<String> pkgList = new ArrayList<String>();
12476        Set<AsecInstallArgs> keys = processCids.keySet();
12477        boolean doGc = false;
12478        for (AsecInstallArgs args : keys) {
12479            String codePath = processCids.get(args);
12480            if (DEBUG_SD_INSTALL)
12481                Log.i(TAG, "Loading container : " + args.cid);
12482            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12483            try {
12484                // Make sure there are no container errors first.
12485                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12486                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12487                            + " when installing from sdcard");
12488                    continue;
12489                }
12490                // Check code path here.
12491                if (codePath == null || !codePath.equals(args.getCodePath())) {
12492                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12493                            + " does not match one in settings " + codePath);
12494                    continue;
12495                }
12496                // Parse package
12497                int parseFlags = mDefParseFlags;
12498                if (args.isExternal()) {
12499                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12500                }
12501                if (args.isFwdLocked()) {
12502                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12503                }
12504
12505                doGc = true;
12506                synchronized (mInstallLock) {
12507                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12508                            0, 0, null);
12509                    // Scan the package
12510                    if (pkg != null) {
12511                        /*
12512                         * TODO why is the lock being held? doPostInstall is
12513                         * called in other places without the lock. This needs
12514                         * to be straightened out.
12515                         */
12516                        // writer
12517                        synchronized (mPackages) {
12518                            retCode = PackageManager.INSTALL_SUCCEEDED;
12519                            pkgList.add(pkg.packageName);
12520                            // Post process args
12521                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12522                                    pkg.applicationInfo.uid);
12523                        }
12524                    } else {
12525                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12526                    }
12527                }
12528
12529            } finally {
12530                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12531                    // Don't destroy container here. Wait till gc clears things
12532                    // up.
12533                    removeCids.add(args.cid);
12534                }
12535            }
12536        }
12537        // writer
12538        synchronized (mPackages) {
12539            // If the platform SDK has changed since the last time we booted,
12540            // we need to re-grant app permission to catch any new ones that
12541            // appear. This is really a hack, and means that apps can in some
12542            // cases get permissions that the user didn't initially explicitly
12543            // allow... it would be nice to have some better way to handle
12544            // this situation.
12545            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12546            if (regrantPermissions)
12547                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12548                        + mSdkVersion + "; regranting permissions for external storage");
12549            mSettings.mExternalSdkPlatform = mSdkVersion;
12550
12551            // Make sure group IDs have been assigned, and any permission
12552            // changes in other apps are accounted for
12553            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12554                    | (regrantPermissions
12555                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12556                            : 0));
12557
12558            mSettings.updateExternalDatabaseVersion();
12559
12560            // can downgrade to reader
12561            // Persist settings
12562            mSettings.writeLPr();
12563        }
12564        // Send a broadcast to let everyone know we are done processing
12565        if (pkgList.size() > 0) {
12566            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12567        }
12568        // Force gc to avoid any stale parser references that we might have.
12569        if (doGc) {
12570            Runtime.getRuntime().gc();
12571        }
12572        // List stale containers and destroy stale temporary containers.
12573        if (removeCids != null) {
12574            for (String cid : removeCids) {
12575                if (cid.startsWith(mTempContainerPrefix)) {
12576                    Log.i(TAG, "Destroying stale temporary container " + cid);
12577                    PackageHelper.destroySdDir(cid);
12578                } else {
12579                    Log.w(TAG, "Container " + cid + " is stale");
12580               }
12581           }
12582        }
12583    }
12584
12585   /*
12586     * Utility method to unload a list of specified containers
12587     */
12588    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12589        // Just unmount all valid containers.
12590        for (AsecInstallArgs arg : cidArgs) {
12591            synchronized (mInstallLock) {
12592                arg.doPostDeleteLI(false);
12593           }
12594       }
12595   }
12596
12597    /*
12598     * Unload packages mounted on external media. This involves deleting package
12599     * data from internal structures, sending broadcasts about diabled packages,
12600     * gc'ing to free up references, unmounting all secure containers
12601     * corresponding to packages on external media, and posting a
12602     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12603     * that we always have to post this message if status has been requested no
12604     * matter what.
12605     */
12606    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12607            final boolean reportStatus) {
12608        if (DEBUG_SD_INSTALL)
12609            Log.i(TAG, "unloading media packages");
12610        ArrayList<String> pkgList = new ArrayList<String>();
12611        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12612        final Set<AsecInstallArgs> keys = processCids.keySet();
12613        for (AsecInstallArgs args : keys) {
12614            String pkgName = args.getPackageName();
12615            if (DEBUG_SD_INSTALL)
12616                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12617            // Delete package internally
12618            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12619            synchronized (mInstallLock) {
12620                boolean res = deletePackageLI(pkgName, null, false, null, null,
12621                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12622                if (res) {
12623                    pkgList.add(pkgName);
12624                } else {
12625                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12626                    failedList.add(args);
12627                }
12628            }
12629        }
12630
12631        // reader
12632        synchronized (mPackages) {
12633            // We didn't update the settings after removing each package;
12634            // write them now for all packages.
12635            mSettings.writeLPr();
12636        }
12637
12638        // We have to absolutely send UPDATED_MEDIA_STATUS only
12639        // after confirming that all the receivers processed the ordered
12640        // broadcast when packages get disabled, force a gc to clean things up.
12641        // and unload all the containers.
12642        if (pkgList.size() > 0) {
12643            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12644                    new IIntentReceiver.Stub() {
12645                public void performReceive(Intent intent, int resultCode, String data,
12646                        Bundle extras, boolean ordered, boolean sticky,
12647                        int sendingUser) throws RemoteException {
12648                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12649                            reportStatus ? 1 : 0, 1, keys);
12650                    mHandler.sendMessage(msg);
12651                }
12652            });
12653        } else {
12654            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12655                    keys);
12656            mHandler.sendMessage(msg);
12657        }
12658    }
12659
12660    /** Binder call */
12661    @Override
12662    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12663            final int flags) {
12664        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12665        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12666        int returnCode = PackageManager.MOVE_SUCCEEDED;
12667        int currFlags = 0;
12668        int newFlags = 0;
12669        // reader
12670        synchronized (mPackages) {
12671            PackageParser.Package pkg = mPackages.get(packageName);
12672            if (pkg == null) {
12673                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12674            } else {
12675                // Disable moving fwd locked apps and system packages
12676                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12677                    Slog.w(TAG, "Cannot move system application");
12678                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12679                } else if (pkg.mOperationPending) {
12680                    Slog.w(TAG, "Attempt to move package which has pending operations");
12681                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12682                } else {
12683                    // Find install location first
12684                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12685                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12686                        Slog.w(TAG, "Ambigous flags specified for move location.");
12687                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12688                    } else {
12689                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12690                                : PackageManager.INSTALL_INTERNAL;
12691                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12692                                : PackageManager.INSTALL_INTERNAL;
12693
12694                        if (newFlags == currFlags) {
12695                            Slog.w(TAG, "No move required. Trying to move to same location");
12696                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12697                        } else {
12698                            if (isForwardLocked(pkg)) {
12699                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12700                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12701                            }
12702                        }
12703                    }
12704                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12705                        pkg.mOperationPending = true;
12706                    }
12707                }
12708            }
12709
12710            /*
12711             * TODO this next block probably shouldn't be inside the lock. We
12712             * can't guarantee these won't change after this is fired off
12713             * anyway.
12714             */
12715            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12716                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12717                        null, -1, user),
12718                        returnCode);
12719            } else {
12720                Message msg = mHandler.obtainMessage(INIT_COPY);
12721                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12722                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12723                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12724                        instructionSet);
12725                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12726                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12727                msg.obj = mp;
12728                mHandler.sendMessage(msg);
12729            }
12730        }
12731    }
12732
12733    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12734        // Queue up an async operation since the package deletion may take a
12735        // little while.
12736        mHandler.post(new Runnable() {
12737            public void run() {
12738                // TODO fix this; this does nothing.
12739                mHandler.removeCallbacks(this);
12740                int returnCode = currentStatus;
12741                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12742                    int uidArr[] = null;
12743                    ArrayList<String> pkgList = null;
12744                    synchronized (mPackages) {
12745                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12746                        if (pkg == null) {
12747                            Slog.w(TAG, " Package " + mp.packageName
12748                                    + " doesn't exist. Aborting move");
12749                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12750                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12751                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12752                                    + mp.srcArgs.getCodePath() + " to "
12753                                    + pkg.applicationInfo.sourceDir
12754                                    + " Aborting move and returning error");
12755                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12756                        } else {
12757                            uidArr = new int[] {
12758                                pkg.applicationInfo.uid
12759                            };
12760                            pkgList = new ArrayList<String>();
12761                            pkgList.add(mp.packageName);
12762                        }
12763                    }
12764                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12765                        // Send resources unavailable broadcast
12766                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12767                        // Update package code and resource paths
12768                        synchronized (mInstallLock) {
12769                            synchronized (mPackages) {
12770                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12771                                // Recheck for package again.
12772                                if (pkg == null) {
12773                                    Slog.w(TAG, " Package " + mp.packageName
12774                                            + " doesn't exist. Aborting move");
12775                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12776                                } else if (!mp.srcArgs.getCodePath().equals(
12777                                        pkg.applicationInfo.sourceDir)) {
12778                                    Slog.w(TAG, "Package " + mp.packageName
12779                                            + " code path changed from " + mp.srcArgs.getCodePath()
12780                                            + " to " + pkg.applicationInfo.sourceDir
12781                                            + " Aborting move and returning error");
12782                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12783                                } else {
12784                                    final String oldCodePath = pkg.mPath;
12785                                    final String newCodePath = mp.targetArgs.getCodePath();
12786                                    final String newResPath = mp.targetArgs.getResourcePath();
12787                                    final String newNativePath = mp.targetArgs
12788                                            .getNativeLibraryPath();
12789
12790                                    final File newNativeDir = new File(newNativePath);
12791
12792                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12793                                        // NOTE: We do not report any errors from the APK scan and library
12794                                        // copy at this point.
12795                                        NativeLibraryHelper.ApkHandle handle =
12796                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12797                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12798                                                handle, Build.SUPPORTED_ABIS);
12799                                        if (abi >= 0) {
12800                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12801                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12802                                        }
12803                                        handle.close();
12804                                    }
12805                                    final int[] users = sUserManager.getUserIds();
12806                                    for (int user : users) {
12807                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12808                                                newNativePath, user) < 0) {
12809                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12810                                        }
12811                                    }
12812
12813                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12814                                        pkg.mPath = newCodePath;
12815                                        // Move dex files around
12816                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12817                                            // Moving of dex files failed. Set
12818                                            // error code and abort move.
12819                                            pkg.mPath = pkg.mScanPath;
12820                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12821                                        }
12822                                    }
12823
12824                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12825                                        pkg.mScanPath = newCodePath;
12826                                        pkg.applicationInfo.sourceDir = newCodePath;
12827                                        pkg.applicationInfo.publicSourceDir = newResPath;
12828                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12829                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12830                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12831                                        ps.codePathString = ps.codePath.getPath();
12832                                        ps.resourcePath = new File(
12833                                                pkg.applicationInfo.publicSourceDir);
12834                                        ps.resourcePathString = ps.resourcePath.getPath();
12835                                        ps.nativeLibraryPathString = newNativePath;
12836                                        // Set the application info flag
12837                                        // correctly.
12838                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12839                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12840                                        } else {
12841                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12842                                        }
12843                                        ps.setFlags(pkg.applicationInfo.flags);
12844                                        mAppDirs.remove(oldCodePath);
12845                                        mAppDirs.put(newCodePath, pkg);
12846                                        // Persist settings
12847                                        mSettings.writeLPr();
12848                                    }
12849                                }
12850                            }
12851                        }
12852                        // Send resources available broadcast
12853                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12854                    }
12855                }
12856                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12857                    // Clean up failed installation
12858                    if (mp.targetArgs != null) {
12859                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12860                                -1);
12861                    }
12862                } else {
12863                    // Force a gc to clear things up.
12864                    Runtime.getRuntime().gc();
12865                    // Delete older code
12866                    synchronized (mInstallLock) {
12867                        mp.srcArgs.doPostDeleteLI(true);
12868                    }
12869                }
12870
12871                // Allow more operations on this file if we didn't fail because
12872                // an operation was already pending for this package.
12873                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12874                    synchronized (mPackages) {
12875                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12876                        if (pkg != null) {
12877                            pkg.mOperationPending = false;
12878                       }
12879                   }
12880                }
12881
12882                IPackageMoveObserver observer = mp.observer;
12883                if (observer != null) {
12884                    try {
12885                        observer.packageMoved(mp.packageName, returnCode);
12886                    } catch (RemoteException e) {
12887                        Log.i(TAG, "Observer no longer exists.");
12888                    }
12889                }
12890            }
12891        });
12892    }
12893
12894    @Override
12895    public boolean setInstallLocation(int loc) {
12896        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12897                null);
12898        if (getInstallLocation() == loc) {
12899            return true;
12900        }
12901        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12902                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12903            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12904                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12905            return true;
12906        }
12907        return false;
12908   }
12909
12910    @Override
12911    public int getInstallLocation() {
12912        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12913                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12914                PackageHelper.APP_INSTALL_AUTO);
12915    }
12916
12917    /** Called by UserManagerService */
12918    void cleanUpUserLILPw(int userHandle) {
12919        mDirtyUsers.remove(userHandle);
12920        mSettings.removeUserLPr(userHandle);
12921        mPendingBroadcasts.remove(userHandle);
12922        if (mInstaller != null) {
12923            // Technically, we shouldn't be doing this with the package lock
12924            // held.  However, this is very rare, and there is already so much
12925            // other disk I/O going on, that we'll let it slide for now.
12926            mInstaller.removeUserDataDirs(userHandle);
12927        }
12928    }
12929
12930    /** Called by UserManagerService */
12931    void createNewUserLILPw(int userHandle, File path) {
12932        if (mInstaller != null) {
12933            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12934        }
12935    }
12936
12937    @Override
12938    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12939        mContext.enforceCallingOrSelfPermission(
12940                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12941                "Only package verification agents can read the verifier device identity");
12942
12943        synchronized (mPackages) {
12944            return mSettings.getVerifierDeviceIdentityLPw();
12945        }
12946    }
12947
12948    @Override
12949    public void setPermissionEnforced(String permission, boolean enforced) {
12950        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12951        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12952            synchronized (mPackages) {
12953                if (mSettings.mReadExternalStorageEnforced == null
12954                        || mSettings.mReadExternalStorageEnforced != enforced) {
12955                    mSettings.mReadExternalStorageEnforced = enforced;
12956                    mSettings.writeLPr();
12957                }
12958            }
12959            // kill any non-foreground processes so we restart them and
12960            // grant/revoke the GID.
12961            final IActivityManager am = ActivityManagerNative.getDefault();
12962            if (am != null) {
12963                final long token = Binder.clearCallingIdentity();
12964                try {
12965                    am.killProcessesBelowForeground("setPermissionEnforcement");
12966                } catch (RemoteException e) {
12967                } finally {
12968                    Binder.restoreCallingIdentity(token);
12969                }
12970            }
12971        } else {
12972            throw new IllegalArgumentException("No selective enforcement for " + permission);
12973        }
12974    }
12975
12976    @Override
12977    @Deprecated
12978    public boolean isPermissionEnforced(String permission) {
12979        return true;
12980    }
12981
12982    @Override
12983    public boolean isStorageLow() {
12984        final long token = Binder.clearCallingIdentity();
12985        try {
12986            final DeviceStorageMonitorInternal
12987                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12988            if (dsm != null) {
12989                return dsm.isMemoryLow();
12990            } else {
12991                return false;
12992            }
12993        } finally {
12994            Binder.restoreCallingIdentity(token);
12995        }
12996    }
12997
12998    @Override
12999    public IPackageInstaller getPackageInstaller() {
13000        return mInstallerService;
13001    }
13002}
13003