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