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