PackageManagerService.java revision a29e43a364dc8dbe7e97184b535fe3f5d587d7ed
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.NativeLibraryHelper.ApkHandle;
44import com.android.internal.content.PackageHelper;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastPrintWriter;
47import com.android.internal.util.FastXmlSerializer;
48import com.android.internal.util.XmlUtils;
49import com.android.server.EventLogTags;
50import com.android.server.IntentResolver;
51import com.android.server.LocalServices;
52import com.android.server.ServiceThread;
53import com.android.server.Watchdog;
54import com.android.server.pm.Settings.DatabaseVersion;
55import com.android.server.storage.DeviceStorageMonitorInternal;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
61import android.app.ActivityManager;
62import android.app.ActivityManagerNative;
63import android.app.IActivityManager;
64import android.app.PackageInstallObserver;
65import android.app.admin.IDevicePolicyManager;
66import android.app.backup.IBackupManager;
67import android.content.BroadcastReceiver;
68import android.content.ComponentName;
69import android.content.Context;
70import android.content.IIntentReceiver;
71import android.content.Intent;
72import android.content.IntentFilter;
73import android.content.IntentSender;
74import android.content.IntentSender.SendIntentException;
75import android.content.ServiceConnection;
76import android.content.pm.ActivityInfo;
77import android.content.pm.ApplicationInfo;
78import android.content.pm.ContainerEncryptionParams;
79import android.content.pm.FeatureInfo;
80import android.content.pm.IPackageDataObserver;
81import android.content.pm.IPackageDeleteObserver;
82import android.content.pm.IPackageInstallObserver;
83import android.content.pm.IPackageInstallObserver2;
84import android.content.pm.IPackageInstaller;
85import android.content.pm.IPackageManager;
86import android.content.pm.IPackageMoveObserver;
87import android.content.pm.IPackageStatsObserver;
88import android.content.pm.InstrumentationInfo;
89import android.content.pm.ManifestDigest;
90import android.content.pm.PackageCleanItem;
91import android.content.pm.PackageInfo;
92import android.content.pm.PackageInfoLite;
93import android.content.pm.PackageManager;
94import android.content.pm.PackageParser.ActivityIntentInfo;
95import android.content.pm.PackageParser.PackageParserException;
96import android.content.pm.PackageParser;
97import android.content.pm.PackageStats;
98import android.content.pm.PackageUserState;
99import android.content.pm.ParceledListSlice;
100import android.content.pm.PermissionGroupInfo;
101import android.content.pm.PermissionInfo;
102import android.content.pm.ProviderInfo;
103import android.content.pm.ResolveInfo;
104import android.content.pm.ServiceInfo;
105import android.content.pm.Signature;
106import android.content.pm.VerificationParams;
107import android.content.pm.VerifierDeviceIdentity;
108import android.content.pm.VerifierInfo;
109import android.content.res.Resources;
110import android.hardware.display.DisplayManager;
111import android.net.Uri;
112import android.os.Binder;
113import android.os.Build;
114import android.os.Bundle;
115import android.os.Environment;
116import android.os.Environment.UserEnvironment;
117import android.os.FileObserver;
118import android.os.FileUtils;
119import android.os.Handler;
120import android.os.IBinder;
121import android.os.Looper;
122import android.os.Message;
123import android.os.Parcel;
124import android.os.ParcelFileDescriptor;
125import android.os.Process;
126import android.os.RemoteException;
127import android.os.SELinux;
128import android.os.ServiceManager;
129import android.os.SystemClock;
130import android.os.SystemProperties;
131import android.os.UserHandle;
132import android.os.UserManager;
133import android.security.KeyStore;
134import android.security.SystemKeyStore;
135import android.system.ErrnoException;
136import android.system.Os;
137import android.system.StructStat;
138import android.text.TextUtils;
139import android.util.ArraySet;
140import android.util.AtomicFile;
141import android.util.DisplayMetrics;
142import android.util.EventLog;
143import android.util.Log;
144import android.util.LogPrinter;
145import android.util.PrintStreamPrinter;
146import android.util.Slog;
147import android.util.SparseArray;
148import android.util.SparseBooleanArray;
149import android.util.Xml;
150import android.view.Display;
151
152import java.io.BufferedInputStream;
153import java.io.BufferedOutputStream;
154import java.io.File;
155import java.io.FileDescriptor;
156import java.io.FileInputStream;
157import java.io.FileNotFoundException;
158import java.io.FileOutputStream;
159import java.io.FileReader;
160import java.io.FilenameFilter;
161import java.io.IOException;
162import java.io.InputStream;
163import java.io.PrintWriter;
164import java.nio.charset.StandardCharsets;
165import java.security.NoSuchAlgorithmException;
166import java.security.PublicKey;
167import java.security.cert.CertificateEncodingException;
168import java.security.cert.CertificateException;
169import java.text.SimpleDateFormat;
170import java.util.ArrayList;
171import java.util.Arrays;
172import java.util.Collection;
173import java.util.Collections;
174import java.util.Comparator;
175import java.util.Date;
176import java.util.HashMap;
177import java.util.HashSet;
178import java.util.Iterator;
179import java.util.List;
180import java.util.Map;
181import java.util.Set;
182import java.util.concurrent.atomic.AtomicBoolean;
183import java.util.concurrent.atomic.AtomicLong;
184
185import dalvik.system.DexFile;
186import dalvik.system.StaleDexCacheError;
187import dalvik.system.VMRuntime;
188
189import libcore.io.IoUtils;
190
191/**
192 * Keep track of all those .apks everywhere.
193 *
194 * This is very central to the platform's security; please run the unit
195 * tests whenever making modifications here:
196 *
197mmm frameworks/base/tests/AndroidTests
198adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
199adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
200 *
201 * {@hide}
202 */
203public class PackageManagerService extends IPackageManager.Stub {
204    static final String TAG = "PackageManager";
205    static final boolean DEBUG_SETTINGS = false;
206    static final boolean DEBUG_PREFERRED = false;
207    static final boolean DEBUG_UPGRADE = false;
208    private static final boolean DEBUG_INSTALL = false;
209    private static final boolean DEBUG_REMOVE = false;
210    private static final boolean DEBUG_BROADCASTS = false;
211    private static final boolean DEBUG_SHOW_INFO = false;
212    private static final boolean DEBUG_PACKAGE_INFO = false;
213    private static final boolean DEBUG_INTENT_MATCHING = false;
214    private static final boolean DEBUG_PACKAGE_SCANNING = false;
215    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
216    private static final boolean DEBUG_VERIFY = false;
217    private static final boolean DEBUG_DEXOPT = false;
218
219    private static final int RADIO_UID = Process.PHONE_UID;
220    private static final int LOG_UID = Process.LOG_UID;
221    private static final int NFC_UID = Process.NFC_UID;
222    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
223    private static final int SHELL_UID = Process.SHELL_UID;
224
225    // Cap the size of permission trees that 3rd party apps can define
226    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
227
228    private static final int REMOVE_EVENTS =
229        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
230    private static final int ADD_EVENTS =
231        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
232
233    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
234    // Suffix used during package installation when copying/moving
235    // package apks to install directory.
236    private static final String INSTALL_PACKAGE_SUFFIX = "-";
237
238    static final int SCAN_MONITOR = 1<<0;
239    static final int SCAN_NO_DEX = 1<<1;
240    static final int SCAN_FORCE_DEX = 1<<2;
241    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
242    static final int SCAN_NEW_INSTALL = 1<<4;
243    static final int SCAN_NO_PATHS = 1<<5;
244    static final int SCAN_UPDATE_TIME = 1<<6;
245    static final int SCAN_DEFER_DEX = 1<<7;
246    static final int SCAN_BOOTING = 1<<8;
247    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
248    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
249
250    static final int REMOVE_CHATTY = 1<<16;
251
252    /**
253     * Timeout (in milliseconds) after which the watchdog should declare that
254     * our handler thread is wedged.  The usual default for such things is one
255     * minute but we sometimes do very lengthy I/O operations on this thread,
256     * such as installing multi-gigabyte applications, so ours needs to be longer.
257     */
258    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
259
260    /**
261     * Whether verification is enabled by default.
262     */
263    private static final boolean DEFAULT_VERIFY_ENABLE = true;
264
265    /**
266     * The default maximum time to wait for the verification agent to return in
267     * milliseconds.
268     */
269    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
270
271    /**
272     * The default response for package verification timeout.
273     *
274     * This can be either PackageManager.VERIFICATION_ALLOW or
275     * PackageManager.VERIFICATION_REJECT.
276     */
277    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
278
279    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
280
281    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
282            DEFAULT_CONTAINER_PACKAGE,
283            "com.android.defcontainer.DefaultContainerService");
284
285    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
286
287    private static final String LIB_DIR_NAME = "lib";
288    private static final String LIB64_DIR_NAME = "lib64";
289
290    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
291
292    static final String mTempContainerPrefix = "smdl2tmp";
293
294    private static String sPreferredInstructionSet;
295
296    final ServiceThread mHandlerThread;
297
298    private static final String IDMAP_PREFIX = "/data/resource-cache/";
299    private static final String IDMAP_SUFFIX = "@idmap";
300
301    final PackageHandler mHandler;
302
303    final int mSdkVersion = Build.VERSION.SDK_INT;
304
305    final Context mContext;
306    final boolean mFactoryTest;
307    final boolean mOnlyCore;
308    final DisplayMetrics mMetrics;
309    final int mDefParseFlags;
310    final String[] mSeparateProcesses;
311
312    // This is where all application persistent data goes.
313    final File mAppDataDir;
314
315    // This is where all application persistent data goes for secondary users.
316    final File mUserAppDataDir;
317
318    /** The location for ASEC container files on internal storage. */
319    final String mAsecInternalPath;
320
321    // This is the object monitoring the framework dir.
322    final FileObserver mFrameworkInstallObserver;
323
324    // This is the object monitoring the system app dir.
325    final FileObserver mSystemInstallObserver;
326
327    // This is the object monitoring the privileged system app dir.
328    final FileObserver mPrivilegedInstallObserver;
329
330    // This is the object monitoring the vendor app dir.
331    final FileObserver mVendorInstallObserver;
332
333    // This is the object monitoring the vendor overlay package dir.
334    final FileObserver mVendorOverlayInstallObserver;
335
336    // This is the object monitoring the OEM app dir.
337    final FileObserver mOemInstallObserver;
338
339    // This is the object monitoring mAppInstallDir.
340    final FileObserver mAppInstallObserver;
341
342    // This is the object monitoring mDrmAppPrivateInstallDir.
343    final FileObserver mDrmAppInstallObserver;
344
345    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
346    // LOCK HELD.  Can be called with mInstallLock held.
347    final Installer mInstaller;
348
349    final File mAppInstallDir;
350
351    /**
352     * Directory to which applications installed internally have native
353     * libraries copied.
354     */
355    private File mAppLibInstallDir;
356
357    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
358    // apps.
359    final File mDrmAppPrivateInstallDir;
360
361    final File mAppStagingDir;
362
363    // ----------------------------------------------------------------
364
365    // Lock for state used when installing and doing other long running
366    // operations.  Methods that must be called with this lock held have
367    // the suffix "LI".
368    final Object mInstallLock = new Object();
369
370    // These are the directories in the 3rd party applications installed dir
371    // that we have currently loaded packages from.  Keys are the application's
372    // installed zip file (absolute codePath), and values are Package.
373    final HashMap<String, PackageParser.Package> mAppDirs =
374            new HashMap<String, PackageParser.Package>();
375
376    // Information for the parser to write more useful error messages.
377    int mLastScanError;
378
379    // ----------------------------------------------------------------
380
381    // Keys are String (package name), values are Package.  This also serves
382    // as the lock for the global state.  Methods that must be called with
383    // this lock held have the prefix "LP".
384    final HashMap<String, PackageParser.Package> mPackages =
385            new HashMap<String, PackageParser.Package>();
386
387    // Tracks available target package names -> overlay package paths.
388    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
389        new HashMap<String, HashMap<String, PackageParser.Package>>();
390
391    final Settings mSettings;
392    boolean mRestoredSettings;
393
394    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
395    int[] mGlobalGids;
396
397    // These are the built-in uid -> permission mappings that were read from the
398    // etc/permissions.xml file.
399    final SparseArray<HashSet<String>> mSystemPermissions =
400            new SparseArray<HashSet<String>>();
401
402    static final class SharedLibraryEntry {
403        final String path;
404        final String apk;
405
406        SharedLibraryEntry(String _path, String _apk) {
407            path = _path;
408            apk = _apk;
409        }
410    }
411
412    // These are the built-in shared libraries that were read from the
413    // etc/permissions.xml file.
414    final HashMap<String, SharedLibraryEntry> mSharedLibraries
415            = new HashMap<String, SharedLibraryEntry>();
416
417    // These are the features this devices supports that were read from the
418    // etc/permissions.xml file.
419    final HashMap<String, FeatureInfo> mAvailableFeatures =
420            new HashMap<String, FeatureInfo>();
421
422    // If mac_permissions.xml was found for seinfo labeling.
423    boolean mFoundPolicyFile;
424
425    // If a recursive restorecon of /data/data/<pkg> is needed.
426    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
427
428    // All available activities, for your resolving pleasure.
429    final ActivityIntentResolver mActivities =
430            new ActivityIntentResolver();
431
432    // All available receivers, for your resolving pleasure.
433    final ActivityIntentResolver mReceivers =
434            new ActivityIntentResolver();
435
436    // All available services, for your resolving pleasure.
437    final ServiceIntentResolver mServices = new ServiceIntentResolver();
438
439    // All available providers, for your resolving pleasure.
440    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
441
442    // Mapping from provider base names (first directory in content URI codePath)
443    // to the provider information.
444    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
445            new HashMap<String, PackageParser.Provider>();
446
447    // Mapping from instrumentation class names to info about them.
448    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
449            new HashMap<ComponentName, PackageParser.Instrumentation>();
450
451    // Mapping from permission names to info about them.
452    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
453            new HashMap<String, PackageParser.PermissionGroup>();
454
455    // Packages whose data we have transfered into another package, thus
456    // should no longer exist.
457    final HashSet<String> mTransferedPackages = new HashSet<String>();
458
459    // Broadcast actions that are only available to the system.
460    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
461
462    /** List of packages waiting for verification. */
463    final SparseArray<PackageVerificationState> mPendingVerification
464            = new SparseArray<PackageVerificationState>();
465
466    final PackageInstallerService mInstallerService;
467
468    HashSet<PackageParser.Package> mDeferredDexOpt = null;
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    boolean mSystemReady;
474    boolean mSafeMode;
475    boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new HashMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsFirstBoot = false;
625
626        boolean isFirstBoot() {
627            return mIsFirstBoot;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsFirstBoot = true;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                args.observer.packageInstalled(res.name, res.returnCode);
1081                            } catch (RemoteException e) {
1082                                Slog.i(TAG, "Observer no longer exists.");
1083                            }
1084                        }
1085                        if (args.observer2 != null) {
1086                            try {
1087                                Bundle extras = extrasForInstallResult(res);
1088                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1089                            } catch (RemoteException e) {
1090                                Slog.i(TAG, "Observer no longer exists.");
1091                            }
1092                        }
1093                    } else {
1094                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1095                    }
1096                } break;
1097                case UPDATED_MEDIA_STATUS: {
1098                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1099                    boolean reportStatus = msg.arg1 == 1;
1100                    boolean doGc = msg.arg2 == 1;
1101                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1102                    if (doGc) {
1103                        // Force a gc to clear up stale containers.
1104                        Runtime.getRuntime().gc();
1105                    }
1106                    if (msg.obj != null) {
1107                        @SuppressWarnings("unchecked")
1108                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1109                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1110                        // Unload containers
1111                        unloadAllContainers(args);
1112                    }
1113                    if (reportStatus) {
1114                        try {
1115                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1116                            PackageHelper.getMountService().finishMediaUpdate();
1117                        } catch (RemoteException e) {
1118                            Log.e(TAG, "MountService not running?");
1119                        }
1120                    }
1121                } break;
1122                case WRITE_SETTINGS: {
1123                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124                    synchronized (mPackages) {
1125                        removeMessages(WRITE_SETTINGS);
1126                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1127                        mSettings.writeLPr();
1128                        mDirtyUsers.clear();
1129                    }
1130                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131                } break;
1132                case WRITE_PACKAGE_RESTRICTIONS: {
1133                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134                    synchronized (mPackages) {
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        for (int userId : mDirtyUsers) {
1137                            mSettings.writePackageRestrictionsLPr(userId);
1138                        }
1139                        mDirtyUsers.clear();
1140                    }
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142                } break;
1143                case CHECK_PENDING_VERIFICATION: {
1144                    final int verificationId = msg.arg1;
1145                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1146
1147                    if ((state != null) && !state.timeoutExtended()) {
1148                        final InstallArgs args = state.getInstallArgs();
1149                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of "
1156                                    + args.packageURI.toString());
1157                            state.setVerifierResponse(Binder.getCallingUid(),
1158                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1159                            broadcastPackageVerified(verificationId, args.packageURI,
1160                                    PackageManager.VERIFICATION_ALLOW,
1161                                    state.getInstallArgs().getUser());
1162                            try {
1163                                ret = args.copyApk(mContainerService, true);
1164                            } catch (RemoteException e) {
1165                                Slog.e(TAG, "Could not contact the ContainerService");
1166                            }
1167                        } else {
1168                            broadcastPackageVerified(verificationId, args.packageURI,
1169                                    PackageManager.VERIFICATION_REJECT,
1170                                    state.getInstallArgs().getUser());
1171                        }
1172
1173                        processPendingInstall(args, ret);
1174                        mHandler.sendEmptyMessage(MCS_UNBIND);
1175                    }
1176                    break;
1177                }
1178                case PACKAGE_VERIFIED: {
1179                    final int verificationId = msg.arg1;
1180
1181                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1182                    if (state == null) {
1183                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1184                        break;
1185                    }
1186
1187                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1188
1189                    state.setVerifierResponse(response.callerUid, response.code);
1190
1191                    if (state.isVerificationComplete()) {
1192                        mPendingVerification.remove(verificationId);
1193
1194                        final InstallArgs args = state.getInstallArgs();
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, args.packageURI,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final PackageManagerService main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mMetrics = new DisplayMetrics();
1299        mSettings = new Settings(context);
1300        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1301                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1302        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1303                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1304        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1305                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312
1313        String separateProcesses = SystemProperties.get("debug.separate_processes");
1314        if (separateProcesses != null && separateProcesses.length() > 0) {
1315            if ("*".equals(separateProcesses)) {
1316                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1317                mSeparateProcesses = null;
1318                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1319            } else {
1320                mDefParseFlags = 0;
1321                mSeparateProcesses = separateProcesses.split(",");
1322                Slog.w(TAG, "Running with debug.separate_processes: "
1323                        + separateProcesses);
1324            }
1325        } else {
1326            mDefParseFlags = 0;
1327            mSeparateProcesses = null;
1328        }
1329
1330        mInstaller = installer;
1331
1332        getDefaultDisplayMetrics(context, mMetrics);
1333
1334        synchronized (mInstallLock) {
1335        // writer
1336        synchronized (mPackages) {
1337            mHandlerThread = new ServiceThread(TAG,
1338                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1339            mHandlerThread.start();
1340            mHandler = new PackageHandler(mHandlerThread.getLooper());
1341            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1342
1343            File dataDir = Environment.getDataDirectory();
1344            mAppDataDir = new File(dataDir, "data");
1345            mAppInstallDir = new File(dataDir, "app");
1346            mAppLibInstallDir = new File(dataDir, "app-lib");
1347            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1348            mUserAppDataDir = new File(dataDir, "user");
1349            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1350            mAppStagingDir = new File(dataDir, "app-staging");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Read permissions and features from system
1356            readPermissions(Environment.buildPath(
1357                    Environment.getRootDirectory(), "etc", "permissions"), false);
1358            // Only read features from OEM
1359            readPermissions(Environment.buildPath(
1360                    Environment.getOemDirectory(), "etc", "permissions"), true);
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            String bootClassPath = System.getProperty("java.boot.class.path");
1393            if (bootClassPath != null) {
1394                String[] paths = splitString(bootClassPath, ':');
1395                for (int i=0; i<paths.length; i++) {
1396                    alreadyDexOpted.add(paths[i]);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            boolean didDexOptLibraryOrTool = false;
1403
1404            final List<String> instructionSets = getAllInstructionSets();
1405
1406            /**
1407             * Ensure all external libraries have had dexopt run on them.
1408             */
1409            if (mSharedLibraries.size() > 0) {
1410                // NOTE: For now, we're compiling these system "shared libraries"
1411                // (and framework jars) into all available architectures. It's possible
1412                // to compile them only when we come across an app that uses them (there's
1413                // already logic for that in scanPackageLI) but that adds some complexity.
1414                for (String instructionSet : instructionSets) {
1415                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1416                        final String lib = libEntry.path;
1417                        if (lib == null) {
1418                            continue;
1419                        }
1420
1421                        try {
1422                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1423                                alreadyDexOpted.add(lib);
1424
1425                                // The list of "shared libraries" we have at this point is
1426                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1427                                didDexOptLibraryOrTool = true;
1428                            }
1429                        } catch (FileNotFoundException e) {
1430                            Slog.w(TAG, "Library not found: " + lib);
1431                        } catch (IOException e) {
1432                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1433                                    + e.getMessage());
1434                        }
1435                    }
1436                }
1437            }
1438
1439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1440
1441            // Gross hack for now: we know this file doesn't contain any
1442            // code, so don't dexopt it to avoid the resulting log spew.
1443            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1444
1445            // Gross hack for now: we know this file is only part of
1446            // the boot class path for art, so don't dexopt it to
1447            // avoid the resulting log spew.
1448            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1449
1450            /**
1451             * And there are a number of commands implemented in Java, which
1452             * we currently need to do the dexopt on so that they can be
1453             * run from a non-root shell.
1454             */
1455            String[] frameworkFiles = frameworkDir.list();
1456            if (frameworkFiles != null) {
1457                // TODO: We could compile these only for the most preferred ABI. We should
1458                // first double check that the dex files for these commands are not referenced
1459                // by other system apps.
1460                for (String instructionSet : instructionSets) {
1461                    for (int i=0; i<frameworkFiles.length; i++) {
1462                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1463                        String path = libPath.getPath();
1464                        // Skip the file if we already did it.
1465                        if (alreadyDexOpted.contains(path)) {
1466                            continue;
1467                        }
1468                        // Skip the file if it is not a type we want to dexopt.
1469                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1470                            continue;
1471                        }
1472                        try {
1473                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1474                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1475                                didDexOptLibraryOrTool = true;
1476                            }
1477                        } catch (FileNotFoundException e) {
1478                            Slog.w(TAG, "Jar not found: " + path);
1479                        } catch (IOException e) {
1480                            Slog.w(TAG, "Exception reading jar: " + path, e);
1481                        }
1482                    }
1483                }
1484            }
1485
1486            if (didDexOptLibraryOrTool) {
1487                // If we dexopted a library or tool, then something on the system has
1488                // changed. Consider this significant, and wipe away all other
1489                // existing dexopt files to ensure we don't leave any dangling around.
1490                //
1491                // Additionally, delete all dex files from the root directory
1492                // since there shouldn't be any there anyway.
1493                //
1494                // TODO: This should be revisited because it isn't as good an indicator
1495                // as it used to be. It used to include the boot classpath but at some point
1496                // DexFile.isDexOptNeeded started returning false for the boot
1497                // class path files in all cases. It is very possible in a
1498                // small maintenance release update that the library and tool
1499                // jars may be unchanged but APK could be removed resulting in
1500                // unused dalvik-cache files.
1501                mInstaller.pruneDexCache();
1502            }
1503
1504            // Collect vendor overlay packages.
1505            // (Do this before scanning any apps.)
1506            // For security and version matching reason, only consider
1507            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1508            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1509            mVendorOverlayInstallObserver = new AppDirObserver(
1510                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1511            mVendorOverlayInstallObserver.startWatching();
1512            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1513                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1514
1515            // Find base frameworks (resource packages without code).
1516            mFrameworkInstallObserver = new AppDirObserver(
1517                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1518            mFrameworkInstallObserver.startWatching();
1519            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR
1521                    | PackageParser.PARSE_IS_PRIVILEGED,
1522                    scanMode | SCAN_NO_DEX, 0);
1523
1524            // Collected privileged system packages.
1525            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1526            mPrivilegedInstallObserver = new AppDirObserver(
1527                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1528            mPrivilegedInstallObserver.startWatching();
1529                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1530                        | PackageParser.PARSE_IS_SYSTEM_DIR
1531                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1532
1533            // Collect ordinary system packages.
1534            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1535            mSystemInstallObserver = new AppDirObserver(
1536                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1537            mSystemInstallObserver.startWatching();
1538            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1540
1541            // Collect all vendor packages.
1542            File vendorAppDir = new File("/vendor/app");
1543            try {
1544                vendorAppDir = vendorAppDir.getCanonicalFile();
1545            } catch (IOException e) {
1546                // failed to look up canonical path, continue with original one
1547            }
1548            mVendorInstallObserver = new AppDirObserver(
1549                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1550            mVendorInstallObserver.startWatching();
1551            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1553
1554            // Collect all OEM packages.
1555            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1556            mOemInstallObserver = new AppDirObserver(
1557                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1558            mOemInstallObserver.startWatching();
1559            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1560                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1561
1562            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1563            mInstaller.moveFiles();
1564
1565            // Prune any system packages that no longer exist.
1566            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1567            if (!mOnlyCore) {
1568                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1569                while (psit.hasNext()) {
1570                    PackageSetting ps = psit.next();
1571
1572                    /*
1573                     * If this is not a system app, it can't be a
1574                     * disable system app.
1575                     */
1576                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1577                        continue;
1578                    }
1579
1580                    /*
1581                     * If the package is scanned, it's not erased.
1582                     */
1583                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1584                    if (scannedPkg != null) {
1585                        /*
1586                         * If the system app is both scanned and in the
1587                         * disabled packages list, then it must have been
1588                         * added via OTA. Remove it from the currently
1589                         * scanned package so the previously user-installed
1590                         * application can be scanned.
1591                         */
1592                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1593                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1594                                    + "; removing system app");
1595                            removePackageLI(ps, true);
1596                        }
1597
1598                        continue;
1599                    }
1600
1601                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1602                        psit.remove();
1603                        String msg = "System package " + ps.name
1604                                + " no longer exists; wiping its data";
1605                        reportSettingsProblem(Log.WARN, msg);
1606                        removeDataDirsLI(ps.name);
1607                    } else {
1608                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1609                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1610                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1611                        }
1612                    }
1613                }
1614            }
1615
1616            //look for any incomplete package installations
1617            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1618            //clean up list
1619            for(int i = 0; i < deletePkgsList.size(); i++) {
1620                //clean up here
1621                cleanupInstallFailedPackage(deletePkgsList.get(i));
1622            }
1623            //delete tmp files
1624            deleteTempPackageFiles();
1625
1626            // Remove any shared userIDs that have no associated packages
1627            mSettings.pruneSharedUsersLPw();
1628
1629            if (!mOnlyCore) {
1630                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1631                        SystemClock.uptimeMillis());
1632                mAppInstallObserver = new AppDirObserver(
1633                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1634                mAppInstallObserver.startWatching();
1635                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1636
1637                mDrmAppInstallObserver = new AppDirObserver(
1638                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1639                mDrmAppInstallObserver.startWatching();
1640                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1641                        scanMode, 0);
1642
1643                /**
1644                 * Remove disable package settings for any updated system
1645                 * apps that were removed via an OTA. If they're not a
1646                 * previously-updated app, remove them completely.
1647                 * Otherwise, just revoke their system-level permissions.
1648                 */
1649                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1650                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1651                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1652
1653                    String msg;
1654                    if (deletedPkg == null) {
1655                        msg = "Updated system package " + deletedAppName
1656                                + " no longer exists; wiping its data";
1657                        removeDataDirsLI(deletedAppName);
1658                    } else {
1659                        msg = "Updated system app + " + deletedAppName
1660                                + " no longer present; removing system privileges for "
1661                                + deletedAppName;
1662
1663                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1664
1665                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1666                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1667                    }
1668                    reportSettingsProblem(Log.WARN, msg);
1669                }
1670            } else {
1671                mAppInstallObserver = null;
1672                mDrmAppInstallObserver = null;
1673            }
1674
1675            // Now that we know all of the shared libraries, update all clients to have
1676            // the correct library paths.
1677            updateAllSharedLibrariesLPw();
1678
1679            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1680                // NOTE: We ignore potential failures here during a system scan (like
1681                // the rest of the commands above) because there's precious little we
1682                // can do about it. A settings error is reported, though.
1683                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1684                        false /* force dexopt */, false /* defer dexopt */);
1685            }
1686
1687            // Now that we know all the packages we are keeping,
1688            // read and update their last usage times.
1689            mPackageUsage.readLP();
1690
1691            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1692                    SystemClock.uptimeMillis());
1693            Slog.i(TAG, "Time to scan packages: "
1694                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1695                    + " seconds");
1696
1697            // If the platform SDK has changed since the last time we booted,
1698            // we need to re-grant app permission to catch any new ones that
1699            // appear.  This is really a hack, and means that apps can in some
1700            // cases get permissions that the user didn't initially explicitly
1701            // allow...  it would be nice to have some better way to handle
1702            // this situation.
1703            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1704                    != mSdkVersion;
1705            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1706                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1707                    + "; regranting permissions for internal storage");
1708            mSettings.mInternalSdkPlatform = mSdkVersion;
1709
1710            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1711                    | (regrantPermissions
1712                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1713                            : 0));
1714
1715            // If this is the first boot, and it is a normal boot, then
1716            // we need to initialize the default preferred apps.
1717            if (!mRestoredSettings && !onlyCore) {
1718                mSettings.readDefaultPreferredAppsLPw(this, 0);
1719            }
1720
1721            // All the changes are done during package scanning.
1722            mSettings.updateInternalDatabaseVersion();
1723
1724            // can downgrade to reader
1725            mSettings.writeLPr();
1726
1727            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1728                    SystemClock.uptimeMillis());
1729
1730
1731            mRequiredVerifierPackage = getRequiredVerifierLPr();
1732        } // synchronized (mPackages)
1733        } // synchronized (mInstallLock)
1734
1735        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1736
1737        // Now after opening every single application zip, make sure they
1738        // are all flushed.  Not really needed, but keeps things nice and
1739        // tidy.
1740        Runtime.getRuntime().gc();
1741    }
1742
1743    @Override
1744    public boolean isFirstBoot() {
1745        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1746    }
1747
1748    @Override
1749    public boolean isOnlyCoreApps() {
1750        return mOnlyCore;
1751    }
1752
1753    private String getRequiredVerifierLPr() {
1754        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1755        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1756                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1757
1758        String requiredVerifier = null;
1759
1760        final int N = receivers.size();
1761        for (int i = 0; i < N; i++) {
1762            final ResolveInfo info = receivers.get(i);
1763
1764            if (info.activityInfo == null) {
1765                continue;
1766            }
1767
1768            final String packageName = info.activityInfo.packageName;
1769
1770            final PackageSetting ps = mSettings.mPackages.get(packageName);
1771            if (ps == null) {
1772                continue;
1773            }
1774
1775            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1776            if (!gp.grantedPermissions
1777                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1778                continue;
1779            }
1780
1781            if (requiredVerifier != null) {
1782                throw new RuntimeException("There can be only one required verifier");
1783            }
1784
1785            requiredVerifier = packageName;
1786        }
1787
1788        return requiredVerifier;
1789    }
1790
1791    @Override
1792    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1793            throws RemoteException {
1794        try {
1795            return super.onTransact(code, data, reply, flags);
1796        } catch (RuntimeException e) {
1797            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1798                Slog.wtf(TAG, "Package Manager Crash", e);
1799            }
1800            throw e;
1801        }
1802    }
1803
1804    void cleanupInstallFailedPackage(PackageSetting ps) {
1805        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1806        removeDataDirsLI(ps.name);
1807        if (ps.codePath != null) {
1808            if (!ps.codePath.delete()) {
1809                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1810            }
1811        }
1812        if (ps.resourcePath != null) {
1813            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1814                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1815            }
1816        }
1817        mSettings.removePackageLPw(ps.name);
1818    }
1819
1820    void readPermissions(File libraryDir, boolean onlyFeatures) {
1821        // Read permissions from .../etc/permission directory.
1822        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1823            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1824            return;
1825        }
1826        if (!libraryDir.canRead()) {
1827            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1828            return;
1829        }
1830
1831        // Iterate over the files in the directory and scan .xml files
1832        for (File f : libraryDir.listFiles()) {
1833            // We'll read platform.xml last
1834            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1835                continue;
1836            }
1837
1838            if (!f.getPath().endsWith(".xml")) {
1839                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1840                continue;
1841            }
1842            if (!f.canRead()) {
1843                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1844                continue;
1845            }
1846
1847            readPermissionsFromXml(f, onlyFeatures);
1848        }
1849
1850        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1851        final File permFile = new File(Environment.getRootDirectory(),
1852                "etc/permissions/platform.xml");
1853        readPermissionsFromXml(permFile, onlyFeatures);
1854    }
1855
1856    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1857        FileReader permReader = null;
1858        try {
1859            permReader = new FileReader(permFile);
1860        } catch (FileNotFoundException e) {
1861            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1862            return;
1863        }
1864
1865        try {
1866            XmlPullParser parser = Xml.newPullParser();
1867            parser.setInput(permReader);
1868
1869            XmlUtils.beginDocument(parser, "permissions");
1870
1871            while (true) {
1872                XmlUtils.nextElement(parser);
1873                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1874                    break;
1875                }
1876
1877                String name = parser.getName();
1878                if ("group".equals(name) && !onlyFeatures) {
1879                    String gidStr = parser.getAttributeValue(null, "gid");
1880                    if (gidStr != null) {
1881                        int gid = Process.getGidForName(gidStr);
1882                        mGlobalGids = appendInt(mGlobalGids, gid);
1883                    } else {
1884                        Slog.w(TAG, "<group> without gid at "
1885                                + parser.getPositionDescription());
1886                    }
1887
1888                    XmlUtils.skipCurrentTag(parser);
1889                    continue;
1890                } else if ("permission".equals(name) && !onlyFeatures) {
1891                    String perm = parser.getAttributeValue(null, "name");
1892                    if (perm == null) {
1893                        Slog.w(TAG, "<permission> without name at "
1894                                + parser.getPositionDescription());
1895                        XmlUtils.skipCurrentTag(parser);
1896                        continue;
1897                    }
1898                    perm = perm.intern();
1899                    readPermission(parser, perm);
1900
1901                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1902                    String perm = parser.getAttributeValue(null, "name");
1903                    if (perm == null) {
1904                        Slog.w(TAG, "<assign-permission> without name at "
1905                                + parser.getPositionDescription());
1906                        XmlUtils.skipCurrentTag(parser);
1907                        continue;
1908                    }
1909                    String uidStr = parser.getAttributeValue(null, "uid");
1910                    if (uidStr == null) {
1911                        Slog.w(TAG, "<assign-permission> without uid at "
1912                                + parser.getPositionDescription());
1913                        XmlUtils.skipCurrentTag(parser);
1914                        continue;
1915                    }
1916                    int uid = Process.getUidForName(uidStr);
1917                    if (uid < 0) {
1918                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1919                                + uidStr + "\" at "
1920                                + parser.getPositionDescription());
1921                        XmlUtils.skipCurrentTag(parser);
1922                        continue;
1923                    }
1924                    perm = perm.intern();
1925                    HashSet<String> perms = mSystemPermissions.get(uid);
1926                    if (perms == null) {
1927                        perms = new HashSet<String>();
1928                        mSystemPermissions.put(uid, perms);
1929                    }
1930                    perms.add(perm);
1931                    XmlUtils.skipCurrentTag(parser);
1932
1933                } else if ("library".equals(name) && !onlyFeatures) {
1934                    String lname = parser.getAttributeValue(null, "name");
1935                    String lfile = parser.getAttributeValue(null, "file");
1936                    if (lname == null) {
1937                        Slog.w(TAG, "<library> without name at "
1938                                + parser.getPositionDescription());
1939                    } else if (lfile == null) {
1940                        Slog.w(TAG, "<library> without file at "
1941                                + parser.getPositionDescription());
1942                    } else {
1943                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1944                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1945                    }
1946                    XmlUtils.skipCurrentTag(parser);
1947                    continue;
1948
1949                } else if ("feature".equals(name)) {
1950                    String fname = parser.getAttributeValue(null, "name");
1951                    if (fname == null) {
1952                        Slog.w(TAG, "<feature> without name at "
1953                                + parser.getPositionDescription());
1954                    } else {
1955                        //Log.i(TAG, "Got feature " + fname);
1956                        FeatureInfo fi = new FeatureInfo();
1957                        fi.name = fname;
1958                        mAvailableFeatures.put(fname, fi);
1959                    }
1960                    XmlUtils.skipCurrentTag(parser);
1961                    continue;
1962
1963                } else {
1964                    XmlUtils.skipCurrentTag(parser);
1965                    continue;
1966                }
1967
1968            }
1969            permReader.close();
1970        } catch (XmlPullParserException e) {
1971            Slog.w(TAG, "Got execption parsing permissions.", e);
1972        } catch (IOException e) {
1973            Slog.w(TAG, "Got execption parsing permissions.", e);
1974        }
1975    }
1976
1977    void readPermission(XmlPullParser parser, String name)
1978            throws IOException, XmlPullParserException {
1979
1980        name = name.intern();
1981
1982        BasePermission bp = mSettings.mPermissions.get(name);
1983        if (bp == null) {
1984            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1985            mSettings.mPermissions.put(name, bp);
1986        }
1987        int outerDepth = parser.getDepth();
1988        int type;
1989        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1990               && (type != XmlPullParser.END_TAG
1991                       || parser.getDepth() > outerDepth)) {
1992            if (type == XmlPullParser.END_TAG
1993                    || type == XmlPullParser.TEXT) {
1994                continue;
1995            }
1996
1997            String tagName = parser.getName();
1998            if ("group".equals(tagName)) {
1999                String gidStr = parser.getAttributeValue(null, "gid");
2000                if (gidStr != null) {
2001                    int gid = Process.getGidForName(gidStr);
2002                    bp.gids = appendInt(bp.gids, gid);
2003                } else {
2004                    Slog.w(TAG, "<group> without gid at "
2005                            + parser.getPositionDescription());
2006                }
2007            }
2008            XmlUtils.skipCurrentTag(parser);
2009        }
2010    }
2011
2012    static int[] appendInts(int[] cur, int[] add) {
2013        if (add == null) return cur;
2014        if (cur == null) return add;
2015        final int N = add.length;
2016        for (int i=0; i<N; i++) {
2017            cur = appendInt(cur, add[i]);
2018        }
2019        return cur;
2020    }
2021
2022    static int[] removeInts(int[] cur, int[] rem) {
2023        if (rem == null) return cur;
2024        if (cur == null) return cur;
2025        final int N = rem.length;
2026        for (int i=0; i<N; i++) {
2027            cur = removeInt(cur, rem[i]);
2028        }
2029        return cur;
2030    }
2031
2032    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2033        if (!sUserManager.exists(userId)) return null;
2034        final PackageSetting ps = (PackageSetting) p.mExtras;
2035        if (ps == null) {
2036            return null;
2037        }
2038        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2039        final PackageUserState state = ps.readUserState(userId);
2040        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2041                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2042                state, userId);
2043    }
2044
2045    @Override
2046    public boolean isPackageAvailable(String packageName, int userId) {
2047        if (!sUserManager.exists(userId)) return false;
2048        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2049        synchronized (mPackages) {
2050            PackageParser.Package p = mPackages.get(packageName);
2051            if (p != null) {
2052                final PackageSetting ps = (PackageSetting) p.mExtras;
2053                if (ps != null) {
2054                    final PackageUserState state = ps.readUserState(userId);
2055                    if (state != null) {
2056                        return PackageParser.isAvailable(state);
2057                    }
2058                }
2059            }
2060        }
2061        return false;
2062    }
2063
2064    @Override
2065    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2066        if (!sUserManager.exists(userId)) return null;
2067        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2068        // reader
2069        synchronized (mPackages) {
2070            PackageParser.Package p = mPackages.get(packageName);
2071            if (DEBUG_PACKAGE_INFO)
2072                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2073            if (p != null) {
2074                return generatePackageInfo(p, flags, userId);
2075            }
2076            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2077                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2078            }
2079        }
2080        return null;
2081    }
2082
2083    @Override
2084    public String[] currentToCanonicalPackageNames(String[] names) {
2085        String[] out = new String[names.length];
2086        // reader
2087        synchronized (mPackages) {
2088            for (int i=names.length-1; i>=0; i--) {
2089                PackageSetting ps = mSettings.mPackages.get(names[i]);
2090                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2091            }
2092        }
2093        return out;
2094    }
2095
2096    @Override
2097    public String[] canonicalToCurrentPackageNames(String[] names) {
2098        String[] out = new String[names.length];
2099        // reader
2100        synchronized (mPackages) {
2101            for (int i=names.length-1; i>=0; i--) {
2102                String cur = mSettings.mRenamedPackages.get(names[i]);
2103                out[i] = cur != null ? cur : names[i];
2104            }
2105        }
2106        return out;
2107    }
2108
2109    @Override
2110    public int getPackageUid(String packageName, int userId) {
2111        if (!sUserManager.exists(userId)) return -1;
2112        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2113        // reader
2114        synchronized (mPackages) {
2115            PackageParser.Package p = mPackages.get(packageName);
2116            if(p != null) {
2117                return UserHandle.getUid(userId, p.applicationInfo.uid);
2118            }
2119            PackageSetting ps = mSettings.mPackages.get(packageName);
2120            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2121                return -1;
2122            }
2123            p = ps.pkg;
2124            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2125        }
2126    }
2127
2128    @Override
2129    public int[] getPackageGids(String packageName) {
2130        // reader
2131        synchronized (mPackages) {
2132            PackageParser.Package p = mPackages.get(packageName);
2133            if (DEBUG_PACKAGE_INFO)
2134                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2135            if (p != null) {
2136                final PackageSetting ps = (PackageSetting)p.mExtras;
2137                return ps.getGids();
2138            }
2139        }
2140        // stupid thing to indicate an error.
2141        return new int[0];
2142    }
2143
2144    static final PermissionInfo generatePermissionInfo(
2145            BasePermission bp, int flags) {
2146        if (bp.perm != null) {
2147            return PackageParser.generatePermissionInfo(bp.perm, flags);
2148        }
2149        PermissionInfo pi = new PermissionInfo();
2150        pi.name = bp.name;
2151        pi.packageName = bp.sourcePackage;
2152        pi.nonLocalizedLabel = bp.name;
2153        pi.protectionLevel = bp.protectionLevel;
2154        return pi;
2155    }
2156
2157    @Override
2158    public PermissionInfo getPermissionInfo(String name, int flags) {
2159        // reader
2160        synchronized (mPackages) {
2161            final BasePermission p = mSettings.mPermissions.get(name);
2162            if (p != null) {
2163                return generatePermissionInfo(p, flags);
2164            }
2165            return null;
2166        }
2167    }
2168
2169    @Override
2170    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2171        // reader
2172        synchronized (mPackages) {
2173            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2174            for (BasePermission p : mSettings.mPermissions.values()) {
2175                if (group == null) {
2176                    if (p.perm == null || p.perm.info.group == null) {
2177                        out.add(generatePermissionInfo(p, flags));
2178                    }
2179                } else {
2180                    if (p.perm != null && group.equals(p.perm.info.group)) {
2181                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2182                    }
2183                }
2184            }
2185
2186            if (out.size() > 0) {
2187                return out;
2188            }
2189            return mPermissionGroups.containsKey(group) ? out : null;
2190        }
2191    }
2192
2193    @Override
2194    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2195        // reader
2196        synchronized (mPackages) {
2197            return PackageParser.generatePermissionGroupInfo(
2198                    mPermissionGroups.get(name), flags);
2199        }
2200    }
2201
2202    @Override
2203    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2204        // reader
2205        synchronized (mPackages) {
2206            final int N = mPermissionGroups.size();
2207            ArrayList<PermissionGroupInfo> out
2208                    = new ArrayList<PermissionGroupInfo>(N);
2209            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2210                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2211            }
2212            return out;
2213        }
2214    }
2215
2216    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2217            int userId) {
2218        if (!sUserManager.exists(userId)) return null;
2219        PackageSetting ps = mSettings.mPackages.get(packageName);
2220        if (ps != null) {
2221            if (ps.pkg == null) {
2222                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2223                        flags, userId);
2224                if (pInfo != null) {
2225                    return pInfo.applicationInfo;
2226                }
2227                return null;
2228            }
2229            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2230                    ps.readUserState(userId), userId);
2231        }
2232        return null;
2233    }
2234
2235    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2236            int userId) {
2237        if (!sUserManager.exists(userId)) return null;
2238        PackageSetting ps = mSettings.mPackages.get(packageName);
2239        if (ps != null) {
2240            PackageParser.Package pkg = ps.pkg;
2241            if (pkg == null) {
2242                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2243                    return null;
2244                }
2245                // App code is gone, so we aren't worried about split paths
2246                pkg = new PackageParser.Package(packageName);
2247                pkg.applicationInfo.packageName = packageName;
2248                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2249                pkg.applicationInfo.sourceDir = ps.codePathString;
2250                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2251                pkg.applicationInfo.dataDir =
2252                        getDataPathForPackage(packageName, 0).getPath();
2253                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2254                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2255            }
2256            return generatePackageInfo(pkg, flags, userId);
2257        }
2258        return null;
2259    }
2260
2261    @Override
2262    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2263        if (!sUserManager.exists(userId)) return null;
2264        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2265        // writer
2266        synchronized (mPackages) {
2267            PackageParser.Package p = mPackages.get(packageName);
2268            if (DEBUG_PACKAGE_INFO) Log.v(
2269                    TAG, "getApplicationInfo " + packageName
2270                    + ": " + p);
2271            if (p != null) {
2272                PackageSetting ps = mSettings.mPackages.get(packageName);
2273                if (ps == null) return null;
2274                // Note: isEnabledLP() does not apply here - always return info
2275                return PackageParser.generateApplicationInfo(
2276                        p, flags, ps.readUserState(userId), userId);
2277            }
2278            if ("android".equals(packageName)||"system".equals(packageName)) {
2279                return mAndroidApplication;
2280            }
2281            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2282                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2283            }
2284        }
2285        return null;
2286    }
2287
2288
2289    @Override
2290    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2291        mContext.enforceCallingOrSelfPermission(
2292                android.Manifest.permission.CLEAR_APP_CACHE, null);
2293        // Queue up an async operation since clearing cache may take a little while.
2294        mHandler.post(new Runnable() {
2295            public void run() {
2296                mHandler.removeCallbacks(this);
2297                int retCode = -1;
2298                synchronized (mInstallLock) {
2299                    retCode = mInstaller.freeCache(freeStorageSize);
2300                    if (retCode < 0) {
2301                        Slog.w(TAG, "Couldn't clear application caches");
2302                    }
2303                }
2304                if (observer != null) {
2305                    try {
2306                        observer.onRemoveCompleted(null, (retCode >= 0));
2307                    } catch (RemoteException e) {
2308                        Slog.w(TAG, "RemoveException when invoking call back");
2309                    }
2310                }
2311            }
2312        });
2313    }
2314
2315    @Override
2316    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2317        mContext.enforceCallingOrSelfPermission(
2318                android.Manifest.permission.CLEAR_APP_CACHE, null);
2319        // Queue up an async operation since clearing cache may take a little while.
2320        mHandler.post(new Runnable() {
2321            public void run() {
2322                mHandler.removeCallbacks(this);
2323                int retCode = -1;
2324                synchronized (mInstallLock) {
2325                    retCode = mInstaller.freeCache(freeStorageSize);
2326                    if (retCode < 0) {
2327                        Slog.w(TAG, "Couldn't clear application caches");
2328                    }
2329                }
2330                if(pi != null) {
2331                    try {
2332                        // Callback via pending intent
2333                        int code = (retCode >= 0) ? 1 : 0;
2334                        pi.sendIntent(null, code, null,
2335                                null, null);
2336                    } catch (SendIntentException e1) {
2337                        Slog.i(TAG, "Failed to send pending intent");
2338                    }
2339                }
2340            }
2341        });
2342    }
2343
2344    void freeStorage(long freeStorageSize) throws IOException {
2345        synchronized (mInstallLock) {
2346            if (mInstaller.freeCache(freeStorageSize) < 0) {
2347                throw new IOException("Failed to free enough space");
2348            }
2349        }
2350    }
2351
2352    @Override
2353    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2354        if (!sUserManager.exists(userId)) return null;
2355        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2356        synchronized (mPackages) {
2357            PackageParser.Activity a = mActivities.mActivities.get(component);
2358
2359            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2360            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2361                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2362                if (ps == null) return null;
2363                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2364                        userId);
2365            }
2366            if (mResolveComponentName.equals(component)) {
2367                return mResolveActivity;
2368            }
2369        }
2370        return null;
2371    }
2372
2373    @Override
2374    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2375            String resolvedType) {
2376        synchronized (mPackages) {
2377            PackageParser.Activity a = mActivities.mActivities.get(component);
2378            if (a == null) {
2379                return false;
2380            }
2381            for (int i=0; i<a.intents.size(); i++) {
2382                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2383                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2384                    return true;
2385                }
2386            }
2387            return false;
2388        }
2389    }
2390
2391    @Override
2392    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2393        if (!sUserManager.exists(userId)) return null;
2394        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2395        synchronized (mPackages) {
2396            PackageParser.Activity a = mReceivers.mActivities.get(component);
2397            if (DEBUG_PACKAGE_INFO) Log.v(
2398                TAG, "getReceiverInfo " + component + ": " + a);
2399            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2400                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2401                if (ps == null) return null;
2402                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2403                        userId);
2404            }
2405        }
2406        return null;
2407    }
2408
2409    @Override
2410    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2411        if (!sUserManager.exists(userId)) return null;
2412        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2413        synchronized (mPackages) {
2414            PackageParser.Service s = mServices.mServices.get(component);
2415            if (DEBUG_PACKAGE_INFO) Log.v(
2416                TAG, "getServiceInfo " + component + ": " + s);
2417            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2418                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2419                if (ps == null) return null;
2420                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2421                        userId);
2422            }
2423        }
2424        return null;
2425    }
2426
2427    @Override
2428    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2429        if (!sUserManager.exists(userId)) return null;
2430        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2431        synchronized (mPackages) {
2432            PackageParser.Provider p = mProviders.mProviders.get(component);
2433            if (DEBUG_PACKAGE_INFO) Log.v(
2434                TAG, "getProviderInfo " + component + ": " + p);
2435            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2436                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2437                if (ps == null) return null;
2438                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2439                        userId);
2440            }
2441        }
2442        return null;
2443    }
2444
2445    @Override
2446    public String[] getSystemSharedLibraryNames() {
2447        Set<String> libSet;
2448        synchronized (mPackages) {
2449            libSet = mSharedLibraries.keySet();
2450            int size = libSet.size();
2451            if (size > 0) {
2452                String[] libs = new String[size];
2453                libSet.toArray(libs);
2454                return libs;
2455            }
2456        }
2457        return null;
2458    }
2459
2460    @Override
2461    public FeatureInfo[] getSystemAvailableFeatures() {
2462        Collection<FeatureInfo> featSet;
2463        synchronized (mPackages) {
2464            featSet = mAvailableFeatures.values();
2465            int size = featSet.size();
2466            if (size > 0) {
2467                FeatureInfo[] features = new FeatureInfo[size+1];
2468                featSet.toArray(features);
2469                FeatureInfo fi = new FeatureInfo();
2470                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2471                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2472                features[size] = fi;
2473                return features;
2474            }
2475        }
2476        return null;
2477    }
2478
2479    @Override
2480    public boolean hasSystemFeature(String name) {
2481        synchronized (mPackages) {
2482            return mAvailableFeatures.containsKey(name);
2483        }
2484    }
2485
2486    private void checkValidCaller(int uid, int userId) {
2487        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2488            return;
2489
2490        throw new SecurityException("Caller uid=" + uid
2491                + " is not privileged to communicate with user=" + userId);
2492    }
2493
2494    @Override
2495    public int checkPermission(String permName, String pkgName) {
2496        synchronized (mPackages) {
2497            PackageParser.Package p = mPackages.get(pkgName);
2498            if (p != null && p.mExtras != null) {
2499                PackageSetting ps = (PackageSetting)p.mExtras;
2500                if (ps.sharedUser != null) {
2501                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2502                        return PackageManager.PERMISSION_GRANTED;
2503                    }
2504                } else if (ps.grantedPermissions.contains(permName)) {
2505                    return PackageManager.PERMISSION_GRANTED;
2506                }
2507            }
2508        }
2509        return PackageManager.PERMISSION_DENIED;
2510    }
2511
2512    @Override
2513    public int checkUidPermission(String permName, int uid) {
2514        synchronized (mPackages) {
2515            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2516            if (obj != null) {
2517                GrantedPermissions gp = (GrantedPermissions)obj;
2518                if (gp.grantedPermissions.contains(permName)) {
2519                    return PackageManager.PERMISSION_GRANTED;
2520                }
2521            } else {
2522                HashSet<String> perms = mSystemPermissions.get(uid);
2523                if (perms != null && perms.contains(permName)) {
2524                    return PackageManager.PERMISSION_GRANTED;
2525                }
2526            }
2527        }
2528        return PackageManager.PERMISSION_DENIED;
2529    }
2530
2531    /**
2532     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2533     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2534     * @param message the message to log on security exception
2535     */
2536    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2537            String message) {
2538        if (userId < 0) {
2539            throw new IllegalArgumentException("Invalid userId " + userId);
2540        }
2541        if (userId == UserHandle.getUserId(callingUid)) return;
2542        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2543            if (requireFullPermission) {
2544                mContext.enforceCallingOrSelfPermission(
2545                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2546            } else {
2547                try {
2548                    mContext.enforceCallingOrSelfPermission(
2549                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2550                } catch (SecurityException se) {
2551                    mContext.enforceCallingOrSelfPermission(
2552                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2553                }
2554            }
2555        }
2556    }
2557
2558    private BasePermission findPermissionTreeLP(String permName) {
2559        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2560            if (permName.startsWith(bp.name) &&
2561                    permName.length() > bp.name.length() &&
2562                    permName.charAt(bp.name.length()) == '.') {
2563                return bp;
2564            }
2565        }
2566        return null;
2567    }
2568
2569    private BasePermission checkPermissionTreeLP(String permName) {
2570        if (permName != null) {
2571            BasePermission bp = findPermissionTreeLP(permName);
2572            if (bp != null) {
2573                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2574                    return bp;
2575                }
2576                throw new SecurityException("Calling uid "
2577                        + Binder.getCallingUid()
2578                        + " is not allowed to add to permission tree "
2579                        + bp.name + " owned by uid " + bp.uid);
2580            }
2581        }
2582        throw new SecurityException("No permission tree found for " + permName);
2583    }
2584
2585    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2586        if (s1 == null) {
2587            return s2 == null;
2588        }
2589        if (s2 == null) {
2590            return false;
2591        }
2592        if (s1.getClass() != s2.getClass()) {
2593            return false;
2594        }
2595        return s1.equals(s2);
2596    }
2597
2598    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2599        if (pi1.icon != pi2.icon) return false;
2600        if (pi1.logo != pi2.logo) return false;
2601        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2602        if (!compareStrings(pi1.name, pi2.name)) return false;
2603        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2604        // We'll take care of setting this one.
2605        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2606        // These are not currently stored in settings.
2607        //if (!compareStrings(pi1.group, pi2.group)) return false;
2608        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2609        //if (pi1.labelRes != pi2.labelRes) return false;
2610        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2611        return true;
2612    }
2613
2614    int permissionInfoFootprint(PermissionInfo info) {
2615        int size = info.name.length();
2616        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2617        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2618        return size;
2619    }
2620
2621    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2622        int size = 0;
2623        for (BasePermission perm : mSettings.mPermissions.values()) {
2624            if (perm.uid == tree.uid) {
2625                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2626            }
2627        }
2628        return size;
2629    }
2630
2631    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2632        // We calculate the max size of permissions defined by this uid and throw
2633        // if that plus the size of 'info' would exceed our stated maximum.
2634        if (tree.uid != Process.SYSTEM_UID) {
2635            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2636            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2637                throw new SecurityException("Permission tree size cap exceeded");
2638            }
2639        }
2640    }
2641
2642    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2643        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2644            throw new SecurityException("Label must be specified in permission");
2645        }
2646        BasePermission tree = checkPermissionTreeLP(info.name);
2647        BasePermission bp = mSettings.mPermissions.get(info.name);
2648        boolean added = bp == null;
2649        boolean changed = true;
2650        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2651        if (added) {
2652            enforcePermissionCapLocked(info, tree);
2653            bp = new BasePermission(info.name, tree.sourcePackage,
2654                    BasePermission.TYPE_DYNAMIC);
2655        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2656            throw new SecurityException(
2657                    "Not allowed to modify non-dynamic permission "
2658                    + info.name);
2659        } else {
2660            if (bp.protectionLevel == fixedLevel
2661                    && bp.perm.owner.equals(tree.perm.owner)
2662                    && bp.uid == tree.uid
2663                    && comparePermissionInfos(bp.perm.info, info)) {
2664                changed = false;
2665            }
2666        }
2667        bp.protectionLevel = fixedLevel;
2668        info = new PermissionInfo(info);
2669        info.protectionLevel = fixedLevel;
2670        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2671        bp.perm.info.packageName = tree.perm.info.packageName;
2672        bp.uid = tree.uid;
2673        if (added) {
2674            mSettings.mPermissions.put(info.name, bp);
2675        }
2676        if (changed) {
2677            if (!async) {
2678                mSettings.writeLPr();
2679            } else {
2680                scheduleWriteSettingsLocked();
2681            }
2682        }
2683        return added;
2684    }
2685
2686    @Override
2687    public boolean addPermission(PermissionInfo info) {
2688        synchronized (mPackages) {
2689            return addPermissionLocked(info, false);
2690        }
2691    }
2692
2693    @Override
2694    public boolean addPermissionAsync(PermissionInfo info) {
2695        synchronized (mPackages) {
2696            return addPermissionLocked(info, true);
2697        }
2698    }
2699
2700    @Override
2701    public void removePermission(String name) {
2702        synchronized (mPackages) {
2703            checkPermissionTreeLP(name);
2704            BasePermission bp = mSettings.mPermissions.get(name);
2705            if (bp != null) {
2706                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2707                    throw new SecurityException(
2708                            "Not allowed to modify non-dynamic permission "
2709                            + name);
2710                }
2711                mSettings.mPermissions.remove(name);
2712                mSettings.writeLPr();
2713            }
2714        }
2715    }
2716
2717    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2718        int index = pkg.requestedPermissions.indexOf(bp.name);
2719        if (index == -1) {
2720            throw new SecurityException("Package " + pkg.packageName
2721                    + " has not requested permission " + bp.name);
2722        }
2723        boolean isNormal =
2724                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2725                        == PermissionInfo.PROTECTION_NORMAL);
2726        boolean isDangerous =
2727                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2728                        == PermissionInfo.PROTECTION_DANGEROUS);
2729        boolean isDevelopment =
2730                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2731
2732        if (!isNormal && !isDangerous && !isDevelopment) {
2733            throw new SecurityException("Permission " + bp.name
2734                    + " is not a changeable permission type");
2735        }
2736
2737        if (isNormal || isDangerous) {
2738            if (pkg.requestedPermissionsRequired.get(index)) {
2739                throw new SecurityException("Can't change " + bp.name
2740                        + ". It is required by the application");
2741            }
2742        }
2743    }
2744
2745    @Override
2746    public void grantPermission(String packageName, String permissionName) {
2747        mContext.enforceCallingOrSelfPermission(
2748                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2749        synchronized (mPackages) {
2750            final PackageParser.Package pkg = mPackages.get(packageName);
2751            if (pkg == null) {
2752                throw new IllegalArgumentException("Unknown package: " + packageName);
2753            }
2754            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2755            if (bp == null) {
2756                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2757            }
2758
2759            checkGrantRevokePermissions(pkg, bp);
2760
2761            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2762            if (ps == null) {
2763                return;
2764            }
2765            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2766            if (gp.grantedPermissions.add(permissionName)) {
2767                if (ps.haveGids) {
2768                    gp.gids = appendInts(gp.gids, bp.gids);
2769                }
2770                mSettings.writeLPr();
2771            }
2772        }
2773    }
2774
2775    @Override
2776    public void revokePermission(String packageName, String permissionName) {
2777        int changedAppId = -1;
2778
2779        synchronized (mPackages) {
2780            final PackageParser.Package pkg = mPackages.get(packageName);
2781            if (pkg == null) {
2782                throw new IllegalArgumentException("Unknown package: " + packageName);
2783            }
2784            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2785                mContext.enforceCallingOrSelfPermission(
2786                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2787            }
2788            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2789            if (bp == null) {
2790                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2791            }
2792
2793            checkGrantRevokePermissions(pkg, bp);
2794
2795            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2796            if (ps == null) {
2797                return;
2798            }
2799            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2800            if (gp.grantedPermissions.remove(permissionName)) {
2801                gp.grantedPermissions.remove(permissionName);
2802                if (ps.haveGids) {
2803                    gp.gids = removeInts(gp.gids, bp.gids);
2804                }
2805                mSettings.writeLPr();
2806                changedAppId = ps.appId;
2807            }
2808        }
2809
2810        if (changedAppId >= 0) {
2811            // We changed the perm on someone, kill its processes.
2812            IActivityManager am = ActivityManagerNative.getDefault();
2813            if (am != null) {
2814                final int callingUserId = UserHandle.getCallingUserId();
2815                final long ident = Binder.clearCallingIdentity();
2816                try {
2817                    //XXX we should only revoke for the calling user's app permissions,
2818                    // but for now we impact all users.
2819                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2820                    //        "revoke " + permissionName);
2821                    int[] users = sUserManager.getUserIds();
2822                    for (int user : users) {
2823                        am.killUid(UserHandle.getUid(user, changedAppId),
2824                                "revoke " + permissionName);
2825                    }
2826                } catch (RemoteException e) {
2827                } finally {
2828                    Binder.restoreCallingIdentity(ident);
2829                }
2830            }
2831        }
2832    }
2833
2834    @Override
2835    public boolean isProtectedBroadcast(String actionName) {
2836        synchronized (mPackages) {
2837            return mProtectedBroadcasts.contains(actionName);
2838        }
2839    }
2840
2841    @Override
2842    public int checkSignatures(String pkg1, String pkg2) {
2843        synchronized (mPackages) {
2844            final PackageParser.Package p1 = mPackages.get(pkg1);
2845            final PackageParser.Package p2 = mPackages.get(pkg2);
2846            if (p1 == null || p1.mExtras == null
2847                    || p2 == null || p2.mExtras == null) {
2848                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2849            }
2850            return compareSignatures(p1.mSignatures, p2.mSignatures);
2851        }
2852    }
2853
2854    @Override
2855    public int checkUidSignatures(int uid1, int uid2) {
2856        // Map to base uids.
2857        uid1 = UserHandle.getAppId(uid1);
2858        uid2 = UserHandle.getAppId(uid2);
2859        // reader
2860        synchronized (mPackages) {
2861            Signature[] s1;
2862            Signature[] s2;
2863            Object obj = mSettings.getUserIdLPr(uid1);
2864            if (obj != null) {
2865                if (obj instanceof SharedUserSetting) {
2866                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2867                } else if (obj instanceof PackageSetting) {
2868                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2869                } else {
2870                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2871                }
2872            } else {
2873                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2874            }
2875            obj = mSettings.getUserIdLPr(uid2);
2876            if (obj != null) {
2877                if (obj instanceof SharedUserSetting) {
2878                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2879                } else if (obj instanceof PackageSetting) {
2880                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2881                } else {
2882                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2883                }
2884            } else {
2885                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2886            }
2887            return compareSignatures(s1, s2);
2888        }
2889    }
2890
2891    /**
2892     * Compares two sets of signatures. Returns:
2893     * <br />
2894     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2895     * <br />
2896     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2897     * <br />
2898     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2899     * <br />
2900     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2901     * <br />
2902     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2903     */
2904    static int compareSignatures(Signature[] s1, Signature[] s2) {
2905        if (s1 == null) {
2906            return s2 == null
2907                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2908                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2909        }
2910
2911        if (s2 == null) {
2912            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2913        }
2914
2915        if (s1.length != s2.length) {
2916            return PackageManager.SIGNATURE_NO_MATCH;
2917        }
2918
2919        // Since both signature sets are of size 1, we can compare without HashSets.
2920        if (s1.length == 1) {
2921            return s1[0].equals(s2[0]) ?
2922                    PackageManager.SIGNATURE_MATCH :
2923                    PackageManager.SIGNATURE_NO_MATCH;
2924        }
2925
2926        HashSet<Signature> set1 = new HashSet<Signature>();
2927        for (Signature sig : s1) {
2928            set1.add(sig);
2929        }
2930        HashSet<Signature> set2 = new HashSet<Signature>();
2931        for (Signature sig : s2) {
2932            set2.add(sig);
2933        }
2934        // Make sure s2 contains all signatures in s1.
2935        if (set1.equals(set2)) {
2936            return PackageManager.SIGNATURE_MATCH;
2937        }
2938        return PackageManager.SIGNATURE_NO_MATCH;
2939    }
2940
2941    /**
2942     * If the database version for this type of package (internal storage or
2943     * external storage) is less than the version where package signatures
2944     * were updated, return true.
2945     */
2946    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2947        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2948                DatabaseVersion.SIGNATURE_END_ENTITY))
2949                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2950                        DatabaseVersion.SIGNATURE_END_ENTITY));
2951    }
2952
2953    /**
2954     * Used for backward compatibility to make sure any packages with
2955     * certificate chains get upgraded to the new style. {@code existingSigs}
2956     * will be in the old format (since they were stored on disk from before the
2957     * system upgrade) and {@code scannedSigs} will be in the newer format.
2958     */
2959    private int compareSignaturesCompat(PackageSignatures existingSigs,
2960            PackageParser.Package scannedPkg) {
2961        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2962            return PackageManager.SIGNATURE_NO_MATCH;
2963        }
2964
2965        HashSet<Signature> existingSet = new HashSet<Signature>();
2966        for (Signature sig : existingSigs.mSignatures) {
2967            existingSet.add(sig);
2968        }
2969        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2970        for (Signature sig : scannedPkg.mSignatures) {
2971            try {
2972                Signature[] chainSignatures = sig.getChainSignatures();
2973                for (Signature chainSig : chainSignatures) {
2974                    scannedCompatSet.add(chainSig);
2975                }
2976            } catch (CertificateEncodingException e) {
2977                scannedCompatSet.add(sig);
2978            }
2979        }
2980        /*
2981         * Make sure the expanded scanned set contains all signatures in the
2982         * existing one.
2983         */
2984        if (scannedCompatSet.equals(existingSet)) {
2985            // Migrate the old signatures to the new scheme.
2986            existingSigs.assignSignatures(scannedPkg.mSignatures);
2987            // The new KeySets will be re-added later in the scanning process.
2988            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2989            return PackageManager.SIGNATURE_MATCH;
2990        }
2991        return PackageManager.SIGNATURE_NO_MATCH;
2992    }
2993
2994    @Override
2995    public String[] getPackagesForUid(int uid) {
2996        uid = UserHandle.getAppId(uid);
2997        // reader
2998        synchronized (mPackages) {
2999            Object obj = mSettings.getUserIdLPr(uid);
3000            if (obj instanceof SharedUserSetting) {
3001                final SharedUserSetting sus = (SharedUserSetting) obj;
3002                final int N = sus.packages.size();
3003                final String[] res = new String[N];
3004                final Iterator<PackageSetting> it = sus.packages.iterator();
3005                int i = 0;
3006                while (it.hasNext()) {
3007                    res[i++] = it.next().name;
3008                }
3009                return res;
3010            } else if (obj instanceof PackageSetting) {
3011                final PackageSetting ps = (PackageSetting) obj;
3012                return new String[] { ps.name };
3013            }
3014        }
3015        return null;
3016    }
3017
3018    @Override
3019    public String getNameForUid(int uid) {
3020        // reader
3021        synchronized (mPackages) {
3022            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3023            if (obj instanceof SharedUserSetting) {
3024                final SharedUserSetting sus = (SharedUserSetting) obj;
3025                return sus.name + ":" + sus.userId;
3026            } else if (obj instanceof PackageSetting) {
3027                final PackageSetting ps = (PackageSetting) obj;
3028                return ps.name;
3029            }
3030        }
3031        return null;
3032    }
3033
3034    @Override
3035    public int getUidForSharedUser(String sharedUserName) {
3036        if(sharedUserName == null) {
3037            return -1;
3038        }
3039        // reader
3040        synchronized (mPackages) {
3041            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3042            if (suid == null) {
3043                return -1;
3044            }
3045            return suid.userId;
3046        }
3047    }
3048
3049    @Override
3050    public int getFlagsForUid(int uid) {
3051        synchronized (mPackages) {
3052            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3053            if (obj instanceof SharedUserSetting) {
3054                final SharedUserSetting sus = (SharedUserSetting) obj;
3055                return sus.pkgFlags;
3056            } else if (obj instanceof PackageSetting) {
3057                final PackageSetting ps = (PackageSetting) obj;
3058                return ps.pkgFlags;
3059            }
3060        }
3061        return 0;
3062    }
3063
3064    @Override
3065    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3066            int flags, int userId) {
3067        if (!sUserManager.exists(userId)) return null;
3068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3069        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3070        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3071    }
3072
3073    @Override
3074    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3075            IntentFilter filter, int match, ComponentName activity) {
3076        final int userId = UserHandle.getCallingUserId();
3077        if (DEBUG_PREFERRED) {
3078            Log.v(TAG, "setLastChosenActivity intent=" + intent
3079                + " resolvedType=" + resolvedType
3080                + " flags=" + flags
3081                + " filter=" + filter
3082                + " match=" + match
3083                + " activity=" + activity);
3084            filter.dump(new PrintStreamPrinter(System.out), "    ");
3085        }
3086        intent.setComponent(null);
3087        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3088        // Find any earlier preferred or last chosen entries and nuke them
3089        findPreferredActivity(intent, resolvedType,
3090                flags, query, 0, false, true, false, userId);
3091        // Add the new activity as the last chosen for this filter
3092        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3093    }
3094
3095    @Override
3096    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3097        final int userId = UserHandle.getCallingUserId();
3098        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3099        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3100        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3101                false, false, false, userId);
3102    }
3103
3104    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3105            int flags, List<ResolveInfo> query, int userId) {
3106        if (query != null) {
3107            final int N = query.size();
3108            if (N == 1) {
3109                return query.get(0);
3110            } else if (N > 1) {
3111                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3112                // If there is more than one activity with the same priority,
3113                // then let the user decide between them.
3114                ResolveInfo r0 = query.get(0);
3115                ResolveInfo r1 = query.get(1);
3116                if (DEBUG_INTENT_MATCHING || debug) {
3117                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3118                            + r1.activityInfo.name + "=" + r1.priority);
3119                }
3120                // If the first activity has a higher priority, or a different
3121                // default, then it is always desireable to pick it.
3122                if (r0.priority != r1.priority
3123                        || r0.preferredOrder != r1.preferredOrder
3124                        || r0.isDefault != r1.isDefault) {
3125                    return query.get(0);
3126                }
3127                // If we have saved a preference for a preferred activity for
3128                // this Intent, use that.
3129                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3130                        flags, query, r0.priority, true, false, debug, userId);
3131                if (ri != null) {
3132                    return ri;
3133                }
3134                if (userId != 0) {
3135                    ri = new ResolveInfo(mResolveInfo);
3136                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3137                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3138                            ri.activityInfo.applicationInfo);
3139                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3140                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3141                    return ri;
3142                }
3143                return mResolveInfo;
3144            }
3145        }
3146        return null;
3147    }
3148
3149    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3150            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3151        final int N = query.size();
3152        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3153                .get(userId);
3154        // Get the list of persistent preferred activities that handle the intent
3155        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3156        List<PersistentPreferredActivity> pprefs = ppir != null
3157                ? ppir.queryIntent(intent, resolvedType,
3158                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3159                : null;
3160        if (pprefs != null && pprefs.size() > 0) {
3161            final int M = pprefs.size();
3162            for (int i=0; i<M; i++) {
3163                final PersistentPreferredActivity ppa = pprefs.get(i);
3164                if (DEBUG_PREFERRED || debug) {
3165                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3166                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3167                            + "\n  component=" + ppa.mComponent);
3168                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3169                }
3170                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3171                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3172                if (DEBUG_PREFERRED || debug) {
3173                    Slog.v(TAG, "Found persistent preferred activity:");
3174                    if (ai != null) {
3175                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3176                    } else {
3177                        Slog.v(TAG, "  null");
3178                    }
3179                }
3180                if (ai == null) {
3181                    // This previously registered persistent preferred activity
3182                    // component is no longer known. Ignore it and do NOT remove it.
3183                    continue;
3184                }
3185                for (int j=0; j<N; j++) {
3186                    final ResolveInfo ri = query.get(j);
3187                    if (!ri.activityInfo.applicationInfo.packageName
3188                            .equals(ai.applicationInfo.packageName)) {
3189                        continue;
3190                    }
3191                    if (!ri.activityInfo.name.equals(ai.name)) {
3192                        continue;
3193                    }
3194                    //  Found a persistent preference that can handle the intent.
3195                    if (DEBUG_PREFERRED || debug) {
3196                        Slog.v(TAG, "Returning persistent preferred activity: " +
3197                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3198                    }
3199                    return ri;
3200                }
3201            }
3202        }
3203        return null;
3204    }
3205
3206    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3207            List<ResolveInfo> query, int priority, boolean always,
3208            boolean removeMatches, boolean debug, int userId) {
3209        if (!sUserManager.exists(userId)) return null;
3210        // writer
3211        synchronized (mPackages) {
3212            if (intent.getSelector() != null) {
3213                intent = intent.getSelector();
3214            }
3215            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3216
3217            // Try to find a matching persistent preferred activity.
3218            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3219                    debug, userId);
3220
3221            // If a persistent preferred activity matched, use it.
3222            if (pri != null) {
3223                return pri;
3224            }
3225
3226            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3227            // Get the list of preferred activities that handle the intent
3228            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3229            List<PreferredActivity> prefs = pir != null
3230                    ? pir.queryIntent(intent, resolvedType,
3231                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3232                    : null;
3233            if (prefs != null && prefs.size() > 0) {
3234                // First figure out how good the original match set is.
3235                // We will only allow preferred activities that came
3236                // from the same match quality.
3237                int match = 0;
3238
3239                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3240
3241                final int N = query.size();
3242                for (int j=0; j<N; j++) {
3243                    final ResolveInfo ri = query.get(j);
3244                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3245                            + ": 0x" + Integer.toHexString(match));
3246                    if (ri.match > match) {
3247                        match = ri.match;
3248                    }
3249                }
3250
3251                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3252                        + Integer.toHexString(match));
3253
3254                match &= IntentFilter.MATCH_CATEGORY_MASK;
3255                final int M = prefs.size();
3256                for (int i=0; i<M; i++) {
3257                    final PreferredActivity pa = prefs.get(i);
3258                    if (DEBUG_PREFERRED || debug) {
3259                        Slog.v(TAG, "Checking PreferredActivity ds="
3260                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3261                                + "\n  component=" + pa.mPref.mComponent);
3262                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3263                    }
3264                    if (pa.mPref.mMatch != match) {
3265                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3266                                + Integer.toHexString(pa.mPref.mMatch));
3267                        continue;
3268                    }
3269                    // If it's not an "always" type preferred activity and that's what we're
3270                    // looking for, skip it.
3271                    if (always && !pa.mPref.mAlways) {
3272                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3273                        continue;
3274                    }
3275                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3276                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3277                    if (DEBUG_PREFERRED || debug) {
3278                        Slog.v(TAG, "Found preferred activity:");
3279                        if (ai != null) {
3280                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3281                        } else {
3282                            Slog.v(TAG, "  null");
3283                        }
3284                    }
3285                    if (ai == null) {
3286                        // This previously registered preferred activity
3287                        // component is no longer known.  Most likely an update
3288                        // to the app was installed and in the new version this
3289                        // component no longer exists.  Clean it up by removing
3290                        // it from the preferred activities list, and skip it.
3291                        Slog.w(TAG, "Removing dangling preferred activity: "
3292                                + pa.mPref.mComponent);
3293                        pir.removeFilter(pa);
3294                        continue;
3295                    }
3296                    for (int j=0; j<N; j++) {
3297                        final ResolveInfo ri = query.get(j);
3298                        if (!ri.activityInfo.applicationInfo.packageName
3299                                .equals(ai.applicationInfo.packageName)) {
3300                            continue;
3301                        }
3302                        if (!ri.activityInfo.name.equals(ai.name)) {
3303                            continue;
3304                        }
3305
3306                        if (removeMatches) {
3307                            pir.removeFilter(pa);
3308                            if (DEBUG_PREFERRED) {
3309                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3310                            }
3311                            break;
3312                        }
3313
3314                        // Okay we found a previously set preferred or last chosen app.
3315                        // If the result set is different from when this
3316                        // was created, we need to clear it and re-ask the
3317                        // user their preference, if we're looking for an "always" type entry.
3318                        if (always && !pa.mPref.sameSet(query, priority)) {
3319                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3320                                    + intent + " type " + resolvedType);
3321                            if (DEBUG_PREFERRED) {
3322                                Slog.v(TAG, "Removing preferred activity since set changed "
3323                                        + pa.mPref.mComponent);
3324                            }
3325                            pir.removeFilter(pa);
3326                            // Re-add the filter as a "last chosen" entry (!always)
3327                            PreferredActivity lastChosen = new PreferredActivity(
3328                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3329                            pir.addFilter(lastChosen);
3330                            mSettings.writePackageRestrictionsLPr(userId);
3331                            return null;
3332                        }
3333
3334                        // Yay! Either the set matched or we're looking for the last chosen
3335                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3336                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3337                        mSettings.writePackageRestrictionsLPr(userId);
3338                        return ri;
3339                    }
3340                }
3341            }
3342            mSettings.writePackageRestrictionsLPr(userId);
3343        }
3344        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3345        return null;
3346    }
3347
3348    /*
3349     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3350     */
3351    @Override
3352    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3353            int targetUserId) {
3354        mContext.enforceCallingOrSelfPermission(
3355                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3356        List<CrossProfileIntentFilter> matches =
3357                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3358        if (matches != null) {
3359            int size = matches.size();
3360            for (int i = 0; i < size; i++) {
3361                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3362            }
3363        }
3364
3365        ArrayList<String> packageNames = null;
3366        SparseArray<ArrayList<String>> fromSource =
3367                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3368        if (fromSource != null) {
3369            packageNames = fromSource.get(targetUserId);
3370        }
3371        if (packageNames.contains(intent.getPackage())) {
3372            return true;
3373        }
3374        // We need the package name, so we try to resolve with the loosest flags possible
3375        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3376                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3377        int count = resolveInfos.size();
3378        for (int i = 0; i < count; i++) {
3379            ResolveInfo resolveInfo = resolveInfos.get(i);
3380            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3381                return true;
3382            }
3383        }
3384        return false;
3385    }
3386
3387    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3388            String resolvedType, int userId) {
3389        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3390        if (resolver != null) {
3391            return resolver.queryIntent(intent, resolvedType, false, userId);
3392        }
3393        return null;
3394    }
3395
3396    @Override
3397    public List<ResolveInfo> queryIntentActivities(Intent intent,
3398            String resolvedType, int flags, int userId) {
3399        if (!sUserManager.exists(userId)) return Collections.emptyList();
3400        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3401        ComponentName comp = intent.getComponent();
3402        if (comp == null) {
3403            if (intent.getSelector() != null) {
3404                intent = intent.getSelector();
3405                comp = intent.getComponent();
3406            }
3407        }
3408
3409        if (comp != null) {
3410            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3411            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3412            if (ai != null) {
3413                final ResolveInfo ri = new ResolveInfo();
3414                ri.activityInfo = ai;
3415                list.add(ri);
3416            }
3417            return list;
3418        }
3419
3420        // reader
3421        synchronized (mPackages) {
3422            final String pkgName = intent.getPackage();
3423            if (pkgName == null) {
3424                //Check if the intent needs to be forwarded to another user for this package
3425                ArrayList<ResolveInfo> crossProfileResult =
3426                        queryIntentActivitiesCrossProfilePackage(
3427                                intent, resolvedType, flags, userId);
3428                if (!crossProfileResult.isEmpty()) {
3429                    // Skip the current profile
3430                    return crossProfileResult;
3431                }
3432                List<ResolveInfo> result;
3433                List<CrossProfileIntentFilter> matchingFilters =
3434                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3435                // Check for results that need to skip the current profile.
3436                ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3437                        resolvedType, flags, userId);
3438                if (resolveInfo != null) {
3439                    result = new ArrayList<ResolveInfo>(1);
3440                    result.add(resolveInfo);
3441                    return result;
3442                }
3443                // Check for results in the current profile.
3444                result = mActivities.queryIntent(intent, resolvedType, flags, userId);
3445                // Check for cross profile results.
3446                resolveInfo = queryCrossProfileIntents(
3447                        matchingFilters, intent, resolvedType, flags, userId);
3448                if (resolveInfo != null) {
3449                    result.add(resolveInfo);
3450                }
3451                return result;
3452            }
3453            final PackageParser.Package pkg = mPackages.get(pkgName);
3454            if (pkg != null) {
3455                ArrayList<ResolveInfo> crossProfileResult =
3456                        queryIntentActivitiesCrossProfilePackage(
3457                                intent, resolvedType, flags, userId, pkg, pkgName);
3458                if (!crossProfileResult.isEmpty()) {
3459                    // Skip the current profile
3460                    return crossProfileResult;
3461                }
3462                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3463                        pkg.activities, userId);
3464            }
3465            return new ArrayList<ResolveInfo>();
3466        }
3467    }
3468
3469    private ResolveInfo querySkipCurrentProfileIntents(
3470            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3471            int flags, int sourceUserId) {
3472        if (matchingFilters != null) {
3473            int size = matchingFilters.size();
3474            for (int i = 0; i < size; i ++) {
3475                CrossProfileIntentFilter filter = matchingFilters.get(i);
3476                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3477                    // Checking if there are activities in the target user that can handle the
3478                    // intent.
3479                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3480                            flags, sourceUserId);
3481                    if (resolveInfo != null) {
3482                        return resolveInfo;
3483                    }
3484                }
3485            }
3486        }
3487        return null;
3488    }
3489
3490    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3491            Intent intent, String resolvedType, int flags, int userId) {
3492        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3493        SparseArray<ArrayList<String>> sourceForwardingInfo =
3494                mSettings.mCrossProfilePackageInfo.get(userId);
3495        if (sourceForwardingInfo != null) {
3496            int NI = sourceForwardingInfo.size();
3497            for (int i = 0; i < NI; i++) {
3498                int targetUserId = sourceForwardingInfo.keyAt(i);
3499                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3500                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3501                        intent, resolvedType, flags, targetUserId);
3502                int NJ = resolveInfos.size();
3503                for (int j = 0; j < NJ; j++) {
3504                    ResolveInfo resolveInfo = resolveInfos.get(j);
3505                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3506                        matchingResolveInfos.add(createForwardingResolveInfo(
3507                                resolveInfo.filter, userId, targetUserId));
3508                    }
3509                }
3510            }
3511        }
3512        return matchingResolveInfos;
3513    }
3514
3515    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3516            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3517            String packageName) {
3518        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3519        SparseArray<ArrayList<String>> sourceForwardingInfo =
3520                mSettings.mCrossProfilePackageInfo.get(userId);
3521        if (sourceForwardingInfo != null) {
3522            int NI = sourceForwardingInfo.size();
3523            for (int i = 0; i < NI; i++) {
3524                int targetUserId = sourceForwardingInfo.keyAt(i);
3525                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3526                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3527                            intent, resolvedType, flags, pkg.activities, targetUserId);
3528                    int NJ = resolveInfos.size();
3529                    for (int j = 0; j < NJ; j++) {
3530                        ResolveInfo resolveInfo = resolveInfos.get(j);
3531                        matchingResolveInfos.add(createForwardingResolveInfo(
3532                                resolveInfo.filter, userId, targetUserId));
3533                    }
3534                }
3535            }
3536        }
3537        return matchingResolveInfos;
3538    }
3539
3540    // Return matching ResolveInfo if any for skip current profile intent filters.
3541    private ResolveInfo queryCrossProfileIntents(
3542            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3543            int flags, int sourceUserId) {
3544        if (matchingFilters != null) {
3545            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3546            // match the same intent. For performance reasons, it is better not to
3547            // run queryIntent twice for the same userId
3548            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3549            int size = matchingFilters.size();
3550            for (int i = 0; i < size; i++) {
3551                CrossProfileIntentFilter filter = matchingFilters.get(i);
3552                int targetUserId = filter.getTargetUserId();
3553                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3554                        && !alreadyTriedUserIds.get(targetUserId)) {
3555                    // Checking if there are activities in the target user that can handle the
3556                    // intent.
3557                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3558                            flags, sourceUserId);
3559                    if (resolveInfo != null) return resolveInfo;
3560                    alreadyTriedUserIds.put(targetUserId, true);
3561                }
3562            }
3563        }
3564        return null;
3565    }
3566
3567    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3568            String resolvedType, int flags, int sourceUserId) {
3569        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3570                resolvedType, flags, filter.getTargetUserId());
3571        if (resultTargetUser != null) {
3572            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3573        }
3574        return null;
3575    }
3576
3577    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3578            int sourceUserId, int targetUserId) {
3579        String className;
3580        if (targetUserId == UserHandle.USER_OWNER) {
3581            className = FORWARD_INTENT_TO_USER_OWNER;
3582        } else {
3583            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3584        }
3585        ComponentName forwardingActivityComponentName = new ComponentName(
3586                mAndroidApplication.packageName, className);
3587        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3588                sourceUserId);
3589        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3590        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3591        forwardingResolveInfo.priority = 0;
3592        forwardingResolveInfo.preferredOrder = 0;
3593        forwardingResolveInfo.match = 0;
3594        forwardingResolveInfo.isDefault = true;
3595        forwardingResolveInfo.filter = filter;
3596        return forwardingResolveInfo;
3597    }
3598
3599    @Override
3600    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3601            Intent[] specifics, String[] specificTypes, Intent intent,
3602            String resolvedType, int flags, int userId) {
3603        if (!sUserManager.exists(userId)) return Collections.emptyList();
3604        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3605                "query intent activity options");
3606        final String resultsAction = intent.getAction();
3607
3608        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3609                | PackageManager.GET_RESOLVED_FILTER, userId);
3610
3611        if (DEBUG_INTENT_MATCHING) {
3612            Log.v(TAG, "Query " + intent + ": " + results);
3613        }
3614
3615        int specificsPos = 0;
3616        int N;
3617
3618        // todo: note that the algorithm used here is O(N^2).  This
3619        // isn't a problem in our current environment, but if we start running
3620        // into situations where we have more than 5 or 10 matches then this
3621        // should probably be changed to something smarter...
3622
3623        // First we go through and resolve each of the specific items
3624        // that were supplied, taking care of removing any corresponding
3625        // duplicate items in the generic resolve list.
3626        if (specifics != null) {
3627            for (int i=0; i<specifics.length; i++) {
3628                final Intent sintent = specifics[i];
3629                if (sintent == null) {
3630                    continue;
3631                }
3632
3633                if (DEBUG_INTENT_MATCHING) {
3634                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3635                }
3636
3637                String action = sintent.getAction();
3638                if (resultsAction != null && resultsAction.equals(action)) {
3639                    // If this action was explicitly requested, then don't
3640                    // remove things that have it.
3641                    action = null;
3642                }
3643
3644                ResolveInfo ri = null;
3645                ActivityInfo ai = null;
3646
3647                ComponentName comp = sintent.getComponent();
3648                if (comp == null) {
3649                    ri = resolveIntent(
3650                        sintent,
3651                        specificTypes != null ? specificTypes[i] : null,
3652                            flags, userId);
3653                    if (ri == null) {
3654                        continue;
3655                    }
3656                    if (ri == mResolveInfo) {
3657                        // ACK!  Must do something better with this.
3658                    }
3659                    ai = ri.activityInfo;
3660                    comp = new ComponentName(ai.applicationInfo.packageName,
3661                            ai.name);
3662                } else {
3663                    ai = getActivityInfo(comp, flags, userId);
3664                    if (ai == null) {
3665                        continue;
3666                    }
3667                }
3668
3669                // Look for any generic query activities that are duplicates
3670                // of this specific one, and remove them from the results.
3671                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3672                N = results.size();
3673                int j;
3674                for (j=specificsPos; j<N; j++) {
3675                    ResolveInfo sri = results.get(j);
3676                    if ((sri.activityInfo.name.equals(comp.getClassName())
3677                            && sri.activityInfo.applicationInfo.packageName.equals(
3678                                    comp.getPackageName()))
3679                        || (action != null && sri.filter.matchAction(action))) {
3680                        results.remove(j);
3681                        if (DEBUG_INTENT_MATCHING) Log.v(
3682                            TAG, "Removing duplicate item from " + j
3683                            + " due to specific " + specificsPos);
3684                        if (ri == null) {
3685                            ri = sri;
3686                        }
3687                        j--;
3688                        N--;
3689                    }
3690                }
3691
3692                // Add this specific item to its proper place.
3693                if (ri == null) {
3694                    ri = new ResolveInfo();
3695                    ri.activityInfo = ai;
3696                }
3697                results.add(specificsPos, ri);
3698                ri.specificIndex = i;
3699                specificsPos++;
3700            }
3701        }
3702
3703        // Now we go through the remaining generic results and remove any
3704        // duplicate actions that are found here.
3705        N = results.size();
3706        for (int i=specificsPos; i<N-1; i++) {
3707            final ResolveInfo rii = results.get(i);
3708            if (rii.filter == null) {
3709                continue;
3710            }
3711
3712            // Iterate over all of the actions of this result's intent
3713            // filter...  typically this should be just one.
3714            final Iterator<String> it = rii.filter.actionsIterator();
3715            if (it == null) {
3716                continue;
3717            }
3718            while (it.hasNext()) {
3719                final String action = it.next();
3720                if (resultsAction != null && resultsAction.equals(action)) {
3721                    // If this action was explicitly requested, then don't
3722                    // remove things that have it.
3723                    continue;
3724                }
3725                for (int j=i+1; j<N; j++) {
3726                    final ResolveInfo rij = results.get(j);
3727                    if (rij.filter != null && rij.filter.hasAction(action)) {
3728                        results.remove(j);
3729                        if (DEBUG_INTENT_MATCHING) Log.v(
3730                            TAG, "Removing duplicate item from " + j
3731                            + " due to action " + action + " at " + i);
3732                        j--;
3733                        N--;
3734                    }
3735                }
3736            }
3737
3738            // If the caller didn't request filter information, drop it now
3739            // so we don't have to marshall/unmarshall it.
3740            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3741                rii.filter = null;
3742            }
3743        }
3744
3745        // Filter out the caller activity if so requested.
3746        if (caller != null) {
3747            N = results.size();
3748            for (int i=0; i<N; i++) {
3749                ActivityInfo ainfo = results.get(i).activityInfo;
3750                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3751                        && caller.getClassName().equals(ainfo.name)) {
3752                    results.remove(i);
3753                    break;
3754                }
3755            }
3756        }
3757
3758        // If the caller didn't request filter information,
3759        // drop them now so we don't have to
3760        // marshall/unmarshall it.
3761        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3762            N = results.size();
3763            for (int i=0; i<N; i++) {
3764                results.get(i).filter = null;
3765            }
3766        }
3767
3768        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3769        return results;
3770    }
3771
3772    @Override
3773    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3774            int userId) {
3775        if (!sUserManager.exists(userId)) return Collections.emptyList();
3776        ComponentName comp = intent.getComponent();
3777        if (comp == null) {
3778            if (intent.getSelector() != null) {
3779                intent = intent.getSelector();
3780                comp = intent.getComponent();
3781            }
3782        }
3783        if (comp != null) {
3784            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3785            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3786            if (ai != null) {
3787                ResolveInfo ri = new ResolveInfo();
3788                ri.activityInfo = ai;
3789                list.add(ri);
3790            }
3791            return list;
3792        }
3793
3794        // reader
3795        synchronized (mPackages) {
3796            String pkgName = intent.getPackage();
3797            if (pkgName == null) {
3798                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3799            }
3800            final PackageParser.Package pkg = mPackages.get(pkgName);
3801            if (pkg != null) {
3802                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3803                        userId);
3804            }
3805            return null;
3806        }
3807    }
3808
3809    @Override
3810    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3811        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3812        if (!sUserManager.exists(userId)) return null;
3813        if (query != null) {
3814            if (query.size() >= 1) {
3815                // If there is more than one service with the same priority,
3816                // just arbitrarily pick the first one.
3817                return query.get(0);
3818            }
3819        }
3820        return null;
3821    }
3822
3823    @Override
3824    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3825            int userId) {
3826        if (!sUserManager.exists(userId)) return Collections.emptyList();
3827        ComponentName comp = intent.getComponent();
3828        if (comp == null) {
3829            if (intent.getSelector() != null) {
3830                intent = intent.getSelector();
3831                comp = intent.getComponent();
3832            }
3833        }
3834        if (comp != null) {
3835            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3836            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3837            if (si != null) {
3838                final ResolveInfo ri = new ResolveInfo();
3839                ri.serviceInfo = si;
3840                list.add(ri);
3841            }
3842            return list;
3843        }
3844
3845        // reader
3846        synchronized (mPackages) {
3847            String pkgName = intent.getPackage();
3848            if (pkgName == null) {
3849                return mServices.queryIntent(intent, resolvedType, flags, userId);
3850            }
3851            final PackageParser.Package pkg = mPackages.get(pkgName);
3852            if (pkg != null) {
3853                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3854                        userId);
3855            }
3856            return null;
3857        }
3858    }
3859
3860    @Override
3861    public List<ResolveInfo> queryIntentContentProviders(
3862            Intent intent, String resolvedType, int flags, int userId) {
3863        if (!sUserManager.exists(userId)) return Collections.emptyList();
3864        ComponentName comp = intent.getComponent();
3865        if (comp == null) {
3866            if (intent.getSelector() != null) {
3867                intent = intent.getSelector();
3868                comp = intent.getComponent();
3869            }
3870        }
3871        if (comp != null) {
3872            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3873            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3874            if (pi != null) {
3875                final ResolveInfo ri = new ResolveInfo();
3876                ri.providerInfo = pi;
3877                list.add(ri);
3878            }
3879            return list;
3880        }
3881
3882        // reader
3883        synchronized (mPackages) {
3884            String pkgName = intent.getPackage();
3885            if (pkgName == null) {
3886                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3887            }
3888            final PackageParser.Package pkg = mPackages.get(pkgName);
3889            if (pkg != null) {
3890                return mProviders.queryIntentForPackage(
3891                        intent, resolvedType, flags, pkg.providers, userId);
3892            }
3893            return null;
3894        }
3895    }
3896
3897    @Override
3898    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3899        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3900
3901        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3902
3903        // writer
3904        synchronized (mPackages) {
3905            ArrayList<PackageInfo> list;
3906            if (listUninstalled) {
3907                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3908                for (PackageSetting ps : mSettings.mPackages.values()) {
3909                    PackageInfo pi;
3910                    if (ps.pkg != null) {
3911                        pi = generatePackageInfo(ps.pkg, flags, userId);
3912                    } else {
3913                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3914                    }
3915                    if (pi != null) {
3916                        list.add(pi);
3917                    }
3918                }
3919            } else {
3920                list = new ArrayList<PackageInfo>(mPackages.size());
3921                for (PackageParser.Package p : mPackages.values()) {
3922                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3923                    if (pi != null) {
3924                        list.add(pi);
3925                    }
3926                }
3927            }
3928
3929            return new ParceledListSlice<PackageInfo>(list);
3930        }
3931    }
3932
3933    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3934            String[] permissions, boolean[] tmp, int flags, int userId) {
3935        int numMatch = 0;
3936        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3937        for (int i=0; i<permissions.length; i++) {
3938            if (gp.grantedPermissions.contains(permissions[i])) {
3939                tmp[i] = true;
3940                numMatch++;
3941            } else {
3942                tmp[i] = false;
3943            }
3944        }
3945        if (numMatch == 0) {
3946            return;
3947        }
3948        PackageInfo pi;
3949        if (ps.pkg != null) {
3950            pi = generatePackageInfo(ps.pkg, flags, userId);
3951        } else {
3952            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3953        }
3954        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3955            if (numMatch == permissions.length) {
3956                pi.requestedPermissions = permissions;
3957            } else {
3958                pi.requestedPermissions = new String[numMatch];
3959                numMatch = 0;
3960                for (int i=0; i<permissions.length; i++) {
3961                    if (tmp[i]) {
3962                        pi.requestedPermissions[numMatch] = permissions[i];
3963                        numMatch++;
3964                    }
3965                }
3966            }
3967        }
3968        list.add(pi);
3969    }
3970
3971    @Override
3972    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3973            String[] permissions, int flags, int userId) {
3974        if (!sUserManager.exists(userId)) return null;
3975        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3976
3977        // writer
3978        synchronized (mPackages) {
3979            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3980            boolean[] tmpBools = new boolean[permissions.length];
3981            if (listUninstalled) {
3982                for (PackageSetting ps : mSettings.mPackages.values()) {
3983                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3984                }
3985            } else {
3986                for (PackageParser.Package pkg : mPackages.values()) {
3987                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3988                    if (ps != null) {
3989                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3990                                userId);
3991                    }
3992                }
3993            }
3994
3995            return new ParceledListSlice<PackageInfo>(list);
3996        }
3997    }
3998
3999    @Override
4000    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4001        if (!sUserManager.exists(userId)) return null;
4002        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4003
4004        // writer
4005        synchronized (mPackages) {
4006            ArrayList<ApplicationInfo> list;
4007            if (listUninstalled) {
4008                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4009                for (PackageSetting ps : mSettings.mPackages.values()) {
4010                    ApplicationInfo ai;
4011                    if (ps.pkg != null) {
4012                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4013                                ps.readUserState(userId), userId);
4014                    } else {
4015                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4016                    }
4017                    if (ai != null) {
4018                        list.add(ai);
4019                    }
4020                }
4021            } else {
4022                list = new ArrayList<ApplicationInfo>(mPackages.size());
4023                for (PackageParser.Package p : mPackages.values()) {
4024                    if (p.mExtras != null) {
4025                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4026                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4027                        if (ai != null) {
4028                            list.add(ai);
4029                        }
4030                    }
4031                }
4032            }
4033
4034            return new ParceledListSlice<ApplicationInfo>(list);
4035        }
4036    }
4037
4038    public List<ApplicationInfo> getPersistentApplications(int flags) {
4039        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4040
4041        // reader
4042        synchronized (mPackages) {
4043            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4044            final int userId = UserHandle.getCallingUserId();
4045            while (i.hasNext()) {
4046                final PackageParser.Package p = i.next();
4047                if (p.applicationInfo != null
4048                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4049                        && (!mSafeMode || isSystemApp(p))) {
4050                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4051                    if (ps != null) {
4052                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4053                                ps.readUserState(userId), userId);
4054                        if (ai != null) {
4055                            finalList.add(ai);
4056                        }
4057                    }
4058                }
4059            }
4060        }
4061
4062        return finalList;
4063    }
4064
4065    @Override
4066    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4067        if (!sUserManager.exists(userId)) return null;
4068        // reader
4069        synchronized (mPackages) {
4070            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4071            PackageSetting ps = provider != null
4072                    ? mSettings.mPackages.get(provider.owner.packageName)
4073                    : null;
4074            return ps != null
4075                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4076                    && (!mSafeMode || (provider.info.applicationInfo.flags
4077                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4078                    ? PackageParser.generateProviderInfo(provider, flags,
4079                            ps.readUserState(userId), userId)
4080                    : null;
4081        }
4082    }
4083
4084    /**
4085     * @deprecated
4086     */
4087    @Deprecated
4088    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4089        // reader
4090        synchronized (mPackages) {
4091            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4092                    .entrySet().iterator();
4093            final int userId = UserHandle.getCallingUserId();
4094            while (i.hasNext()) {
4095                Map.Entry<String, PackageParser.Provider> entry = i.next();
4096                PackageParser.Provider p = entry.getValue();
4097                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4098
4099                if (ps != null && p.syncable
4100                        && (!mSafeMode || (p.info.applicationInfo.flags
4101                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4102                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4103                            ps.readUserState(userId), userId);
4104                    if (info != null) {
4105                        outNames.add(entry.getKey());
4106                        outInfo.add(info);
4107                    }
4108                }
4109            }
4110        }
4111    }
4112
4113    @Override
4114    public List<ProviderInfo> queryContentProviders(String processName,
4115            int uid, int flags) {
4116        ArrayList<ProviderInfo> finalList = null;
4117        // reader
4118        synchronized (mPackages) {
4119            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4120            final int userId = processName != null ?
4121                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4122            while (i.hasNext()) {
4123                final PackageParser.Provider p = i.next();
4124                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4125                if (ps != null && p.info.authority != null
4126                        && (processName == null
4127                                || (p.info.processName.equals(processName)
4128                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4129                        && mSettings.isEnabledLPr(p.info, flags, userId)
4130                        && (!mSafeMode
4131                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4132                    if (finalList == null) {
4133                        finalList = new ArrayList<ProviderInfo>(3);
4134                    }
4135                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4136                            ps.readUserState(userId), userId);
4137                    if (info != null) {
4138                        finalList.add(info);
4139                    }
4140                }
4141            }
4142        }
4143
4144        if (finalList != null) {
4145            Collections.sort(finalList, mProviderInitOrderSorter);
4146        }
4147
4148        return finalList;
4149    }
4150
4151    @Override
4152    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4153            int flags) {
4154        // reader
4155        synchronized (mPackages) {
4156            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4157            return PackageParser.generateInstrumentationInfo(i, flags);
4158        }
4159    }
4160
4161    @Override
4162    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4163            int flags) {
4164        ArrayList<InstrumentationInfo> finalList =
4165            new ArrayList<InstrumentationInfo>();
4166
4167        // reader
4168        synchronized (mPackages) {
4169            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4170            while (i.hasNext()) {
4171                final PackageParser.Instrumentation p = i.next();
4172                if (targetPackage == null
4173                        || targetPackage.equals(p.info.targetPackage)) {
4174                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4175                            flags);
4176                    if (ii != null) {
4177                        finalList.add(ii);
4178                    }
4179                }
4180            }
4181        }
4182
4183        return finalList;
4184    }
4185
4186    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4187        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4188        if (overlays == null) {
4189            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4190            return;
4191        }
4192        for (PackageParser.Package opkg : overlays.values()) {
4193            // Not much to do if idmap fails: we already logged the error
4194            // and we certainly don't want to abort installation of pkg simply
4195            // because an overlay didn't fit properly. For these reasons,
4196            // ignore the return value of createIdmapForPackagePairLI.
4197            createIdmapForPackagePairLI(pkg, opkg);
4198        }
4199    }
4200
4201    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4202            PackageParser.Package opkg) {
4203        if (!opkg.mTrustedOverlay) {
4204            Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " +
4205                    opkg.codePath + ": overlay not trusted");
4206            return false;
4207        }
4208        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4209        if (overlaySet == null) {
4210            Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " +
4211                    opkg.codePath + " but target package has no known overlays");
4212            return false;
4213        }
4214        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4215        // TODO: generate idmap for split APKs
4216        if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) {
4217            Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath);
4218            return false;
4219        }
4220        PackageParser.Package[] overlayArray =
4221            overlaySet.values().toArray(new PackageParser.Package[0]);
4222        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4223            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4224                return p1.mOverlayPriority - p2.mOverlayPriority;
4225            }
4226        };
4227        Arrays.sort(overlayArray, cmp);
4228
4229        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4230        int i = 0;
4231        for (PackageParser.Package p : overlayArray) {
4232            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4233        }
4234        return true;
4235    }
4236
4237    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4238        String[] files = dir.list();
4239        if (files == null) {
4240            Log.d(TAG, "No files in app dir " + dir);
4241            return;
4242        }
4243
4244        if (DEBUG_PACKAGE_SCANNING) {
4245            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4246                    + " flags=0x" + Integer.toHexString(flags));
4247        }
4248
4249        int i;
4250        for (i=0; i<files.length; i++) {
4251            File file = new File(dir, files[i]);
4252            if (!isPackageFilename(files[i])) {
4253                // Ignore entries which are not apk's
4254                continue;
4255            }
4256            PackageParser.Package pkg = scanPackageLI(file,
4257                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4258            // Don't mess around with apps in system partition.
4259            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4260                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4261                // Delete the apk
4262                Slog.w(TAG, "Cleaning up failed install of " + file);
4263                file.delete();
4264            }
4265        }
4266    }
4267
4268    private static File getSettingsProblemFile() {
4269        File dataDir = Environment.getDataDirectory();
4270        File systemDir = new File(dataDir, "system");
4271        File fname = new File(systemDir, "uiderrors.txt");
4272        return fname;
4273    }
4274
4275    static void reportSettingsProblem(int priority, String msg) {
4276        try {
4277            File fname = getSettingsProblemFile();
4278            FileOutputStream out = new FileOutputStream(fname, true);
4279            PrintWriter pw = new FastPrintWriter(out);
4280            SimpleDateFormat formatter = new SimpleDateFormat();
4281            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4282            pw.println(dateString + ": " + msg);
4283            pw.close();
4284            FileUtils.setPermissions(
4285                    fname.toString(),
4286                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4287                    -1, -1);
4288        } catch (java.io.IOException e) {
4289        }
4290        Slog.println(priority, TAG, msg);
4291    }
4292
4293    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4294            PackageParser.Package pkg, File srcFile, int parseFlags) {
4295        if (ps != null
4296                && ps.codePath.equals(srcFile)
4297                && ps.timeStamp == srcFile.lastModified()
4298                && !isCompatSignatureUpdateNeeded(pkg)) {
4299            if (ps.signatures.mSignatures != null
4300                    && ps.signatures.mSignatures.length != 0) {
4301                // Optimization: reuse the existing cached certificates
4302                // if the package appears to be unchanged.
4303                pkg.mSignatures = ps.signatures.mSignatures;
4304                return true;
4305            }
4306
4307            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4308        } else {
4309            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4310        }
4311
4312        try {
4313            pp.collectCertificates(pkg, parseFlags);
4314            pp.collectManifestDigest(pkg);
4315        } catch (PackageParserException e) {
4316            mLastScanError = e.error;
4317            return false;
4318        }
4319        return true;
4320    }
4321
4322    /*
4323     *  Scan a package and return the newly parsed package.
4324     *  Returns null in case of errors and the error code is stored in mLastScanError
4325     */
4326    private PackageParser.Package scanPackageLI(File scanFile,
4327            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4328        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4329        String scanPath = scanFile.getPath();
4330        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4331        parseFlags |= mDefParseFlags;
4332        PackageParser pp = new PackageParser();
4333        pp.setSeparateProcesses(mSeparateProcesses);
4334        pp.setOnlyCoreApps(mOnlyCore);
4335        pp.setDisplayMetrics(mMetrics);
4336
4337        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4338            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4339        }
4340
4341        final PackageParser.Package pkg;
4342        try {
4343            pkg = pp.parseMonolithicPackage(scanFile, parseFlags);
4344        } catch (PackageParserException e) {
4345            mLastScanError = e.error;
4346            return null;
4347        }
4348
4349        PackageSetting ps = null;
4350        PackageSetting updatedPkg;
4351        // reader
4352        synchronized (mPackages) {
4353            // Look to see if we already know about this package.
4354            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4355            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4356                // This package has been renamed to its original name.  Let's
4357                // use that.
4358                ps = mSettings.peekPackageLPr(oldName);
4359            }
4360            // If there was no original package, see one for the real package name.
4361            if (ps == null) {
4362                ps = mSettings.peekPackageLPr(pkg.packageName);
4363            }
4364            // Check to see if this package could be hiding/updating a system
4365            // package.  Must look for it either under the original or real
4366            // package name depending on our state.
4367            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4368            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4369        }
4370        boolean updatedPkgBetter = false;
4371        // First check if this is a system package that may involve an update
4372        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4373            if (ps != null && !ps.codePath.equals(scanFile)) {
4374                // The path has changed from what was last scanned...  check the
4375                // version of the new path against what we have stored to determine
4376                // what to do.
4377                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4378                if (pkg.mVersionCode < ps.versionCode) {
4379                    // The system package has been updated and the code path does not match
4380                    // Ignore entry. Skip it.
4381                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4382                            + " ignored: updated version " + ps.versionCode
4383                            + " better than this " + pkg.mVersionCode);
4384                    if (!updatedPkg.codePath.equals(scanFile)) {
4385                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4386                                + ps.name + " changing from " + updatedPkg.codePathString
4387                                + " to " + scanFile);
4388                        updatedPkg.codePath = scanFile;
4389                        updatedPkg.codePathString = scanFile.toString();
4390                        // This is the point at which we know that the system-disk APK
4391                        // for this package has moved during a reboot (e.g. due to an OTA),
4392                        // so we need to reevaluate it for privilege policy.
4393                        if (locationIsPrivileged(scanFile)) {
4394                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4395                        }
4396                    }
4397                    updatedPkg.pkg = pkg;
4398                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4399                    return null;
4400                } else {
4401                    // The current app on the system partition is better than
4402                    // what we have updated to on the data partition; switch
4403                    // back to the system partition version.
4404                    // At this point, its safely assumed that package installation for
4405                    // apps in system partition will go through. If not there won't be a working
4406                    // version of the app
4407                    // writer
4408                    synchronized (mPackages) {
4409                        // Just remove the loaded entries from package lists.
4410                        mPackages.remove(ps.name);
4411                    }
4412                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4413                            + "reverting from " + ps.codePathString
4414                            + ": new version " + pkg.mVersionCode
4415                            + " better than installed " + ps.versionCode);
4416
4417                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4418                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4419                            getAppInstructionSetFromSettings(ps));
4420                    synchronized (mInstallLock) {
4421                        args.cleanUpResourcesLI();
4422                    }
4423                    synchronized (mPackages) {
4424                        mSettings.enableSystemPackageLPw(ps.name);
4425                    }
4426                    updatedPkgBetter = true;
4427                }
4428            }
4429        }
4430
4431        if (updatedPkg != null) {
4432            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4433            // initially
4434            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4435
4436            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4437            // flag set initially
4438            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4439                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4440            }
4441        }
4442        // Verify certificates against what was last scanned
4443        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4444            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4445            return null;
4446        }
4447
4448        /*
4449         * A new system app appeared, but we already had a non-system one of the
4450         * same name installed earlier.
4451         */
4452        boolean shouldHideSystemApp = false;
4453        if (updatedPkg == null && ps != null
4454                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4455            /*
4456             * Check to make sure the signatures match first. If they don't,
4457             * wipe the installed application and its data.
4458             */
4459            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4460                    != PackageManager.SIGNATURE_MATCH) {
4461                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4462                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4463                ps = null;
4464            } else {
4465                /*
4466                 * If the newly-added system app is an older version than the
4467                 * already installed version, hide it. It will be scanned later
4468                 * and re-added like an update.
4469                 */
4470                if (pkg.mVersionCode < ps.versionCode) {
4471                    shouldHideSystemApp = true;
4472                } else {
4473                    /*
4474                     * The newly found system app is a newer version that the
4475                     * one previously installed. Simply remove the
4476                     * already-installed application and replace it with our own
4477                     * while keeping the application data.
4478                     */
4479                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4480                            + ps.codePathString + ": new version " + pkg.mVersionCode
4481                            + " better than installed " + ps.versionCode);
4482                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4483                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4484                            getAppInstructionSetFromSettings(ps));
4485                    synchronized (mInstallLock) {
4486                        args.cleanUpResourcesLI();
4487                    }
4488                }
4489            }
4490        }
4491
4492        // The apk is forward locked (not public) if its code and resources
4493        // are kept in different files. (except for app in either system or
4494        // vendor path).
4495        // TODO grab this value from PackageSettings
4496        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4497            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4498                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4499            }
4500        }
4501
4502        final String codePath = pkg.codePath;
4503        final String[] splitCodePaths = pkg.splitCodePaths;
4504
4505        String resPath = null;
4506        String[] splitResPaths = null;
4507        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4508            if (ps != null && ps.resourcePathString != null) {
4509                resPath = ps.resourcePathString;
4510                splitResPaths = deriveSplitResPaths(pkg.splitCodePaths);
4511            } else {
4512                // Should not happen at all. Just log an error.
4513                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4514            }
4515        } else {
4516            resPath = pkg.codePath;
4517            splitResPaths = pkg.splitCodePaths;
4518        }
4519
4520        // Set application objects path explicitly.
4521        pkg.applicationInfo.sourceDir = codePath;
4522        pkg.applicationInfo.publicSourceDir = resPath;
4523        pkg.applicationInfo.splitSourceDirs = splitCodePaths;
4524        pkg.applicationInfo.splitPublicSourceDirs = splitResPaths;
4525
4526        // Note that we invoke the following method only if we are about to unpack an application
4527        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4528                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4529
4530        /*
4531         * If the system app should be overridden by a previously installed
4532         * data, hide the system app now and let the /data/app scan pick it up
4533         * again.
4534         */
4535        if (shouldHideSystemApp) {
4536            synchronized (mPackages) {
4537                /*
4538                 * We have to grant systems permissions before we hide, because
4539                 * grantPermissions will assume the package update is trying to
4540                 * expand its permissions.
4541                 */
4542                grantPermissionsLPw(pkg, true);
4543                mSettings.disableSystemPackageLPw(pkg.packageName);
4544            }
4545        }
4546
4547        return scannedPkg;
4548    }
4549
4550    private static String fixProcessName(String defProcessName,
4551            String processName, int uid) {
4552        if (processName == null) {
4553            return defProcessName;
4554        }
4555        return processName;
4556    }
4557
4558    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4559        if (pkgSetting.signatures.mSignatures != null) {
4560            // Already existing package. Make sure signatures match
4561            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4562                    == PackageManager.SIGNATURE_MATCH;
4563            if (!match) {
4564                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4565                        == PackageManager.SIGNATURE_MATCH;
4566            }
4567            if (!match) {
4568                Slog.e(TAG, "Package " + pkg.packageName
4569                        + " signatures do not match the previously installed version; ignoring!");
4570                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4571                return false;
4572            }
4573        }
4574        // Check for shared user signatures
4575        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4576            // Already existing package. Make sure signatures match
4577            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4578                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4579            if (!match) {
4580                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4581                        == PackageManager.SIGNATURE_MATCH;
4582            }
4583            if (!match) {
4584                Slog.e(TAG, "Package " + pkg.packageName
4585                        + " has no signatures that match those in shared user "
4586                        + pkgSetting.sharedUser.name + "; ignoring!");
4587                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4588                return false;
4589            }
4590        }
4591        return true;
4592    }
4593
4594    /**
4595     * Enforces that only the system UID or root's UID can call a method exposed
4596     * via Binder.
4597     *
4598     * @param message used as message if SecurityException is thrown
4599     * @throws SecurityException if the caller is not system or root
4600     */
4601    private static final void enforceSystemOrRoot(String message) {
4602        final int uid = Binder.getCallingUid();
4603        if (uid != Process.SYSTEM_UID && uid != 0) {
4604            throw new SecurityException(message);
4605        }
4606    }
4607
4608    @Override
4609    public void performBootDexOpt() {
4610        enforceSystemOrRoot("Only the system can request dexopt be performed");
4611
4612        final HashSet<PackageParser.Package> pkgs;
4613        synchronized (mPackages) {
4614            pkgs = mDeferredDexOpt;
4615            mDeferredDexOpt = null;
4616        }
4617
4618        if (pkgs != null) {
4619            // Filter out packages that aren't recently used.
4620            //
4621            // The exception is first boot of a non-eng device, which
4622            // should do a full dexopt.
4623            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4624            if (eng || !isFirstBoot()) {
4625                // TODO: add a property to control this?
4626                long dexOptLRUThresholdInMinutes;
4627                if (eng) {
4628                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4629                } else {
4630                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4631                }
4632                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4633
4634                int total = pkgs.size();
4635                int skipped = 0;
4636                long now = System.currentTimeMillis();
4637                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4638                    PackageParser.Package pkg = i.next();
4639                    long then = pkg.mLastPackageUsageTimeInMills;
4640                    if (then + dexOptLRUThresholdInMills < now) {
4641                        if (DEBUG_DEXOPT) {
4642                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4643                                  ((then == 0) ? "never" : new Date(then)));
4644                        }
4645                        i.remove();
4646                        skipped++;
4647                    }
4648                }
4649                if (DEBUG_DEXOPT) {
4650                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4651                }
4652            }
4653
4654            int i = 0;
4655            for (PackageParser.Package pkg : pkgs) {
4656                i++;
4657                if (DEBUG_DEXOPT) {
4658                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4659                          + ": " + pkg.packageName);
4660                }
4661                if (!isFirstBoot()) {
4662                    try {
4663                        ActivityManagerNative.getDefault().showBootMessage(
4664                                mContext.getResources().getString(
4665                                        R.string.android_upgrading_apk,
4666                                        i, pkgs.size()), true);
4667                    } catch (RemoteException e) {
4668                    }
4669                }
4670                PackageParser.Package p = pkg;
4671                synchronized (mInstallLock) {
4672                    if (p.mDexOptNeeded) {
4673                        performDexOptLI(p, false /* force dex */, false /* defer */,
4674                                true /* include dependencies */);
4675                    }
4676                }
4677            }
4678        }
4679    }
4680
4681    @Override
4682    public boolean performDexOpt(String packageName) {
4683        enforceSystemOrRoot("Only the system can request dexopt be performed");
4684        return performDexOpt(packageName, true);
4685    }
4686
4687    public boolean performDexOpt(String packageName, boolean updateUsage) {
4688
4689        PackageParser.Package p;
4690        synchronized (mPackages) {
4691            p = mPackages.get(packageName);
4692            if (p == null) {
4693                return false;
4694            }
4695            if (updateUsage) {
4696                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4697            }
4698            mPackageUsage.write(false);
4699            if (!p.mDexOptNeeded) {
4700                return false;
4701            }
4702        }
4703
4704        synchronized (mInstallLock) {
4705            return performDexOptLI(p, false /* force dex */, false /* defer */,
4706                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4707        }
4708    }
4709
4710    public HashSet<String> getPackagesThatNeedDexOpt() {
4711        HashSet<String> pkgs = null;
4712        synchronized (mPackages) {
4713            for (PackageParser.Package p : mPackages.values()) {
4714                if (DEBUG_DEXOPT) {
4715                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4716                }
4717                if (!p.mDexOptNeeded) {
4718                    continue;
4719                }
4720                if (pkgs == null) {
4721                    pkgs = new HashSet<String>();
4722                }
4723                pkgs.add(p.packageName);
4724            }
4725        }
4726        return pkgs;
4727    }
4728
4729    public void shutdown() {
4730        mPackageUsage.write(true);
4731    }
4732
4733    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4734             boolean forceDex, boolean defer, HashSet<String> done) {
4735        for (int i=0; i<libs.size(); i++) {
4736            PackageParser.Package libPkg;
4737            String libName;
4738            synchronized (mPackages) {
4739                libName = libs.get(i);
4740                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4741                if (lib != null && lib.apk != null) {
4742                    libPkg = mPackages.get(lib.apk);
4743                } else {
4744                    libPkg = null;
4745                }
4746            }
4747            if (libPkg != null && !done.contains(libName)) {
4748                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4749            }
4750        }
4751    }
4752
4753    static final int DEX_OPT_SKIPPED = 0;
4754    static final int DEX_OPT_PERFORMED = 1;
4755    static final int DEX_OPT_DEFERRED = 2;
4756    static final int DEX_OPT_FAILED = -1;
4757
4758    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4759            boolean forceDex, boolean defer, HashSet<String> done) {
4760        final String instructionSet = instructionSetOverride != null ?
4761                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4762
4763        if (done != null) {
4764            done.add(pkg.packageName);
4765            if (pkg.usesLibraries != null) {
4766                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4767            }
4768            if (pkg.usesOptionalLibraries != null) {
4769                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4770            }
4771        }
4772
4773        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4774            final Collection<String> paths = pkg.getAllCodePaths();
4775            for (String path : paths) {
4776                try {
4777                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4778                            pkg.packageName, instructionSet, defer);
4779                    // There are three basic cases here:
4780                    // 1.) we need to dexopt, either because we are forced or it is needed
4781                    // 2.) we are defering a needed dexopt
4782                    // 3.) we are skipping an unneeded dexopt
4783                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4784                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4785                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4786                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4787                                                    pkg.packageName, instructionSet);
4788                        // Note that we ran dexopt, since rerunning will
4789                        // probably just result in an error again.
4790                        pkg.mDexOptNeeded = false;
4791                        if (ret < 0) {
4792                            return DEX_OPT_FAILED;
4793                        }
4794                        return DEX_OPT_PERFORMED;
4795                    }
4796                    if (defer && isDexOptNeededInternal) {
4797                        if (mDeferredDexOpt == null) {
4798                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4799                        }
4800                        mDeferredDexOpt.add(pkg);
4801                        return DEX_OPT_DEFERRED;
4802                    }
4803                    pkg.mDexOptNeeded = false;
4804                    return DEX_OPT_SKIPPED;
4805                } catch (FileNotFoundException e) {
4806                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4807                    return DEX_OPT_FAILED;
4808                } catch (IOException e) {
4809                    Slog.w(TAG, "IOException reading apk: " + path, e);
4810                    return DEX_OPT_FAILED;
4811                } catch (StaleDexCacheError e) {
4812                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4813                    return DEX_OPT_FAILED;
4814                } catch (Exception e) {
4815                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4816                    return DEX_OPT_FAILED;
4817                }
4818            }
4819        }
4820        return DEX_OPT_SKIPPED;
4821    }
4822
4823    private String getAppInstructionSet(ApplicationInfo info) {
4824        String instructionSet = getPreferredInstructionSet();
4825
4826        if (info.cpuAbi != null) {
4827            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4828        }
4829
4830        return instructionSet;
4831    }
4832
4833    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4834        String instructionSet = getPreferredInstructionSet();
4835
4836        if (ps.cpuAbiString != null) {
4837            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4838        }
4839
4840        return instructionSet;
4841    }
4842
4843    private static String getPreferredInstructionSet() {
4844        if (sPreferredInstructionSet == null) {
4845            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4846        }
4847
4848        return sPreferredInstructionSet;
4849    }
4850
4851    private static List<String> getAllInstructionSets() {
4852        final String[] allAbis = Build.SUPPORTED_ABIS;
4853        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4854
4855        for (String abi : allAbis) {
4856            final String instructionSet = VMRuntime.getInstructionSet(abi);
4857            if (!allInstructionSets.contains(instructionSet)) {
4858                allInstructionSets.add(instructionSet);
4859            }
4860        }
4861
4862        return allInstructionSets;
4863    }
4864
4865    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4866            boolean inclDependencies) {
4867        HashSet<String> done;
4868        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4869            done = new HashSet<String>();
4870            done.add(pkg.packageName);
4871        } else {
4872            done = null;
4873        }
4874        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4875    }
4876
4877    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4878        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4879            Slog.w(TAG, "Unable to update from " + oldPkg.name
4880                    + " to " + newPkg.packageName
4881                    + ": old package not in system partition");
4882            return false;
4883        } else if (mPackages.get(oldPkg.name) != null) {
4884            Slog.w(TAG, "Unable to update from " + oldPkg.name
4885                    + " to " + newPkg.packageName
4886                    + ": old package still exists");
4887            return false;
4888        }
4889        return true;
4890    }
4891
4892    File getDataPathForUser(int userId) {
4893        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4894    }
4895
4896    private File getDataPathForPackage(String packageName, int userId) {
4897        /*
4898         * Until we fully support multiple users, return the directory we
4899         * previously would have. The PackageManagerTests will need to be
4900         * revised when this is changed back..
4901         */
4902        if (userId == 0) {
4903            return new File(mAppDataDir, packageName);
4904        } else {
4905            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4906                + File.separator + packageName);
4907        }
4908    }
4909
4910    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4911        int[] users = sUserManager.getUserIds();
4912        int res = mInstaller.install(packageName, uid, uid, seinfo);
4913        if (res < 0) {
4914            return res;
4915        }
4916        for (int user : users) {
4917            if (user != 0) {
4918                res = mInstaller.createUserData(packageName,
4919                        UserHandle.getUid(user, uid), user, seinfo);
4920                if (res < 0) {
4921                    return res;
4922                }
4923            }
4924        }
4925        return res;
4926    }
4927
4928    private int removeDataDirsLI(String packageName) {
4929        int[] users = sUserManager.getUserIds();
4930        int res = 0;
4931        for (int user : users) {
4932            int resInner = mInstaller.remove(packageName, user);
4933            if (resInner < 0) {
4934                res = resInner;
4935            }
4936        }
4937
4938        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4939        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4940        if (!nativeLibraryFile.delete()) {
4941            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4942        }
4943
4944        return res;
4945    }
4946
4947    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4948            PackageParser.Package changingLib) {
4949        if (file.path != null) {
4950            usesLibraryFiles.add(file.path);
4951            return;
4952        }
4953        PackageParser.Package p = mPackages.get(file.apk);
4954        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4955            // If we are doing this while in the middle of updating a library apk,
4956            // then we need to make sure to use that new apk for determining the
4957            // dependencies here.  (We haven't yet finished committing the new apk
4958            // to the package manager state.)
4959            if (p == null || p.packageName.equals(changingLib.packageName)) {
4960                p = changingLib;
4961            }
4962        }
4963        if (p != null) {
4964            usesLibraryFiles.addAll(p.getAllCodePaths());
4965        }
4966    }
4967
4968    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4969            PackageParser.Package changingLib) {
4970        // We might be upgrading from a version of the platform that did not
4971        // provide per-package native library directories for system apps.
4972        // Fix that up here.
4973        if (isSystemApp(pkg)) {
4974            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4975            setInternalAppNativeLibraryPath(pkg, ps);
4976        }
4977
4978        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4979            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4980            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4981            for (int i=0; i<N; i++) {
4982                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4983                if (file == null) {
4984                    Slog.e(TAG, "Package " + pkg.packageName
4985                            + " requires unavailable shared library "
4986                            + pkg.usesLibraries.get(i) + "; failing!");
4987                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4988                    return false;
4989                }
4990                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4991            }
4992            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4993            for (int i=0; i<N; i++) {
4994                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4995                if (file == null) {
4996                    Slog.w(TAG, "Package " + pkg.packageName
4997                            + " desires unavailable shared library "
4998                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4999                } else {
5000                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5001                }
5002            }
5003            N = usesLibraryFiles.size();
5004            if (N > 0) {
5005                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5006            } else {
5007                pkg.usesLibraryFiles = null;
5008            }
5009        }
5010        return true;
5011    }
5012
5013    private static boolean hasString(List<String> list, List<String> which) {
5014        if (list == null) {
5015            return false;
5016        }
5017        for (int i=list.size()-1; i>=0; i--) {
5018            for (int j=which.size()-1; j>=0; j--) {
5019                if (which.get(j).equals(list.get(i))) {
5020                    return true;
5021                }
5022            }
5023        }
5024        return false;
5025    }
5026
5027    private void updateAllSharedLibrariesLPw() {
5028        for (PackageParser.Package pkg : mPackages.values()) {
5029            updateSharedLibrariesLPw(pkg, null);
5030        }
5031    }
5032
5033    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5034            PackageParser.Package changingPkg) {
5035        ArrayList<PackageParser.Package> res = null;
5036        for (PackageParser.Package pkg : mPackages.values()) {
5037            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5038                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5039                if (res == null) {
5040                    res = new ArrayList<PackageParser.Package>();
5041                }
5042                res.add(pkg);
5043                updateSharedLibrariesLPw(pkg, changingPkg);
5044            }
5045        }
5046        return res;
5047    }
5048
5049    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
5050            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
5051        final File scanFile = new File(pkg.codePath);
5052        if (pkg.applicationInfo.sourceDir == null ||
5053                pkg.applicationInfo.publicSourceDir == null) {
5054            // Bail out. The resource and code paths haven't been set.
5055            Slog.w(TAG, " Code and resource paths haven't been set correctly");
5056            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
5057            return null;
5058        }
5059
5060        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5061            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5062        }
5063
5064        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5065            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5066        }
5067
5068        if (mCustomResolverComponentName != null &&
5069                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5070            setUpCustomResolverActivity(pkg);
5071        }
5072
5073        if (pkg.packageName.equals("android")) {
5074            synchronized (mPackages) {
5075                if (mAndroidApplication != null) {
5076                    Slog.w(TAG, "*************************************************");
5077                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5078                    Slog.w(TAG, " file=" + scanFile);
5079                    Slog.w(TAG, "*************************************************");
5080                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5081                    return null;
5082                }
5083
5084                // Set up information for our fall-back user intent resolution activity.
5085                mPlatformPackage = pkg;
5086                pkg.mVersionCode = mSdkVersion;
5087                mAndroidApplication = pkg.applicationInfo;
5088
5089                if (!mResolverReplaced) {
5090                    mResolveActivity.applicationInfo = mAndroidApplication;
5091                    mResolveActivity.name = ResolverActivity.class.getName();
5092                    mResolveActivity.packageName = mAndroidApplication.packageName;
5093                    mResolveActivity.processName = "system:ui";
5094                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5095                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5096                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5097                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5098                    mResolveActivity.exported = true;
5099                    mResolveActivity.enabled = true;
5100                    mResolveInfo.activityInfo = mResolveActivity;
5101                    mResolveInfo.priority = 0;
5102                    mResolveInfo.preferredOrder = 0;
5103                    mResolveInfo.match = 0;
5104                    mResolveComponentName = new ComponentName(
5105                            mAndroidApplication.packageName, mResolveActivity.name);
5106                }
5107            }
5108        }
5109
5110        if (DEBUG_PACKAGE_SCANNING) {
5111            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5112                Log.d(TAG, "Scanning package " + pkg.packageName);
5113        }
5114
5115        if (mPackages.containsKey(pkg.packageName)
5116                || mSharedLibraries.containsKey(pkg.packageName)) {
5117            Slog.w(TAG, "Application package " + pkg.packageName
5118                    + " already installed.  Skipping duplicate.");
5119            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5120            return null;
5121        }
5122
5123        // Initialize package source and resource directories
5124        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
5125        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
5126
5127        SharedUserSetting suid = null;
5128        PackageSetting pkgSetting = null;
5129
5130        if (!isSystemApp(pkg)) {
5131            // Only system apps can use these features.
5132            pkg.mOriginalPackages = null;
5133            pkg.mRealPackage = null;
5134            pkg.mAdoptPermissions = null;
5135        }
5136
5137        // writer
5138        synchronized (mPackages) {
5139            if (pkg.mSharedUserId != null) {
5140                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5141                if (suid == null) {
5142                    Slog.w(TAG, "Creating application package " + pkg.packageName
5143                            + " for shared user failed");
5144                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5145                    return null;
5146                }
5147                if (DEBUG_PACKAGE_SCANNING) {
5148                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5149                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5150                                + "): packages=" + suid.packages);
5151                }
5152            }
5153
5154            // Check if we are renaming from an original package name.
5155            PackageSetting origPackage = null;
5156            String realName = null;
5157            if (pkg.mOriginalPackages != null) {
5158                // This package may need to be renamed to a previously
5159                // installed name.  Let's check on that...
5160                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5161                if (pkg.mOriginalPackages.contains(renamed)) {
5162                    // This package had originally been installed as the
5163                    // original name, and we have already taken care of
5164                    // transitioning to the new one.  Just update the new
5165                    // one to continue using the old name.
5166                    realName = pkg.mRealPackage;
5167                    if (!pkg.packageName.equals(renamed)) {
5168                        // Callers into this function may have already taken
5169                        // care of renaming the package; only do it here if
5170                        // it is not already done.
5171                        pkg.setPackageName(renamed);
5172                    }
5173
5174                } else {
5175                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5176                        if ((origPackage = mSettings.peekPackageLPr(
5177                                pkg.mOriginalPackages.get(i))) != null) {
5178                            // We do have the package already installed under its
5179                            // original name...  should we use it?
5180                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5181                                // New package is not compatible with original.
5182                                origPackage = null;
5183                                continue;
5184                            } else if (origPackage.sharedUser != null) {
5185                                // Make sure uid is compatible between packages.
5186                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5187                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5188                                            + " to " + pkg.packageName + ": old uid "
5189                                            + origPackage.sharedUser.name
5190                                            + " differs from " + pkg.mSharedUserId);
5191                                    origPackage = null;
5192                                    continue;
5193                                }
5194                            } else {
5195                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5196                                        + pkg.packageName + " to old name " + origPackage.name);
5197                            }
5198                            break;
5199                        }
5200                    }
5201                }
5202            }
5203
5204            if (mTransferedPackages.contains(pkg.packageName)) {
5205                Slog.w(TAG, "Package " + pkg.packageName
5206                        + " was transferred to another, but its .apk remains");
5207            }
5208
5209            // Just create the setting, don't add it yet. For already existing packages
5210            // the PkgSetting exists already and doesn't have to be created.
5211            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5212                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5213                    pkg.applicationInfo.cpuAbi,
5214                    pkg.applicationInfo.flags, user, false);
5215            if (pkgSetting == null) {
5216                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5217                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5218                return null;
5219            }
5220
5221            if (pkgSetting.origPackage != null) {
5222                // If we are first transitioning from an original package,
5223                // fix up the new package's name now.  We need to do this after
5224                // looking up the package under its new name, so getPackageLP
5225                // can take care of fiddling things correctly.
5226                pkg.setPackageName(origPackage.name);
5227
5228                // File a report about this.
5229                String msg = "New package " + pkgSetting.realName
5230                        + " renamed to replace old package " + pkgSetting.name;
5231                reportSettingsProblem(Log.WARN, msg);
5232
5233                // Make a note of it.
5234                mTransferedPackages.add(origPackage.name);
5235
5236                // No longer need to retain this.
5237                pkgSetting.origPackage = null;
5238            }
5239
5240            if (realName != null) {
5241                // Make a note of it.
5242                mTransferedPackages.add(pkg.packageName);
5243            }
5244
5245            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5246                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5247            }
5248
5249            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5250                // Check all shared libraries and map to their actual file path.
5251                // We only do this here for apps not on a system dir, because those
5252                // are the only ones that can fail an install due to this.  We
5253                // will take care of the system apps by updating all of their
5254                // library paths after the scan is done.
5255                if (!updateSharedLibrariesLPw(pkg, null)) {
5256                    return null;
5257                }
5258            }
5259
5260            if (mFoundPolicyFile) {
5261                SELinuxMMAC.assignSeinfoValue(pkg);
5262            }
5263
5264            pkg.applicationInfo.uid = pkgSetting.appId;
5265            pkg.mExtras = pkgSetting;
5266
5267            if (!verifySignaturesLP(pkgSetting, pkg)) {
5268                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5269                    return null;
5270                }
5271                // The signature has changed, but this package is in the system
5272                // image...  let's recover!
5273                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5274                // However...  if this package is part of a shared user, but it
5275                // doesn't match the signature of the shared user, let's fail.
5276                // What this means is that you can't change the signatures
5277                // associated with an overall shared user, which doesn't seem all
5278                // that unreasonable.
5279                if (pkgSetting.sharedUser != null) {
5280                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5281                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5282                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5283                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5284                        return null;
5285                    }
5286                }
5287                // File a report about this.
5288                String msg = "System package " + pkg.packageName
5289                        + " signature changed; retaining data.";
5290                reportSettingsProblem(Log.WARN, msg);
5291            }
5292
5293            // Verify that this new package doesn't have any content providers
5294            // that conflict with existing packages.  Only do this if the
5295            // package isn't already installed, since we don't want to break
5296            // things that are installed.
5297            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5298                final int N = pkg.providers.size();
5299                int i;
5300                for (i=0; i<N; i++) {
5301                    PackageParser.Provider p = pkg.providers.get(i);
5302                    if (p.info.authority != null) {
5303                        String names[] = p.info.authority.split(";");
5304                        for (int j = 0; j < names.length; j++) {
5305                            if (mProvidersByAuthority.containsKey(names[j])) {
5306                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5307                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5308                                        " (in package " + pkg.applicationInfo.packageName +
5309                                        ") is already used by "
5310                                        + ((other != null && other.getComponentName() != null)
5311                                                ? other.getComponentName().getPackageName() : "?"));
5312                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5313                                return null;
5314                            }
5315                        }
5316                    }
5317                }
5318            }
5319
5320            if (pkg.mAdoptPermissions != null) {
5321                // This package wants to adopt ownership of permissions from
5322                // another package.
5323                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5324                    final String origName = pkg.mAdoptPermissions.get(i);
5325                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5326                    if (orig != null) {
5327                        if (verifyPackageUpdateLPr(orig, pkg)) {
5328                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5329                                    + pkg.packageName);
5330                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5331                        }
5332                    }
5333                }
5334            }
5335        }
5336
5337        final String pkgName = pkg.packageName;
5338
5339        final long scanFileTime = scanFile.lastModified();
5340        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5341        pkg.applicationInfo.processName = fixProcessName(
5342                pkg.applicationInfo.packageName,
5343                pkg.applicationInfo.processName,
5344                pkg.applicationInfo.uid);
5345
5346        File dataPath;
5347        if (mPlatformPackage == pkg) {
5348            // The system package is special.
5349            dataPath = new File (Environment.getDataDirectory(), "system");
5350            pkg.applicationInfo.dataDir = dataPath.getPath();
5351        } else {
5352            // This is a normal package, need to make its data directory.
5353            dataPath = getDataPathForPackage(pkg.packageName, 0);
5354
5355            boolean uidError = false;
5356
5357            if (dataPath.exists()) {
5358                int currentUid = 0;
5359                try {
5360                    StructStat stat = Os.stat(dataPath.getPath());
5361                    currentUid = stat.st_uid;
5362                } catch (ErrnoException e) {
5363                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5364                }
5365
5366                // If we have mismatched owners for the data path, we have a problem.
5367                if (currentUid != pkg.applicationInfo.uid) {
5368                    boolean recovered = false;
5369                    if (currentUid == 0) {
5370                        // The directory somehow became owned by root.  Wow.
5371                        // This is probably because the system was stopped while
5372                        // installd was in the middle of messing with its libs
5373                        // directory.  Ask installd to fix that.
5374                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5375                                pkg.applicationInfo.uid);
5376                        if (ret >= 0) {
5377                            recovered = true;
5378                            String msg = "Package " + pkg.packageName
5379                                    + " unexpectedly changed to uid 0; recovered to " +
5380                                    + pkg.applicationInfo.uid;
5381                            reportSettingsProblem(Log.WARN, msg);
5382                        }
5383                    }
5384                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5385                            || (scanMode&SCAN_BOOTING) != 0)) {
5386                        // If this is a system app, we can at least delete its
5387                        // current data so the application will still work.
5388                        int ret = removeDataDirsLI(pkgName);
5389                        if (ret >= 0) {
5390                            // TODO: Kill the processes first
5391                            // Old data gone!
5392                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5393                                    ? "System package " : "Third party package ";
5394                            String msg = prefix + pkg.packageName
5395                                    + " has changed from uid: "
5396                                    + currentUid + " to "
5397                                    + pkg.applicationInfo.uid + "; old data erased";
5398                            reportSettingsProblem(Log.WARN, msg);
5399                            recovered = true;
5400
5401                            // And now re-install the app.
5402                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5403                                                   pkg.applicationInfo.seinfo);
5404                            if (ret == -1) {
5405                                // Ack should not happen!
5406                                msg = prefix + pkg.packageName
5407                                        + " could not have data directory re-created after delete.";
5408                                reportSettingsProblem(Log.WARN, msg);
5409                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5410                                return null;
5411                            }
5412                        }
5413                        if (!recovered) {
5414                            mHasSystemUidErrors = true;
5415                        }
5416                    } else if (!recovered) {
5417                        // If we allow this install to proceed, we will be broken.
5418                        // Abort, abort!
5419                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5420                        return null;
5421                    }
5422                    if (!recovered) {
5423                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5424                            + pkg.applicationInfo.uid + "/fs_"
5425                            + currentUid;
5426                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5427                        String msg = "Package " + pkg.packageName
5428                                + " has mismatched uid: "
5429                                + currentUid + " on disk, "
5430                                + pkg.applicationInfo.uid + " in settings";
5431                        // writer
5432                        synchronized (mPackages) {
5433                            mSettings.mReadMessages.append(msg);
5434                            mSettings.mReadMessages.append('\n');
5435                            uidError = true;
5436                            if (!pkgSetting.uidError) {
5437                                reportSettingsProblem(Log.ERROR, msg);
5438                            }
5439                        }
5440                    }
5441                }
5442                pkg.applicationInfo.dataDir = dataPath.getPath();
5443                if (mShouldRestoreconData) {
5444                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5445                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5446                                pkg.applicationInfo.uid);
5447                }
5448            } else {
5449                if (DEBUG_PACKAGE_SCANNING) {
5450                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5451                        Log.v(TAG, "Want this data dir: " + dataPath);
5452                }
5453                //invoke installer to do the actual installation
5454                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5455                                           pkg.applicationInfo.seinfo);
5456                if (ret < 0) {
5457                    // Error from installer
5458                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5459                    return null;
5460                }
5461
5462                if (dataPath.exists()) {
5463                    pkg.applicationInfo.dataDir = dataPath.getPath();
5464                } else {
5465                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5466                    pkg.applicationInfo.dataDir = null;
5467                }
5468            }
5469
5470            /*
5471             * Set the data dir to the default "/data/data/<package name>/lib"
5472             * if we got here without anyone telling us different (e.g., apps
5473             * stored on SD card have their native libraries stored in the ASEC
5474             * container with the APK).
5475             *
5476             * This happens during an upgrade from a package settings file that
5477             * doesn't have a native library path attribute at all.
5478             */
5479            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5480                if (pkgSetting.nativeLibraryPathString == null) {
5481                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5482                } else {
5483                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5484                }
5485            }
5486            pkgSetting.uidError = uidError;
5487        }
5488
5489        final String path = scanFile.getPath();
5490        /* Note: We don't want to unpack the native binaries for
5491         *        system applications, unless they have been updated
5492         *        (the binaries are already under /system/lib).
5493         *        Also, don't unpack libs for apps on the external card
5494         *        since they should have their libraries in the ASEC
5495         *        container already.
5496         *
5497         *        In other words, we're going to unpack the binaries
5498         *        only for non-system apps and system app upgrades.
5499         */
5500        if (pkg.applicationInfo.nativeLibraryDir != null) {
5501            // TODO: extend to extract native code from split APKs
5502            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5503            try {
5504                // Enable gross and lame hacks for apps that are built with old
5505                // SDK tools. We must scan their APKs for renderscript bitcode and
5506                // not launch them if it's present. Don't bother checking on devices
5507                // that don't have 64 bit support.
5508                String[] abiList = Build.SUPPORTED_ABIS;
5509                boolean hasLegacyRenderscriptBitcode = false;
5510                if (abiOverride != null) {
5511                    abiList = new String[] { abiOverride };
5512                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5513                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5514                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5515                    hasLegacyRenderscriptBitcode = true;
5516                }
5517
5518                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5519                final String dataPathString = dataPath.getCanonicalPath();
5520
5521                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5522                    /*
5523                     * Upgrading from a previous version of the OS sometimes
5524                     * leaves native libraries in the /data/data/<app>/lib
5525                     * directory for system apps even when they shouldn't be.
5526                     * Recent changes in the JNI library search path
5527                     * necessitates we remove those to match previous behavior.
5528                     */
5529                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5530                        Log.i(TAG, "removed obsolete native libraries for system package "
5531                                + path);
5532                    }
5533                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5534                        pkg.applicationInfo.cpuAbi = abiList[0];
5535                        pkgSetting.cpuAbiString = abiList[0];
5536                    } else {
5537                        setInternalAppAbi(pkg, pkgSetting);
5538                    }
5539                } else {
5540                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5541                        /*
5542                        * Update native library dir if it starts with
5543                        * /data/data
5544                        */
5545                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5546                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5547                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5548                        }
5549
5550                        try {
5551                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5552                                    nativeLibraryDir, abiList);
5553                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5554                                Slog.e(TAG, "Unable to copy native libraries");
5555                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5556                                return null;
5557                            }
5558
5559                            // We've successfully copied native libraries across, so we make a
5560                            // note of what ABI we're using
5561                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5562                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5563                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5564                                pkg.applicationInfo.cpuAbi = abiList[0];
5565                            } else {
5566                                pkg.applicationInfo.cpuAbi = null;
5567                            }
5568                        } catch (IOException e) {
5569                            Slog.e(TAG, "Unable to copy native libraries", e);
5570                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5571                            return null;
5572                        }
5573                    } else {
5574                        // We don't have to copy the shared libraries if we're in the ASEC container
5575                        // but we still need to scan the file to figure out what ABI the app needs.
5576                        //
5577                        // TODO: This duplicates work done in the default container service. It's possible
5578                        // to clean this up but we'll need to change the interface between this service
5579                        // and IMediaContainerService (but doing so will spread this logic out, rather
5580                        // than centralizing it).
5581                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5582                        if (abi >= 0) {
5583                            pkg.applicationInfo.cpuAbi = abiList[abi];
5584                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5585                            // Note that (non upgraded) system apps will not have any native
5586                            // libraries bundled in their APK, but we're guaranteed not to be
5587                            // such an app at this point.
5588                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5589                                pkg.applicationInfo.cpuAbi = abiList[0];
5590                            } else {
5591                                pkg.applicationInfo.cpuAbi = null;
5592                            }
5593                        } else {
5594                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5595                            return null;
5596                        }
5597                    }
5598
5599                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5600                    final int[] userIds = sUserManager.getUserIds();
5601                    synchronized (mInstallLock) {
5602                        for (int userId : userIds) {
5603                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5604                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5605                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5606                                        + ")");
5607                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5608                                return null;
5609                            }
5610                        }
5611                    }
5612                }
5613
5614                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5615            } catch (IOException ioe) {
5616                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5617            } finally {
5618                handle.close();
5619            }
5620        }
5621
5622        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5623            // We don't do this here during boot because we can do it all
5624            // at once after scanning all existing packages.
5625            //
5626            // We also do this *before* we perform dexopt on this package, so that
5627            // we can avoid redundant dexopts, and also to make sure we've got the
5628            // code and package path correct.
5629            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5630                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5631                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5632                return null;
5633            }
5634        }
5635
5636        if ((scanMode&SCAN_NO_DEX) == 0) {
5637            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5638                    == DEX_OPT_FAILED) {
5639                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5640                    removeDataDirsLI(pkg.packageName);
5641                }
5642
5643                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5644                return null;
5645            }
5646        }
5647
5648        if (mFactoryTest && pkg.requestedPermissions.contains(
5649                android.Manifest.permission.FACTORY_TEST)) {
5650            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5651        }
5652
5653        ArrayList<PackageParser.Package> clientLibPkgs = null;
5654
5655        // writer
5656        synchronized (mPackages) {
5657            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5658                // Only system apps can add new shared libraries.
5659                if (pkg.libraryNames != null) {
5660                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5661                        String name = pkg.libraryNames.get(i);
5662                        boolean allowed = false;
5663                        if (isUpdatedSystemApp(pkg)) {
5664                            // New library entries can only be added through the
5665                            // system image.  This is important to get rid of a lot
5666                            // of nasty edge cases: for example if we allowed a non-
5667                            // system update of the app to add a library, then uninstalling
5668                            // the update would make the library go away, and assumptions
5669                            // we made such as through app install filtering would now
5670                            // have allowed apps on the device which aren't compatible
5671                            // with it.  Better to just have the restriction here, be
5672                            // conservative, and create many fewer cases that can negatively
5673                            // impact the user experience.
5674                            final PackageSetting sysPs = mSettings
5675                                    .getDisabledSystemPkgLPr(pkg.packageName);
5676                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5677                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5678                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5679                                        allowed = true;
5680                                        allowed = true;
5681                                        break;
5682                                    }
5683                                }
5684                            }
5685                        } else {
5686                            allowed = true;
5687                        }
5688                        if (allowed) {
5689                            if (!mSharedLibraries.containsKey(name)) {
5690                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5691                            } else if (!name.equals(pkg.packageName)) {
5692                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5693                                        + name + " already exists; skipping");
5694                            }
5695                        } else {
5696                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5697                                    + name + " that is not declared on system image; skipping");
5698                        }
5699                    }
5700                    if ((scanMode&SCAN_BOOTING) == 0) {
5701                        // If we are not booting, we need to update any applications
5702                        // that are clients of our shared library.  If we are booting,
5703                        // this will all be done once the scan is complete.
5704                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5705                    }
5706                }
5707            }
5708        }
5709
5710        // We also need to dexopt any apps that are dependent on this library.  Note that
5711        // if these fail, we should abort the install since installing the library will
5712        // result in some apps being broken.
5713        if (clientLibPkgs != null) {
5714            if ((scanMode&SCAN_NO_DEX) == 0) {
5715                for (int i=0; i<clientLibPkgs.size(); i++) {
5716                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5717                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5718                            == DEX_OPT_FAILED) {
5719                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5720                            removeDataDirsLI(pkg.packageName);
5721                        }
5722
5723                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5724                        return null;
5725                    }
5726                }
5727            }
5728        }
5729
5730        // Request the ActivityManager to kill the process(only for existing packages)
5731        // so that we do not end up in a confused state while the user is still using the older
5732        // version of the application while the new one gets installed.
5733        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5734            // If the package lives in an asec, tell everyone that the container is going
5735            // away so they can clean up any references to its resources (which would prevent
5736            // vold from being able to unmount the asec)
5737            if (isForwardLocked(pkg) || isExternal(pkg)) {
5738                if (DEBUG_INSTALL) {
5739                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5740                }
5741                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5742                final ArrayList<String> pkgList = new ArrayList<String>(1);
5743                pkgList.add(pkg.applicationInfo.packageName);
5744                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5745            }
5746
5747            // Post the request that it be killed now that the going-away broadcast is en route
5748            killApplication(pkg.applicationInfo.packageName,
5749                        pkg.applicationInfo.uid, "update pkg");
5750        }
5751
5752        // Also need to kill any apps that are dependent on the library.
5753        if (clientLibPkgs != null) {
5754            for (int i=0; i<clientLibPkgs.size(); i++) {
5755                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5756                killApplication(clientPkg.applicationInfo.packageName,
5757                        clientPkg.applicationInfo.uid, "update lib");
5758            }
5759        }
5760
5761        // writer
5762        synchronized (mPackages) {
5763            // We don't expect installation to fail beyond this point,
5764            if ((scanMode&SCAN_MONITOR) != 0) {
5765                mAppDirs.put(pkg.codePath, pkg);
5766            }
5767            // Add the new setting to mSettings
5768            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5769            // Add the new setting to mPackages
5770            mPackages.put(pkg.applicationInfo.packageName, pkg);
5771            // Make sure we don't accidentally delete its data.
5772            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5773            while (iter.hasNext()) {
5774                PackageCleanItem item = iter.next();
5775                if (pkgName.equals(item.packageName)) {
5776                    iter.remove();
5777                }
5778            }
5779
5780            // Take care of first install / last update times.
5781            if (currentTime != 0) {
5782                if (pkgSetting.firstInstallTime == 0) {
5783                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5784                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5785                    pkgSetting.lastUpdateTime = currentTime;
5786                }
5787            } else if (pkgSetting.firstInstallTime == 0) {
5788                // We need *something*.  Take time time stamp of the file.
5789                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5790            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5791                if (scanFileTime != pkgSetting.timeStamp) {
5792                    // A package on the system image has changed; consider this
5793                    // to be an update.
5794                    pkgSetting.lastUpdateTime = scanFileTime;
5795                }
5796            }
5797
5798            // Add the package's KeySets to the global KeySetManager
5799            KeySetManager ksm = mSettings.mKeySetManager;
5800            try {
5801                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5802                if (pkg.mKeySetMapping != null) {
5803                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5804                            pkg.mKeySetMapping.entrySet()) {
5805                        if (entry.getValue() != null) {
5806                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5807                                entry.getValue(), entry.getKey());
5808                        }
5809                    }
5810                }
5811            } catch (NullPointerException e) {
5812                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5813            } catch (IllegalArgumentException e) {
5814                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5815            }
5816
5817            int N = pkg.providers.size();
5818            StringBuilder r = null;
5819            int i;
5820            for (i=0; i<N; i++) {
5821                PackageParser.Provider p = pkg.providers.get(i);
5822                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5823                        p.info.processName, pkg.applicationInfo.uid);
5824                mProviders.addProvider(p);
5825                p.syncable = p.info.isSyncable;
5826                if (p.info.authority != null) {
5827                    String names[] = p.info.authority.split(";");
5828                    p.info.authority = null;
5829                    for (int j = 0; j < names.length; j++) {
5830                        if (j == 1 && p.syncable) {
5831                            // We only want the first authority for a provider to possibly be
5832                            // syncable, so if we already added this provider using a different
5833                            // authority clear the syncable flag. We copy the provider before
5834                            // changing it because the mProviders object contains a reference
5835                            // to a provider that we don't want to change.
5836                            // Only do this for the second authority since the resulting provider
5837                            // object can be the same for all future authorities for this provider.
5838                            p = new PackageParser.Provider(p);
5839                            p.syncable = false;
5840                        }
5841                        if (!mProvidersByAuthority.containsKey(names[j])) {
5842                            mProvidersByAuthority.put(names[j], p);
5843                            if (p.info.authority == null) {
5844                                p.info.authority = names[j];
5845                            } else {
5846                                p.info.authority = p.info.authority + ";" + names[j];
5847                            }
5848                            if (DEBUG_PACKAGE_SCANNING) {
5849                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5850                                    Log.d(TAG, "Registered content provider: " + names[j]
5851                                            + ", className = " + p.info.name + ", isSyncable = "
5852                                            + p.info.isSyncable);
5853                            }
5854                        } else {
5855                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5856                            Slog.w(TAG, "Skipping provider name " + names[j] +
5857                                    " (in package " + pkg.applicationInfo.packageName +
5858                                    "): name already used by "
5859                                    + ((other != null && other.getComponentName() != null)
5860                                            ? other.getComponentName().getPackageName() : "?"));
5861                        }
5862                    }
5863                }
5864                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5865                    if (r == null) {
5866                        r = new StringBuilder(256);
5867                    } else {
5868                        r.append(' ');
5869                    }
5870                    r.append(p.info.name);
5871                }
5872            }
5873            if (r != null) {
5874                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5875            }
5876
5877            N = pkg.services.size();
5878            r = null;
5879            for (i=0; i<N; i++) {
5880                PackageParser.Service s = pkg.services.get(i);
5881                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5882                        s.info.processName, pkg.applicationInfo.uid);
5883                mServices.addService(s);
5884                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5885                    if (r == null) {
5886                        r = new StringBuilder(256);
5887                    } else {
5888                        r.append(' ');
5889                    }
5890                    r.append(s.info.name);
5891                }
5892            }
5893            if (r != null) {
5894                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5895            }
5896
5897            N = pkg.receivers.size();
5898            r = null;
5899            for (i=0; i<N; i++) {
5900                PackageParser.Activity a = pkg.receivers.get(i);
5901                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5902                        a.info.processName, pkg.applicationInfo.uid);
5903                mReceivers.addActivity(a, "receiver");
5904                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5905                    if (r == null) {
5906                        r = new StringBuilder(256);
5907                    } else {
5908                        r.append(' ');
5909                    }
5910                    r.append(a.info.name);
5911                }
5912            }
5913            if (r != null) {
5914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5915            }
5916
5917            N = pkg.activities.size();
5918            r = null;
5919            for (i=0; i<N; i++) {
5920                PackageParser.Activity a = pkg.activities.get(i);
5921                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5922                        a.info.processName, pkg.applicationInfo.uid);
5923                mActivities.addActivity(a, "activity");
5924                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5925                    if (r == null) {
5926                        r = new StringBuilder(256);
5927                    } else {
5928                        r.append(' ');
5929                    }
5930                    r.append(a.info.name);
5931                }
5932            }
5933            if (r != null) {
5934                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5935            }
5936
5937            N = pkg.permissionGroups.size();
5938            r = null;
5939            for (i=0; i<N; i++) {
5940                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5941                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5942                if (cur == null) {
5943                    mPermissionGroups.put(pg.info.name, pg);
5944                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5945                        if (r == null) {
5946                            r = new StringBuilder(256);
5947                        } else {
5948                            r.append(' ');
5949                        }
5950                        r.append(pg.info.name);
5951                    }
5952                } else {
5953                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5954                            + pg.info.packageName + " ignored: original from "
5955                            + cur.info.packageName);
5956                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5957                        if (r == null) {
5958                            r = new StringBuilder(256);
5959                        } else {
5960                            r.append(' ');
5961                        }
5962                        r.append("DUP:");
5963                        r.append(pg.info.name);
5964                    }
5965                }
5966            }
5967            if (r != null) {
5968                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5969            }
5970
5971            N = pkg.permissions.size();
5972            r = null;
5973            for (i=0; i<N; i++) {
5974                PackageParser.Permission p = pkg.permissions.get(i);
5975                HashMap<String, BasePermission> permissionMap =
5976                        p.tree ? mSettings.mPermissionTrees
5977                        : mSettings.mPermissions;
5978                p.group = mPermissionGroups.get(p.info.group);
5979                if (p.info.group == null || p.group != null) {
5980                    BasePermission bp = permissionMap.get(p.info.name);
5981                    if (bp == null) {
5982                        bp = new BasePermission(p.info.name, p.info.packageName,
5983                                BasePermission.TYPE_NORMAL);
5984                        permissionMap.put(p.info.name, bp);
5985                    }
5986                    if (bp.perm == null) {
5987                        if (bp.sourcePackage != null
5988                                && !bp.sourcePackage.equals(p.info.packageName)) {
5989                            // If this is a permission that was formerly defined by a non-system
5990                            // app, but is now defined by a system app (following an upgrade),
5991                            // discard the previous declaration and consider the system's to be
5992                            // canonical.
5993                            if (isSystemApp(p.owner)) {
5994                                String msg = "New decl " + p.owner + " of permission  "
5995                                        + p.info.name + " is system";
5996                                reportSettingsProblem(Log.WARN, msg);
5997                                bp.sourcePackage = null;
5998                            }
5999                        }
6000                        if (bp.sourcePackage == null
6001                                || bp.sourcePackage.equals(p.info.packageName)) {
6002                            BasePermission tree = findPermissionTreeLP(p.info.name);
6003                            if (tree == null
6004                                    || tree.sourcePackage.equals(p.info.packageName)) {
6005                                bp.packageSetting = pkgSetting;
6006                                bp.perm = p;
6007                                bp.uid = pkg.applicationInfo.uid;
6008                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6009                                    if (r == null) {
6010                                        r = new StringBuilder(256);
6011                                    } else {
6012                                        r.append(' ');
6013                                    }
6014                                    r.append(p.info.name);
6015                                }
6016                            } else {
6017                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6018                                        + p.info.packageName + " ignored: base tree "
6019                                        + tree.name + " is from package "
6020                                        + tree.sourcePackage);
6021                            }
6022                        } else {
6023                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6024                                    + p.info.packageName + " ignored: original from "
6025                                    + bp.sourcePackage);
6026                        }
6027                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6028                        if (r == null) {
6029                            r = new StringBuilder(256);
6030                        } else {
6031                            r.append(' ');
6032                        }
6033                        r.append("DUP:");
6034                        r.append(p.info.name);
6035                    }
6036                    if (bp.perm == p) {
6037                        bp.protectionLevel = p.info.protectionLevel;
6038                    }
6039                } else {
6040                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6041                            + p.info.packageName + " ignored: no group "
6042                            + p.group);
6043                }
6044            }
6045            if (r != null) {
6046                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6047            }
6048
6049            N = pkg.instrumentation.size();
6050            r = null;
6051            for (i=0; i<N; i++) {
6052                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6053                a.info.packageName = pkg.applicationInfo.packageName;
6054                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6055                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6056                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6057                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6058                a.info.dataDir = pkg.applicationInfo.dataDir;
6059                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6060                mInstrumentation.put(a.getComponentName(), a);
6061                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6062                    if (r == null) {
6063                        r = new StringBuilder(256);
6064                    } else {
6065                        r.append(' ');
6066                    }
6067                    r.append(a.info.name);
6068                }
6069            }
6070            if (r != null) {
6071                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6072            }
6073
6074            if (pkg.protectedBroadcasts != null) {
6075                N = pkg.protectedBroadcasts.size();
6076                for (i=0; i<N; i++) {
6077                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6078                }
6079            }
6080
6081            pkgSetting.setTimeStamp(scanFileTime);
6082
6083            // Create idmap files for pairs of (packages, overlay packages).
6084            // Note: "android", ie framework-res.apk, is handled by native layers.
6085            if (pkg.mOverlayTarget != null) {
6086                // This is an overlay package.
6087                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6088                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6089                        mOverlays.put(pkg.mOverlayTarget,
6090                                new HashMap<String, PackageParser.Package>());
6091                    }
6092                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6093                    map.put(pkg.packageName, pkg);
6094                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6095                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6096                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
6097                        return null;
6098                    }
6099                }
6100            } else if (mOverlays.containsKey(pkg.packageName) &&
6101                    !pkg.packageName.equals("android")) {
6102                // This is a regular package, with one or more known overlay packages.
6103                createIdmapsForPackageLI(pkg);
6104            }
6105        }
6106
6107        return pkg;
6108    }
6109
6110    /**
6111     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6112     * i.e, so that all packages can be run inside a single process if required.
6113     *
6114     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6115     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6116     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6117     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6118     * updating a package that belongs to a shared user.
6119     */
6120    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6121            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6122        String requiredInstructionSet = null;
6123        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
6124            requiredInstructionSet = VMRuntime.getInstructionSet(
6125                     scannedPackage.applicationInfo.cpuAbi);
6126        }
6127
6128        PackageSetting requirer = null;
6129        for (PackageSetting ps : packagesForUser) {
6130            // If packagesForUser contains scannedPackage, we skip it. This will happen
6131            // when scannedPackage is an update of an existing package. Without this check,
6132            // we will never be able to change the ABI of any package belonging to a shared
6133            // user, even if it's compatible with other packages.
6134            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6135                if (ps.cpuAbiString == null) {
6136                    continue;
6137                }
6138
6139                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6140                if (requiredInstructionSet != null) {
6141                    if (!instructionSet.equals(requiredInstructionSet)) {
6142                        // We have a mismatch between instruction sets (say arm vs arm64).
6143                        // bail out.
6144                        String errorMessage = "Instruction set mismatch, "
6145                                + ((requirer == null) ? "[caller]" : requirer)
6146                                + " requires " + requiredInstructionSet + " whereas " + ps
6147                                + " requires " + instructionSet;
6148                        Slog.e(TAG, errorMessage);
6149
6150                        reportSettingsProblem(Log.WARN, errorMessage);
6151                        // Give up, don't bother making any other changes to the package settings.
6152                        return false;
6153                    }
6154                } else {
6155                    requiredInstructionSet = instructionSet;
6156                    requirer = ps;
6157                }
6158            }
6159        }
6160
6161        if (requiredInstructionSet != null) {
6162            String adjustedAbi;
6163            if (requirer != null) {
6164                // requirer != null implies that either scannedPackage was null or that scannedPackage
6165                // did not require an ABI, in which case we have to adjust scannedPackage to match
6166                // the ABI of the set (which is the same as requirer's ABI)
6167                adjustedAbi = requirer.cpuAbiString;
6168                if (scannedPackage != null) {
6169                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6170                }
6171            } else {
6172                // requirer == null implies that we're updating all ABIs in the set to
6173                // match scannedPackage.
6174                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6175            }
6176
6177            for (PackageSetting ps : packagesForUser) {
6178                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6179                    if (ps.cpuAbiString != null) {
6180                        continue;
6181                    }
6182
6183                    ps.cpuAbiString = adjustedAbi;
6184                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6185                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6186                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6187
6188                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6189                            ps.cpuAbiString = null;
6190                            ps.pkg.applicationInfo.cpuAbi = null;
6191                            return false;
6192                        } else {
6193                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6194                        }
6195                    }
6196                }
6197            }
6198        }
6199
6200        return true;
6201    }
6202
6203    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6204        synchronized (mPackages) {
6205            mResolverReplaced = true;
6206            // Set up information for custom user intent resolution activity.
6207            mResolveActivity.applicationInfo = pkg.applicationInfo;
6208            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6209            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6210            mResolveActivity.processName = null;
6211            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6212            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6213                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6214            mResolveActivity.theme = 0;
6215            mResolveActivity.exported = true;
6216            mResolveActivity.enabled = true;
6217            mResolveInfo.activityInfo = mResolveActivity;
6218            mResolveInfo.priority = 0;
6219            mResolveInfo.preferredOrder = 0;
6220            mResolveInfo.match = 0;
6221            mResolveComponentName = mCustomResolverComponentName;
6222            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6223                    mResolveComponentName);
6224        }
6225    }
6226
6227    private String calculateApkRoot(final String codePathString) {
6228        final File codePath = new File(codePathString);
6229        final File codeRoot;
6230        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6231            codeRoot = Environment.getRootDirectory();
6232        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6233            codeRoot = Environment.getOemDirectory();
6234        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6235            codeRoot = Environment.getVendorDirectory();
6236        } else {
6237            // Unrecognized code path; take its top real segment as the apk root:
6238            // e.g. /something/app/blah.apk => /something
6239            try {
6240                File f = codePath.getCanonicalFile();
6241                File parent = f.getParentFile();    // non-null because codePath is a file
6242                File tmp;
6243                while ((tmp = parent.getParentFile()) != null) {
6244                    f = parent;
6245                    parent = tmp;
6246                }
6247                codeRoot = f;
6248                Slog.w(TAG, "Unrecognized code path "
6249                        + codePath + " - using " + codeRoot);
6250            } catch (IOException e) {
6251                // Can't canonicalize the lib path -- shenanigans?
6252                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6253                return Environment.getRootDirectory().getPath();
6254            }
6255        }
6256        return codeRoot.getPath();
6257    }
6258
6259    // This is the initial scan-time determination of how to handle a given
6260    // package for purposes of native library location.
6261    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6262            PackageSetting pkgSetting) {
6263        // "bundled" here means system-installed with no overriding update
6264        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6265        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6266        final File libDir;
6267        if (bundledApk) {
6268            // If "/system/lib64/apkname" exists, assume that is the per-package
6269            // native library directory to use; otherwise use "/system/lib/apkname".
6270            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6271            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6272            File packLib64 = new File(lib64, apkName);
6273            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6274        } else {
6275            libDir = mAppLibInstallDir;
6276        }
6277        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6278        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6279        // pkgSetting might be null during rescan following uninstall of updates
6280        // to a bundled app, so accommodate that possibility.  The settings in
6281        // that case will be established later from the parsed package.
6282        if (pkgSetting != null) {
6283            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6284        }
6285    }
6286
6287    // Deduces the required ABI of an upgraded system app.
6288    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6289        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6290        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6291
6292        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6293        // or similar.
6294        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6295        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6296
6297        // Assume that the bundled native libraries always correspond to the
6298        // most preferred 32 or 64 bit ABI.
6299        if (lib64.exists()) {
6300            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6301            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6302        } else if (lib.exists()) {
6303            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6304            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6305        } else {
6306            // This is the case where the app has no native code.
6307            pkg.applicationInfo.cpuAbi = null;
6308            pkgSetting.cpuAbiString = null;
6309        }
6310    }
6311
6312    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6313            final File nativeLibraryDir, String[] abiList) throws IOException {
6314        if (!nativeLibraryDir.isDirectory()) {
6315            nativeLibraryDir.delete();
6316
6317            if (!nativeLibraryDir.mkdir()) {
6318                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6319            }
6320
6321            try {
6322                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6323            } catch (ErrnoException e) {
6324                throw new IOException("Cannot chmod native library directory "
6325                        + nativeLibraryDir.getPath(), e);
6326            }
6327        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6328            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6329        }
6330
6331        /*
6332         * If this is an internal application or our nativeLibraryPath points to
6333         * the app-lib directory, unpack the libraries if necessary.
6334         */
6335        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6336        if (abi >= 0) {
6337            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6338                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6339            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6340                return copyRet;
6341            }
6342        }
6343
6344        return abi;
6345    }
6346
6347    private void killApplication(String pkgName, int appId, String reason) {
6348        // Request the ActivityManager to kill the process(only for existing packages)
6349        // so that we do not end up in a confused state while the user is still using the older
6350        // version of the application while the new one gets installed.
6351        IActivityManager am = ActivityManagerNative.getDefault();
6352        if (am != null) {
6353            try {
6354                am.killApplicationWithAppId(pkgName, appId, reason);
6355            } catch (RemoteException e) {
6356            }
6357        }
6358    }
6359
6360    void removePackageLI(PackageSetting ps, boolean chatty) {
6361        if (DEBUG_INSTALL) {
6362            if (chatty)
6363                Log.d(TAG, "Removing package " + ps.name);
6364        }
6365
6366        // writer
6367        synchronized (mPackages) {
6368            mPackages.remove(ps.name);
6369            if (ps.codePathString != null) {
6370                mAppDirs.remove(ps.codePathString);
6371            }
6372
6373            final PackageParser.Package pkg = ps.pkg;
6374            if (pkg != null) {
6375                cleanPackageDataStructuresLILPw(pkg, chatty);
6376            }
6377        }
6378    }
6379
6380    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6381        if (DEBUG_INSTALL) {
6382            if (chatty)
6383                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6384        }
6385
6386        // writer
6387        synchronized (mPackages) {
6388            mPackages.remove(pkg.applicationInfo.packageName);
6389            if (pkg.codePath != null) {
6390                mAppDirs.remove(pkg.codePath);
6391            }
6392            cleanPackageDataStructuresLILPw(pkg, chatty);
6393        }
6394    }
6395
6396    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6397        int N = pkg.providers.size();
6398        StringBuilder r = null;
6399        int i;
6400        for (i=0; i<N; i++) {
6401            PackageParser.Provider p = pkg.providers.get(i);
6402            mProviders.removeProvider(p);
6403            if (p.info.authority == null) {
6404
6405                /* There was another ContentProvider with this authority when
6406                 * this app was installed so this authority is null,
6407                 * Ignore it as we don't have to unregister the provider.
6408                 */
6409                continue;
6410            }
6411            String names[] = p.info.authority.split(";");
6412            for (int j = 0; j < names.length; j++) {
6413                if (mProvidersByAuthority.get(names[j]) == p) {
6414                    mProvidersByAuthority.remove(names[j]);
6415                    if (DEBUG_REMOVE) {
6416                        if (chatty)
6417                            Log.d(TAG, "Unregistered content provider: " + names[j]
6418                                    + ", className = " + p.info.name + ", isSyncable = "
6419                                    + p.info.isSyncable);
6420                    }
6421                }
6422            }
6423            if (DEBUG_REMOVE && chatty) {
6424                if (r == null) {
6425                    r = new StringBuilder(256);
6426                } else {
6427                    r.append(' ');
6428                }
6429                r.append(p.info.name);
6430            }
6431        }
6432        if (r != null) {
6433            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6434        }
6435
6436        N = pkg.services.size();
6437        r = null;
6438        for (i=0; i<N; i++) {
6439            PackageParser.Service s = pkg.services.get(i);
6440            mServices.removeService(s);
6441            if (chatty) {
6442                if (r == null) {
6443                    r = new StringBuilder(256);
6444                } else {
6445                    r.append(' ');
6446                }
6447                r.append(s.info.name);
6448            }
6449        }
6450        if (r != null) {
6451            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6452        }
6453
6454        N = pkg.receivers.size();
6455        r = null;
6456        for (i=0; i<N; i++) {
6457            PackageParser.Activity a = pkg.receivers.get(i);
6458            mReceivers.removeActivity(a, "receiver");
6459            if (DEBUG_REMOVE && chatty) {
6460                if (r == null) {
6461                    r = new StringBuilder(256);
6462                } else {
6463                    r.append(' ');
6464                }
6465                r.append(a.info.name);
6466            }
6467        }
6468        if (r != null) {
6469            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6470        }
6471
6472        N = pkg.activities.size();
6473        r = null;
6474        for (i=0; i<N; i++) {
6475            PackageParser.Activity a = pkg.activities.get(i);
6476            mActivities.removeActivity(a, "activity");
6477            if (DEBUG_REMOVE && chatty) {
6478                if (r == null) {
6479                    r = new StringBuilder(256);
6480                } else {
6481                    r.append(' ');
6482                }
6483                r.append(a.info.name);
6484            }
6485        }
6486        if (r != null) {
6487            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6488        }
6489
6490        N = pkg.permissions.size();
6491        r = null;
6492        for (i=0; i<N; i++) {
6493            PackageParser.Permission p = pkg.permissions.get(i);
6494            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6495            if (bp == null) {
6496                bp = mSettings.mPermissionTrees.get(p.info.name);
6497            }
6498            if (bp != null && bp.perm == p) {
6499                bp.perm = null;
6500                if (DEBUG_REMOVE && chatty) {
6501                    if (r == null) {
6502                        r = new StringBuilder(256);
6503                    } else {
6504                        r.append(' ');
6505                    }
6506                    r.append(p.info.name);
6507                }
6508            }
6509        }
6510        if (r != null) {
6511            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6512        }
6513
6514        N = pkg.instrumentation.size();
6515        r = null;
6516        for (i=0; i<N; i++) {
6517            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6518            mInstrumentation.remove(a.getComponentName());
6519            if (DEBUG_REMOVE && chatty) {
6520                if (r == null) {
6521                    r = new StringBuilder(256);
6522                } else {
6523                    r.append(' ');
6524                }
6525                r.append(a.info.name);
6526            }
6527        }
6528        if (r != null) {
6529            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6530        }
6531
6532        r = null;
6533        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6534            // Only system apps can hold shared libraries.
6535            if (pkg.libraryNames != null) {
6536                for (i=0; i<pkg.libraryNames.size(); i++) {
6537                    String name = pkg.libraryNames.get(i);
6538                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6539                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6540                        mSharedLibraries.remove(name);
6541                        if (DEBUG_REMOVE && chatty) {
6542                            if (r == null) {
6543                                r = new StringBuilder(256);
6544                            } else {
6545                                r.append(' ');
6546                            }
6547                            r.append(name);
6548                        }
6549                    }
6550                }
6551            }
6552        }
6553        if (r != null) {
6554            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6555        }
6556    }
6557
6558    private static final boolean isPackageFilename(String name) {
6559        return name != null && name.endsWith(".apk");
6560    }
6561
6562    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6563        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6564            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6565                return true;
6566            }
6567        }
6568        return false;
6569    }
6570
6571    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6572    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6573    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6574
6575    private void updatePermissionsLPw(String changingPkg,
6576            PackageParser.Package pkgInfo, int flags) {
6577        // Make sure there are no dangling permission trees.
6578        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6579        while (it.hasNext()) {
6580            final BasePermission bp = it.next();
6581            if (bp.packageSetting == null) {
6582                // We may not yet have parsed the package, so just see if
6583                // we still know about its settings.
6584                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6585            }
6586            if (bp.packageSetting == null) {
6587                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6588                        + " from package " + bp.sourcePackage);
6589                it.remove();
6590            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6591                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6592                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6593                            + " from package " + bp.sourcePackage);
6594                    flags |= UPDATE_PERMISSIONS_ALL;
6595                    it.remove();
6596                }
6597            }
6598        }
6599
6600        // Make sure all dynamic permissions have been assigned to a package,
6601        // and make sure there are no dangling permissions.
6602        it = mSettings.mPermissions.values().iterator();
6603        while (it.hasNext()) {
6604            final BasePermission bp = it.next();
6605            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6606                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6607                        + bp.name + " pkg=" + bp.sourcePackage
6608                        + " info=" + bp.pendingInfo);
6609                if (bp.packageSetting == null && bp.pendingInfo != null) {
6610                    final BasePermission tree = findPermissionTreeLP(bp.name);
6611                    if (tree != null && tree.perm != null) {
6612                        bp.packageSetting = tree.packageSetting;
6613                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6614                                new PermissionInfo(bp.pendingInfo));
6615                        bp.perm.info.packageName = tree.perm.info.packageName;
6616                        bp.perm.info.name = bp.name;
6617                        bp.uid = tree.uid;
6618                    }
6619                }
6620            }
6621            if (bp.packageSetting == null) {
6622                // We may not yet have parsed the package, so just see if
6623                // we still know about its settings.
6624                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6625            }
6626            if (bp.packageSetting == null) {
6627                Slog.w(TAG, "Removing dangling permission: " + bp.name
6628                        + " from package " + bp.sourcePackage);
6629                it.remove();
6630            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6631                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6632                    Slog.i(TAG, "Removing old permission: " + bp.name
6633                            + " from package " + bp.sourcePackage);
6634                    flags |= UPDATE_PERMISSIONS_ALL;
6635                    it.remove();
6636                }
6637            }
6638        }
6639
6640        // Now update the permissions for all packages, in particular
6641        // replace the granted permissions of the system packages.
6642        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6643            for (PackageParser.Package pkg : mPackages.values()) {
6644                if (pkg != pkgInfo) {
6645                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6646                }
6647            }
6648        }
6649
6650        if (pkgInfo != null) {
6651            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6652        }
6653    }
6654
6655    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6656        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6657        if (ps == null) {
6658            return;
6659        }
6660        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6661        HashSet<String> origPermissions = gp.grantedPermissions;
6662        boolean changedPermission = false;
6663
6664        if (replace) {
6665            ps.permissionsFixed = false;
6666            if (gp == ps) {
6667                origPermissions = new HashSet<String>(gp.grantedPermissions);
6668                gp.grantedPermissions.clear();
6669                gp.gids = mGlobalGids;
6670            }
6671        }
6672
6673        if (gp.gids == null) {
6674            gp.gids = mGlobalGids;
6675        }
6676
6677        final int N = pkg.requestedPermissions.size();
6678        for (int i=0; i<N; i++) {
6679            final String name = pkg.requestedPermissions.get(i);
6680            final boolean required = pkg.requestedPermissionsRequired.get(i);
6681            final BasePermission bp = mSettings.mPermissions.get(name);
6682            if (DEBUG_INSTALL) {
6683                if (gp != ps) {
6684                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6685                }
6686            }
6687
6688            if (bp == null || bp.packageSetting == null) {
6689                Slog.w(TAG, "Unknown permission " + name
6690                        + " in package " + pkg.packageName);
6691                continue;
6692            }
6693
6694            final String perm = bp.name;
6695            boolean allowed;
6696            boolean allowedSig = false;
6697            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6698            if (level == PermissionInfo.PROTECTION_NORMAL
6699                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6700                // We grant a normal or dangerous permission if any of the following
6701                // are true:
6702                // 1) The permission is required
6703                // 2) The permission is optional, but was granted in the past
6704                // 3) The permission is optional, but was requested by an
6705                //    app in /system (not /data)
6706                //
6707                // Otherwise, reject the permission.
6708                allowed = (required || origPermissions.contains(perm)
6709                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6710            } else if (bp.packageSetting == null) {
6711                // This permission is invalid; skip it.
6712                allowed = false;
6713            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6714                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6715                if (allowed) {
6716                    allowedSig = true;
6717                }
6718            } else {
6719                allowed = false;
6720            }
6721            if (DEBUG_INSTALL) {
6722                if (gp != ps) {
6723                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6724                }
6725            }
6726            if (allowed) {
6727                if (!isSystemApp(ps) && ps.permissionsFixed) {
6728                    // If this is an existing, non-system package, then
6729                    // we can't add any new permissions to it.
6730                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6731                        // Except...  if this is a permission that was added
6732                        // to the platform (note: need to only do this when
6733                        // updating the platform).
6734                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6735                    }
6736                }
6737                if (allowed) {
6738                    if (!gp.grantedPermissions.contains(perm)) {
6739                        changedPermission = true;
6740                        gp.grantedPermissions.add(perm);
6741                        gp.gids = appendInts(gp.gids, bp.gids);
6742                    } else if (!ps.haveGids) {
6743                        gp.gids = appendInts(gp.gids, bp.gids);
6744                    }
6745                } else {
6746                    Slog.w(TAG, "Not granting permission " + perm
6747                            + " to package " + pkg.packageName
6748                            + " because it was previously installed without");
6749                }
6750            } else {
6751                if (gp.grantedPermissions.remove(perm)) {
6752                    changedPermission = true;
6753                    gp.gids = removeInts(gp.gids, bp.gids);
6754                    Slog.i(TAG, "Un-granting permission " + perm
6755                            + " from package " + pkg.packageName
6756                            + " (protectionLevel=" + bp.protectionLevel
6757                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6758                            + ")");
6759                } else {
6760                    Slog.w(TAG, "Not granting permission " + perm
6761                            + " to package " + pkg.packageName
6762                            + " (protectionLevel=" + bp.protectionLevel
6763                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6764                            + ")");
6765                }
6766            }
6767        }
6768
6769        if ((changedPermission || replace) && !ps.permissionsFixed &&
6770                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6771            // This is the first that we have heard about this package, so the
6772            // permissions we have now selected are fixed until explicitly
6773            // changed.
6774            ps.permissionsFixed = true;
6775        }
6776        ps.haveGids = true;
6777    }
6778
6779    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6780        boolean allowed = false;
6781        final int NP = PackageParser.NEW_PERMISSIONS.length;
6782        for (int ip=0; ip<NP; ip++) {
6783            final PackageParser.NewPermissionInfo npi
6784                    = PackageParser.NEW_PERMISSIONS[ip];
6785            if (npi.name.equals(perm)
6786                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6787                allowed = true;
6788                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6789                        + pkg.packageName);
6790                break;
6791            }
6792        }
6793        return allowed;
6794    }
6795
6796    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6797                                          BasePermission bp, HashSet<String> origPermissions) {
6798        boolean allowed;
6799        allowed = (compareSignatures(
6800                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6801                        == PackageManager.SIGNATURE_MATCH)
6802                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6803                        == PackageManager.SIGNATURE_MATCH);
6804        if (!allowed && (bp.protectionLevel
6805                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6806            if (isSystemApp(pkg)) {
6807                // For updated system applications, a system permission
6808                // is granted only if it had been defined by the original application.
6809                if (isUpdatedSystemApp(pkg)) {
6810                    final PackageSetting sysPs = mSettings
6811                            .getDisabledSystemPkgLPr(pkg.packageName);
6812                    final GrantedPermissions origGp = sysPs.sharedUser != null
6813                            ? sysPs.sharedUser : sysPs;
6814
6815                    if (origGp.grantedPermissions.contains(perm)) {
6816                        // If the original was granted this permission, we take
6817                        // that grant decision as read and propagate it to the
6818                        // update.
6819                        allowed = true;
6820                    } else {
6821                        // The system apk may have been updated with an older
6822                        // version of the one on the data partition, but which
6823                        // granted a new system permission that it didn't have
6824                        // before.  In this case we do want to allow the app to
6825                        // now get the new permission if the ancestral apk is
6826                        // privileged to get it.
6827                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6828                            for (int j=0;
6829                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6830                                if (perm.equals(
6831                                        sysPs.pkg.requestedPermissions.get(j))) {
6832                                    allowed = true;
6833                                    break;
6834                                }
6835                            }
6836                        }
6837                    }
6838                } else {
6839                    allowed = isPrivilegedApp(pkg);
6840                }
6841            }
6842        }
6843        if (!allowed && (bp.protectionLevel
6844                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6845            // For development permissions, a development permission
6846            // is granted only if it was already granted.
6847            allowed = origPermissions.contains(perm);
6848        }
6849        return allowed;
6850    }
6851
6852    final class ActivityIntentResolver
6853            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6854        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6855                boolean defaultOnly, int userId) {
6856            if (!sUserManager.exists(userId)) return null;
6857            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6858            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6859        }
6860
6861        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6862                int userId) {
6863            if (!sUserManager.exists(userId)) return null;
6864            mFlags = flags;
6865            return super.queryIntent(intent, resolvedType,
6866                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6867        }
6868
6869        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6870                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6871            if (!sUserManager.exists(userId)) return null;
6872            if (packageActivities == null) {
6873                return null;
6874            }
6875            mFlags = flags;
6876            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6877            final int N = packageActivities.size();
6878            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6879                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6880
6881            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6882            for (int i = 0; i < N; ++i) {
6883                intentFilters = packageActivities.get(i).intents;
6884                if (intentFilters != null && intentFilters.size() > 0) {
6885                    PackageParser.ActivityIntentInfo[] array =
6886                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6887                    intentFilters.toArray(array);
6888                    listCut.add(array);
6889                }
6890            }
6891            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6892        }
6893
6894        public final void addActivity(PackageParser.Activity a, String type) {
6895            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6896            mActivities.put(a.getComponentName(), a);
6897            if (DEBUG_SHOW_INFO)
6898                Log.v(
6899                TAG, "  " + type + " " +
6900                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6901            if (DEBUG_SHOW_INFO)
6902                Log.v(TAG, "    Class=" + a.info.name);
6903            final int NI = a.intents.size();
6904            for (int j=0; j<NI; j++) {
6905                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6906                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6907                    intent.setPriority(0);
6908                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6909                            + a.className + " with priority > 0, forcing to 0");
6910                }
6911                if (DEBUG_SHOW_INFO) {
6912                    Log.v(TAG, "    IntentFilter:");
6913                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6914                }
6915                if (!intent.debugCheck()) {
6916                    Log.w(TAG, "==> For Activity " + a.info.name);
6917                }
6918                addFilter(intent);
6919            }
6920        }
6921
6922        public final void removeActivity(PackageParser.Activity a, String type) {
6923            mActivities.remove(a.getComponentName());
6924            if (DEBUG_SHOW_INFO) {
6925                Log.v(TAG, "  " + type + " "
6926                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6927                                : a.info.name) + ":");
6928                Log.v(TAG, "    Class=" + a.info.name);
6929            }
6930            final int NI = a.intents.size();
6931            for (int j=0; j<NI; j++) {
6932                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6933                if (DEBUG_SHOW_INFO) {
6934                    Log.v(TAG, "    IntentFilter:");
6935                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6936                }
6937                removeFilter(intent);
6938            }
6939        }
6940
6941        @Override
6942        protected boolean allowFilterResult(
6943                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6944            ActivityInfo filterAi = filter.activity.info;
6945            for (int i=dest.size()-1; i>=0; i--) {
6946                ActivityInfo destAi = dest.get(i).activityInfo;
6947                if (destAi.name == filterAi.name
6948                        && destAi.packageName == filterAi.packageName) {
6949                    return false;
6950                }
6951            }
6952            return true;
6953        }
6954
6955        @Override
6956        protected ActivityIntentInfo[] newArray(int size) {
6957            return new ActivityIntentInfo[size];
6958        }
6959
6960        @Override
6961        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6962            if (!sUserManager.exists(userId)) return true;
6963            PackageParser.Package p = filter.activity.owner;
6964            if (p != null) {
6965                PackageSetting ps = (PackageSetting)p.mExtras;
6966                if (ps != null) {
6967                    // System apps are never considered stopped for purposes of
6968                    // filtering, because there may be no way for the user to
6969                    // actually re-launch them.
6970                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6971                            && ps.getStopped(userId);
6972                }
6973            }
6974            return false;
6975        }
6976
6977        @Override
6978        protected boolean isPackageForFilter(String packageName,
6979                PackageParser.ActivityIntentInfo info) {
6980            return packageName.equals(info.activity.owner.packageName);
6981        }
6982
6983        @Override
6984        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6985                int match, int userId) {
6986            if (!sUserManager.exists(userId)) return null;
6987            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6988                return null;
6989            }
6990            final PackageParser.Activity activity = info.activity;
6991            if (mSafeMode && (activity.info.applicationInfo.flags
6992                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6993                return null;
6994            }
6995            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6996            if (ps == null) {
6997                return null;
6998            }
6999            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7000                    ps.readUserState(userId), userId);
7001            if (ai == null) {
7002                return null;
7003            }
7004            final ResolveInfo res = new ResolveInfo();
7005            res.activityInfo = ai;
7006            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7007                res.filter = info;
7008            }
7009            res.priority = info.getPriority();
7010            res.preferredOrder = activity.owner.mPreferredOrder;
7011            //System.out.println("Result: " + res.activityInfo.className +
7012            //                   " = " + res.priority);
7013            res.match = match;
7014            res.isDefault = info.hasDefault;
7015            res.labelRes = info.labelRes;
7016            res.nonLocalizedLabel = info.nonLocalizedLabel;
7017            res.icon = info.icon;
7018            res.system = isSystemApp(res.activityInfo.applicationInfo);
7019            return res;
7020        }
7021
7022        @Override
7023        protected void sortResults(List<ResolveInfo> results) {
7024            Collections.sort(results, mResolvePrioritySorter);
7025        }
7026
7027        @Override
7028        protected void dumpFilter(PrintWriter out, String prefix,
7029                PackageParser.ActivityIntentInfo filter) {
7030            out.print(prefix); out.print(
7031                    Integer.toHexString(System.identityHashCode(filter.activity)));
7032                    out.print(' ');
7033                    filter.activity.printComponentShortName(out);
7034                    out.print(" filter ");
7035                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7036        }
7037
7038//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7039//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7040//            final List<ResolveInfo> retList = Lists.newArrayList();
7041//            while (i.hasNext()) {
7042//                final ResolveInfo resolveInfo = i.next();
7043//                if (isEnabledLP(resolveInfo.activityInfo)) {
7044//                    retList.add(resolveInfo);
7045//                }
7046//            }
7047//            return retList;
7048//        }
7049
7050        // Keys are String (activity class name), values are Activity.
7051        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7052                = new HashMap<ComponentName, PackageParser.Activity>();
7053        private int mFlags;
7054    }
7055
7056    private final class ServiceIntentResolver
7057            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7058        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7059                boolean defaultOnly, int userId) {
7060            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7061            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7062        }
7063
7064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7065                int userId) {
7066            if (!sUserManager.exists(userId)) return null;
7067            mFlags = flags;
7068            return super.queryIntent(intent, resolvedType,
7069                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7070        }
7071
7072        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7073                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7074            if (!sUserManager.exists(userId)) return null;
7075            if (packageServices == null) {
7076                return null;
7077            }
7078            mFlags = flags;
7079            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7080            final int N = packageServices.size();
7081            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7082                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7083
7084            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7085            for (int i = 0; i < N; ++i) {
7086                intentFilters = packageServices.get(i).intents;
7087                if (intentFilters != null && intentFilters.size() > 0) {
7088                    PackageParser.ServiceIntentInfo[] array =
7089                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7090                    intentFilters.toArray(array);
7091                    listCut.add(array);
7092                }
7093            }
7094            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7095        }
7096
7097        public final void addService(PackageParser.Service s) {
7098            mServices.put(s.getComponentName(), s);
7099            if (DEBUG_SHOW_INFO) {
7100                Log.v(TAG, "  "
7101                        + (s.info.nonLocalizedLabel != null
7102                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7103                Log.v(TAG, "    Class=" + s.info.name);
7104            }
7105            final int NI = s.intents.size();
7106            int j;
7107            for (j=0; j<NI; j++) {
7108                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7109                if (DEBUG_SHOW_INFO) {
7110                    Log.v(TAG, "    IntentFilter:");
7111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7112                }
7113                if (!intent.debugCheck()) {
7114                    Log.w(TAG, "==> For Service " + s.info.name);
7115                }
7116                addFilter(intent);
7117            }
7118        }
7119
7120        public final void removeService(PackageParser.Service s) {
7121            mServices.remove(s.getComponentName());
7122            if (DEBUG_SHOW_INFO) {
7123                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7124                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7125                Log.v(TAG, "    Class=" + s.info.name);
7126            }
7127            final int NI = s.intents.size();
7128            int j;
7129            for (j=0; j<NI; j++) {
7130                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7131                if (DEBUG_SHOW_INFO) {
7132                    Log.v(TAG, "    IntentFilter:");
7133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7134                }
7135                removeFilter(intent);
7136            }
7137        }
7138
7139        @Override
7140        protected boolean allowFilterResult(
7141                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7142            ServiceInfo filterSi = filter.service.info;
7143            for (int i=dest.size()-1; i>=0; i--) {
7144                ServiceInfo destAi = dest.get(i).serviceInfo;
7145                if (destAi.name == filterSi.name
7146                        && destAi.packageName == filterSi.packageName) {
7147                    return false;
7148                }
7149            }
7150            return true;
7151        }
7152
7153        @Override
7154        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7155            return new PackageParser.ServiceIntentInfo[size];
7156        }
7157
7158        @Override
7159        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7160            if (!sUserManager.exists(userId)) return true;
7161            PackageParser.Package p = filter.service.owner;
7162            if (p != null) {
7163                PackageSetting ps = (PackageSetting)p.mExtras;
7164                if (ps != null) {
7165                    // System apps are never considered stopped for purposes of
7166                    // filtering, because there may be no way for the user to
7167                    // actually re-launch them.
7168                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7169                            && ps.getStopped(userId);
7170                }
7171            }
7172            return false;
7173        }
7174
7175        @Override
7176        protected boolean isPackageForFilter(String packageName,
7177                PackageParser.ServiceIntentInfo info) {
7178            return packageName.equals(info.service.owner.packageName);
7179        }
7180
7181        @Override
7182        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7183                int match, int userId) {
7184            if (!sUserManager.exists(userId)) return null;
7185            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7186            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7187                return null;
7188            }
7189            final PackageParser.Service service = info.service;
7190            if (mSafeMode && (service.info.applicationInfo.flags
7191                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7192                return null;
7193            }
7194            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7195            if (ps == null) {
7196                return null;
7197            }
7198            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7199                    ps.readUserState(userId), userId);
7200            if (si == null) {
7201                return null;
7202            }
7203            final ResolveInfo res = new ResolveInfo();
7204            res.serviceInfo = si;
7205            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7206                res.filter = filter;
7207            }
7208            res.priority = info.getPriority();
7209            res.preferredOrder = service.owner.mPreferredOrder;
7210            //System.out.println("Result: " + res.activityInfo.className +
7211            //                   " = " + res.priority);
7212            res.match = match;
7213            res.isDefault = info.hasDefault;
7214            res.labelRes = info.labelRes;
7215            res.nonLocalizedLabel = info.nonLocalizedLabel;
7216            res.icon = info.icon;
7217            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7218            return res;
7219        }
7220
7221        @Override
7222        protected void sortResults(List<ResolveInfo> results) {
7223            Collections.sort(results, mResolvePrioritySorter);
7224        }
7225
7226        @Override
7227        protected void dumpFilter(PrintWriter out, String prefix,
7228                PackageParser.ServiceIntentInfo filter) {
7229            out.print(prefix); out.print(
7230                    Integer.toHexString(System.identityHashCode(filter.service)));
7231                    out.print(' ');
7232                    filter.service.printComponentShortName(out);
7233                    out.print(" filter ");
7234                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7235        }
7236
7237//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7238//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7239//            final List<ResolveInfo> retList = Lists.newArrayList();
7240//            while (i.hasNext()) {
7241//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7242//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7243//                    retList.add(resolveInfo);
7244//                }
7245//            }
7246//            return retList;
7247//        }
7248
7249        // Keys are String (activity class name), values are Activity.
7250        private final HashMap<ComponentName, PackageParser.Service> mServices
7251                = new HashMap<ComponentName, PackageParser.Service>();
7252        private int mFlags;
7253    };
7254
7255    private final class ProviderIntentResolver
7256            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7257        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7258                boolean defaultOnly, int userId) {
7259            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7260            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7261        }
7262
7263        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7264                int userId) {
7265            if (!sUserManager.exists(userId))
7266                return null;
7267            mFlags = flags;
7268            return super.queryIntent(intent, resolvedType,
7269                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7270        }
7271
7272        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7273                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7274            if (!sUserManager.exists(userId))
7275                return null;
7276            if (packageProviders == null) {
7277                return null;
7278            }
7279            mFlags = flags;
7280            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7281            final int N = packageProviders.size();
7282            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7283                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7284
7285            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7286            for (int i = 0; i < N; ++i) {
7287                intentFilters = packageProviders.get(i).intents;
7288                if (intentFilters != null && intentFilters.size() > 0) {
7289                    PackageParser.ProviderIntentInfo[] array =
7290                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7291                    intentFilters.toArray(array);
7292                    listCut.add(array);
7293                }
7294            }
7295            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7296        }
7297
7298        public final void addProvider(PackageParser.Provider p) {
7299            if (mProviders.containsKey(p.getComponentName())) {
7300                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7301                return;
7302            }
7303
7304            mProviders.put(p.getComponentName(), p);
7305            if (DEBUG_SHOW_INFO) {
7306                Log.v(TAG, "  "
7307                        + (p.info.nonLocalizedLabel != null
7308                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7309                Log.v(TAG, "    Class=" + p.info.name);
7310            }
7311            final int NI = p.intents.size();
7312            int j;
7313            for (j = 0; j < NI; j++) {
7314                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7315                if (DEBUG_SHOW_INFO) {
7316                    Log.v(TAG, "    IntentFilter:");
7317                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7318                }
7319                if (!intent.debugCheck()) {
7320                    Log.w(TAG, "==> For Provider " + p.info.name);
7321                }
7322                addFilter(intent);
7323            }
7324        }
7325
7326        public final void removeProvider(PackageParser.Provider p) {
7327            mProviders.remove(p.getComponentName());
7328            if (DEBUG_SHOW_INFO) {
7329                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7330                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7331                Log.v(TAG, "    Class=" + p.info.name);
7332            }
7333            final int NI = p.intents.size();
7334            int j;
7335            for (j = 0; j < NI; j++) {
7336                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7337                if (DEBUG_SHOW_INFO) {
7338                    Log.v(TAG, "    IntentFilter:");
7339                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7340                }
7341                removeFilter(intent);
7342            }
7343        }
7344
7345        @Override
7346        protected boolean allowFilterResult(
7347                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7348            ProviderInfo filterPi = filter.provider.info;
7349            for (int i = dest.size() - 1; i >= 0; i--) {
7350                ProviderInfo destPi = dest.get(i).providerInfo;
7351                if (destPi.name == filterPi.name
7352                        && destPi.packageName == filterPi.packageName) {
7353                    return false;
7354                }
7355            }
7356            return true;
7357        }
7358
7359        @Override
7360        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7361            return new PackageParser.ProviderIntentInfo[size];
7362        }
7363
7364        @Override
7365        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7366            if (!sUserManager.exists(userId))
7367                return true;
7368            PackageParser.Package p = filter.provider.owner;
7369            if (p != null) {
7370                PackageSetting ps = (PackageSetting) p.mExtras;
7371                if (ps != null) {
7372                    // System apps are never considered stopped for purposes of
7373                    // filtering, because there may be no way for the user to
7374                    // actually re-launch them.
7375                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7376                            && ps.getStopped(userId);
7377                }
7378            }
7379            return false;
7380        }
7381
7382        @Override
7383        protected boolean isPackageForFilter(String packageName,
7384                PackageParser.ProviderIntentInfo info) {
7385            return packageName.equals(info.provider.owner.packageName);
7386        }
7387
7388        @Override
7389        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7390                int match, int userId) {
7391            if (!sUserManager.exists(userId))
7392                return null;
7393            final PackageParser.ProviderIntentInfo info = filter;
7394            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7395                return null;
7396            }
7397            final PackageParser.Provider provider = info.provider;
7398            if (mSafeMode && (provider.info.applicationInfo.flags
7399                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7400                return null;
7401            }
7402            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7403            if (ps == null) {
7404                return null;
7405            }
7406            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7407                    ps.readUserState(userId), userId);
7408            if (pi == null) {
7409                return null;
7410            }
7411            final ResolveInfo res = new ResolveInfo();
7412            res.providerInfo = pi;
7413            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7414                res.filter = filter;
7415            }
7416            res.priority = info.getPriority();
7417            res.preferredOrder = provider.owner.mPreferredOrder;
7418            res.match = match;
7419            res.isDefault = info.hasDefault;
7420            res.labelRes = info.labelRes;
7421            res.nonLocalizedLabel = info.nonLocalizedLabel;
7422            res.icon = info.icon;
7423            res.system = isSystemApp(res.providerInfo.applicationInfo);
7424            return res;
7425        }
7426
7427        @Override
7428        protected void sortResults(List<ResolveInfo> results) {
7429            Collections.sort(results, mResolvePrioritySorter);
7430        }
7431
7432        @Override
7433        protected void dumpFilter(PrintWriter out, String prefix,
7434                PackageParser.ProviderIntentInfo filter) {
7435            out.print(prefix);
7436            out.print(
7437                    Integer.toHexString(System.identityHashCode(filter.provider)));
7438            out.print(' ');
7439            filter.provider.printComponentShortName(out);
7440            out.print(" filter ");
7441            out.println(Integer.toHexString(System.identityHashCode(filter)));
7442        }
7443
7444        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7445                = new HashMap<ComponentName, PackageParser.Provider>();
7446        private int mFlags;
7447    };
7448
7449    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7450            new Comparator<ResolveInfo>() {
7451        public int compare(ResolveInfo r1, ResolveInfo r2) {
7452            int v1 = r1.priority;
7453            int v2 = r2.priority;
7454            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7455            if (v1 != v2) {
7456                return (v1 > v2) ? -1 : 1;
7457            }
7458            v1 = r1.preferredOrder;
7459            v2 = r2.preferredOrder;
7460            if (v1 != v2) {
7461                return (v1 > v2) ? -1 : 1;
7462            }
7463            if (r1.isDefault != r2.isDefault) {
7464                return r1.isDefault ? -1 : 1;
7465            }
7466            v1 = r1.match;
7467            v2 = r2.match;
7468            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7469            if (v1 != v2) {
7470                return (v1 > v2) ? -1 : 1;
7471            }
7472            if (r1.system != r2.system) {
7473                return r1.system ? -1 : 1;
7474            }
7475            return 0;
7476        }
7477    };
7478
7479    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7480            new Comparator<ProviderInfo>() {
7481        public int compare(ProviderInfo p1, ProviderInfo p2) {
7482            final int v1 = p1.initOrder;
7483            final int v2 = p2.initOrder;
7484            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7485        }
7486    };
7487
7488    static final void sendPackageBroadcast(String action, String pkg,
7489            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7490            int[] userIds) {
7491        IActivityManager am = ActivityManagerNative.getDefault();
7492        if (am != null) {
7493            try {
7494                if (userIds == null) {
7495                    userIds = am.getRunningUserIds();
7496                }
7497                for (int id : userIds) {
7498                    final Intent intent = new Intent(action,
7499                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7500                    if (extras != null) {
7501                        intent.putExtras(extras);
7502                    }
7503                    if (targetPkg != null) {
7504                        intent.setPackage(targetPkg);
7505                    }
7506                    // Modify the UID when posting to other users
7507                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7508                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7509                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7510                        intent.putExtra(Intent.EXTRA_UID, uid);
7511                    }
7512                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7513                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7514                    if (DEBUG_BROADCASTS) {
7515                        RuntimeException here = new RuntimeException("here");
7516                        here.fillInStackTrace();
7517                        Slog.d(TAG, "Sending to user " + id + ": "
7518                                + intent.toShortString(false, true, false, false)
7519                                + " " + intent.getExtras(), here);
7520                    }
7521                    am.broadcastIntent(null, intent, null, finishedReceiver,
7522                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7523                            finishedReceiver != null, false, id);
7524                }
7525            } catch (RemoteException ex) {
7526            }
7527        }
7528    }
7529
7530    /**
7531     * Check if the external storage media is available. This is true if there
7532     * is a mounted external storage medium or if the external storage is
7533     * emulated.
7534     */
7535    private boolean isExternalMediaAvailable() {
7536        return mMediaMounted || Environment.isExternalStorageEmulated();
7537    }
7538
7539    @Override
7540    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7541        // writer
7542        synchronized (mPackages) {
7543            if (!isExternalMediaAvailable()) {
7544                // If the external storage is no longer mounted at this point,
7545                // the caller may not have been able to delete all of this
7546                // packages files and can not delete any more.  Bail.
7547                return null;
7548            }
7549            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7550            if (lastPackage != null) {
7551                pkgs.remove(lastPackage);
7552            }
7553            if (pkgs.size() > 0) {
7554                return pkgs.get(0);
7555            }
7556        }
7557        return null;
7558    }
7559
7560    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7561        if (false) {
7562            RuntimeException here = new RuntimeException("here");
7563            here.fillInStackTrace();
7564            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7565                    + " andCode=" + andCode, here);
7566        }
7567        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7568                userId, andCode ? 1 : 0, packageName));
7569    }
7570
7571    void startCleaningPackages() {
7572        // reader
7573        synchronized (mPackages) {
7574            if (!isExternalMediaAvailable()) {
7575                return;
7576            }
7577            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7578                return;
7579            }
7580        }
7581        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7582        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7583        IActivityManager am = ActivityManagerNative.getDefault();
7584        if (am != null) {
7585            try {
7586                am.startService(null, intent, null, UserHandle.USER_OWNER);
7587            } catch (RemoteException e) {
7588            }
7589        }
7590    }
7591
7592    private final class AppDirObserver extends FileObserver {
7593        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7594            super(path, mask);
7595            mRootDir = path;
7596            mIsRom = isrom;
7597            mIsPrivileged = isPrivileged;
7598        }
7599
7600        public void onEvent(int event, String path) {
7601            String removedPackage = null;
7602            int removedAppId = -1;
7603            int[] removedUsers = null;
7604            String addedPackage = null;
7605            int addedAppId = -1;
7606            int[] addedUsers = null;
7607
7608            // TODO post a message to the handler to obtain serial ordering
7609            synchronized (mInstallLock) {
7610                String fullPathStr = null;
7611                File fullPath = null;
7612                if (path != null) {
7613                    fullPath = new File(mRootDir, path);
7614                    fullPathStr = fullPath.getPath();
7615                }
7616
7617                if (DEBUG_APP_DIR_OBSERVER)
7618                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7619
7620                if (!isPackageFilename(path)) {
7621                    if (DEBUG_APP_DIR_OBSERVER)
7622                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7623                    return;
7624                }
7625
7626                // Ignore packages that are being installed or
7627                // have just been installed.
7628                if (ignoreCodePath(fullPathStr)) {
7629                    return;
7630                }
7631                PackageParser.Package p = null;
7632                PackageSetting ps = null;
7633                // reader
7634                synchronized (mPackages) {
7635                    p = mAppDirs.get(fullPathStr);
7636                    if (p != null) {
7637                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7638                        if (ps != null) {
7639                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7640                        } else {
7641                            removedUsers = sUserManager.getUserIds();
7642                        }
7643                    }
7644                    addedUsers = sUserManager.getUserIds();
7645                }
7646                if ((event&REMOVE_EVENTS) != 0) {
7647                    if (ps != null) {
7648                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7649                        removePackageLI(ps, true);
7650                        removedPackage = ps.name;
7651                        removedAppId = ps.appId;
7652                    }
7653                }
7654
7655                if ((event&ADD_EVENTS) != 0) {
7656                    if (p == null) {
7657                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7658                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7659                        if (mIsRom) {
7660                            flags |= PackageParser.PARSE_IS_SYSTEM
7661                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7662                            if (mIsPrivileged) {
7663                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7664                            }
7665                        }
7666                        p = scanPackageLI(fullPath, flags,
7667                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7668                                System.currentTimeMillis(), UserHandle.ALL, null);
7669                        if (p != null) {
7670                            /*
7671                             * TODO this seems dangerous as the package may have
7672                             * changed since we last acquired the mPackages
7673                             * lock.
7674                             */
7675                            // writer
7676                            synchronized (mPackages) {
7677                                updatePermissionsLPw(p.packageName, p,
7678                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7679                            }
7680                            addedPackage = p.applicationInfo.packageName;
7681                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7682                        }
7683                    }
7684                }
7685
7686                // reader
7687                synchronized (mPackages) {
7688                    mSettings.writeLPr();
7689                }
7690            }
7691
7692            if (removedPackage != null) {
7693                Bundle extras = new Bundle(1);
7694                extras.putInt(Intent.EXTRA_UID, removedAppId);
7695                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7696                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7697                        extras, null, null, removedUsers);
7698            }
7699            if (addedPackage != null) {
7700                Bundle extras = new Bundle(1);
7701                extras.putInt(Intent.EXTRA_UID, addedAppId);
7702                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7703                        extras, null, null, addedUsers);
7704            }
7705        }
7706
7707        private final String mRootDir;
7708        private final boolean mIsRom;
7709        private final boolean mIsPrivileged;
7710    }
7711
7712    /*
7713     * The old-style observer methods all just trampoline to the newer signature with
7714     * expanded install observer API.  The older API continues to work but does not
7715     * supply the additional details of the Observer2 API.
7716     */
7717
7718    /* Called when a downloaded package installation has been confirmed by the user */
7719    public void installPackage(
7720            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7721        installPackageEtc(packageURI, observer, null, flags, null);
7722    }
7723
7724    /* Called when a downloaded package installation has been confirmed by the user */
7725    @Override
7726    public void installPackage(
7727            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7728            final String installerPackageName) {
7729        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7730                installerPackageName, null, null, null);
7731    }
7732
7733    @Override
7734    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7735            int flags, String installerPackageName, Uri verificationURI,
7736            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7737        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7738                VerificationParams.NO_UID, manifestDigest);
7739        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7740                installerPackageName, verificationParams, encryptionParams);
7741    }
7742
7743    @Override
7744    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7745            IPackageInstallObserver observer, int flags, String installerPackageName,
7746            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7747        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7748                installerPackageName, verificationParams, encryptionParams);
7749    }
7750
7751    /*
7752     * And here are the "live" versions that take both observer arguments
7753     */
7754    public void installPackageEtc(
7755            final Uri packageURI, final IPackageInstallObserver observer,
7756            IPackageInstallObserver2 observer2, final int flags) {
7757        installPackageEtc(packageURI, observer, observer2, flags, null);
7758    }
7759
7760    public void installPackageEtc(
7761            final Uri packageURI, final IPackageInstallObserver observer,
7762            final IPackageInstallObserver2 observer2, final int flags,
7763            final String installerPackageName) {
7764        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7765                installerPackageName, null, null, null);
7766    }
7767
7768    @Override
7769    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7770            IPackageInstallObserver2 observer2,
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, observer2, flags,
7776                installerPackageName, verificationParams, encryptionParams);
7777    }
7778
7779    /*
7780     * All of the installPackage...*() methods redirect to this one for the master implementation
7781     */
7782    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7783            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7784            int flags, String installerPackageName,
7785            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7786        if (observer == null && observer2 == null) {
7787            throw new IllegalArgumentException("No install observer supplied");
7788        }
7789        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7790                flags, installerPackageName, verificationParams, encryptionParams, null);
7791    }
7792
7793    @Override
7794    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7795            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7796            int flags, String installerPackageName,
7797            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7798            String packageAbiOverride) {
7799        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7800                null);
7801
7802        final int uid = Binder.getCallingUid();
7803        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7804            try {
7805                if (observer != null) {
7806                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7807                }
7808                if (observer2 != null) {
7809                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7810                }
7811            } catch (RemoteException re) {
7812            }
7813            return;
7814        }
7815
7816        UserHandle user;
7817        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7818            user = UserHandle.ALL;
7819        } else {
7820            user = new UserHandle(UserHandle.getUserId(uid));
7821        }
7822
7823        final int filteredFlags;
7824
7825        if (uid == Process.SHELL_UID || uid == 0) {
7826            if (DEBUG_INSTALL) {
7827                Slog.v(TAG, "Install from ADB");
7828            }
7829            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7830        } else {
7831            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7832        }
7833
7834        verificationParams.setInstallerUid(uid);
7835
7836        final Message msg = mHandler.obtainMessage(INIT_COPY);
7837        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7838                installerPackageName, verificationParams, encryptionParams, user,
7839                packageAbiOverride);
7840        mHandler.sendMessage(msg);
7841    }
7842
7843    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7844        Bundle extras = new Bundle(1);
7845        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7846
7847        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7848                packageName, extras, null, null, new int[] {userId});
7849        try {
7850            IActivityManager am = ActivityManagerNative.getDefault();
7851            final boolean isSystem =
7852                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7853            if (isSystem && am.isUserRunning(userId, false)) {
7854                // The just-installed/enabled app is bundled on the system, so presumed
7855                // to be able to run automatically without needing an explicit launch.
7856                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7857                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7858                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7859                        .setPackage(packageName);
7860                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7861                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7862            }
7863        } catch (RemoteException e) {
7864            // shouldn't happen
7865            Slog.w(TAG, "Unable to bootstrap installed package", e);
7866        }
7867    }
7868
7869    @Override
7870    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7871            int userId) {
7872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7873        PackageSetting pkgSetting;
7874        final int uid = Binder.getCallingUid();
7875        if (UserHandle.getUserId(uid) != userId) {
7876            mContext.enforceCallingOrSelfPermission(
7877                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7878                    "setApplicationBlockedSetting for user " + userId);
7879        }
7880
7881        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7882            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7883            return false;
7884        }
7885
7886        long callingId = Binder.clearCallingIdentity();
7887        try {
7888            boolean sendAdded = false;
7889            boolean sendRemoved = false;
7890            // writer
7891            synchronized (mPackages) {
7892                pkgSetting = mSettings.mPackages.get(packageName);
7893                if (pkgSetting == null) {
7894                    return false;
7895                }
7896                if (pkgSetting.getBlocked(userId) != blocked) {
7897                    pkgSetting.setBlocked(blocked, userId);
7898                    mSettings.writePackageRestrictionsLPr(userId);
7899                    if (blocked) {
7900                        sendRemoved = true;
7901                    } else {
7902                        sendAdded = true;
7903                    }
7904                }
7905            }
7906            if (sendAdded) {
7907                sendPackageAddedForUser(packageName, pkgSetting, userId);
7908                return true;
7909            }
7910            if (sendRemoved) {
7911                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7912                        "blocking pkg");
7913                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7914            }
7915        } finally {
7916            Binder.restoreCallingIdentity(callingId);
7917        }
7918        return false;
7919    }
7920
7921    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7922            int userId) {
7923        final PackageRemovedInfo info = new PackageRemovedInfo();
7924        info.removedPackage = packageName;
7925        info.removedUsers = new int[] {userId};
7926        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7927        info.sendBroadcast(false, false, false);
7928    }
7929
7930    /**
7931     * Returns true if application is not found or there was an error. Otherwise it returns
7932     * the blocked state of the package for the given user.
7933     */
7934    @Override
7935    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7938                "getApplicationBlocked for user " + userId);
7939        PackageSetting pkgSetting;
7940        long callingId = Binder.clearCallingIdentity();
7941        try {
7942            // writer
7943            synchronized (mPackages) {
7944                pkgSetting = mSettings.mPackages.get(packageName);
7945                if (pkgSetting == null) {
7946                    return true;
7947                }
7948                return pkgSetting.getBlocked(userId);
7949            }
7950        } finally {
7951            Binder.restoreCallingIdentity(callingId);
7952        }
7953    }
7954
7955    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7956            int flags) {
7957        // TODO: install stage!
7958        try {
7959            observer.packageInstalled(basePackageName, null,
7960                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7961        } catch (RemoteException ignored) {
7962        }
7963    }
7964
7965    /**
7966     * @hide
7967     */
7968    @Override
7969    public int installExistingPackageAsUser(String packageName, int userId) {
7970        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7971                null);
7972        PackageSetting pkgSetting;
7973        final int uid = Binder.getCallingUid();
7974        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7975        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7976            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7977        }
7978
7979        long callingId = Binder.clearCallingIdentity();
7980        try {
7981            boolean sendAdded = false;
7982            Bundle extras = new Bundle(1);
7983
7984            // writer
7985            synchronized (mPackages) {
7986                pkgSetting = mSettings.mPackages.get(packageName);
7987                if (pkgSetting == null) {
7988                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7989                }
7990                if (!pkgSetting.getInstalled(userId)) {
7991                    pkgSetting.setInstalled(true, userId);
7992                    pkgSetting.setBlocked(false, userId);
7993                    mSettings.writePackageRestrictionsLPr(userId);
7994                    sendAdded = true;
7995                }
7996            }
7997
7998            if (sendAdded) {
7999                sendPackageAddedForUser(packageName, pkgSetting, userId);
8000            }
8001        } finally {
8002            Binder.restoreCallingIdentity(callingId);
8003        }
8004
8005        return PackageManager.INSTALL_SUCCEEDED;
8006    }
8007
8008    boolean isUserRestricted(int userId, String restrictionKey) {
8009        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8010        if (restrictions.getBoolean(restrictionKey, false)) {
8011            Log.w(TAG, "User is restricted: " + restrictionKey);
8012            return true;
8013        }
8014        return false;
8015    }
8016
8017    @Override
8018    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8019        mContext.enforceCallingOrSelfPermission(
8020                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8021                "Only package verification agents can verify applications");
8022
8023        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8024        final PackageVerificationResponse response = new PackageVerificationResponse(
8025                verificationCode, Binder.getCallingUid());
8026        msg.arg1 = id;
8027        msg.obj = response;
8028        mHandler.sendMessage(msg);
8029    }
8030
8031    @Override
8032    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8033            long millisecondsToDelay) {
8034        mContext.enforceCallingOrSelfPermission(
8035                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8036                "Only package verification agents can extend verification timeouts");
8037
8038        final PackageVerificationState state = mPendingVerification.get(id);
8039        final PackageVerificationResponse response = new PackageVerificationResponse(
8040                verificationCodeAtTimeout, Binder.getCallingUid());
8041
8042        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8043            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8044        }
8045        if (millisecondsToDelay < 0) {
8046            millisecondsToDelay = 0;
8047        }
8048        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8049                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8050            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8051        }
8052
8053        if ((state != null) && !state.timeoutExtended()) {
8054            state.extendTimeout();
8055
8056            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8057            msg.arg1 = id;
8058            msg.obj = response;
8059            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8060        }
8061    }
8062
8063    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8064            int verificationCode, UserHandle user) {
8065        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8066        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8067        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8068        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8069        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8070
8071        mContext.sendBroadcastAsUser(intent, user,
8072                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8073    }
8074
8075    private ComponentName matchComponentForVerifier(String packageName,
8076            List<ResolveInfo> receivers) {
8077        ActivityInfo targetReceiver = null;
8078
8079        final int NR = receivers.size();
8080        for (int i = 0; i < NR; i++) {
8081            final ResolveInfo info = receivers.get(i);
8082            if (info.activityInfo == null) {
8083                continue;
8084            }
8085
8086            if (packageName.equals(info.activityInfo.packageName)) {
8087                targetReceiver = info.activityInfo;
8088                break;
8089            }
8090        }
8091
8092        if (targetReceiver == null) {
8093            return null;
8094        }
8095
8096        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8097    }
8098
8099    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8100            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8101        if (pkgInfo.verifiers.length == 0) {
8102            return null;
8103        }
8104
8105        final int N = pkgInfo.verifiers.length;
8106        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8107        for (int i = 0; i < N; i++) {
8108            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8109
8110            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8111                    receivers);
8112            if (comp == null) {
8113                continue;
8114            }
8115
8116            final int verifierUid = getUidForVerifier(verifierInfo);
8117            if (verifierUid == -1) {
8118                continue;
8119            }
8120
8121            if (DEBUG_VERIFY) {
8122                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8123                        + " with the correct signature");
8124            }
8125            sufficientVerifiers.add(comp);
8126            verificationState.addSufficientVerifier(verifierUid);
8127        }
8128
8129        return sufficientVerifiers;
8130    }
8131
8132    private int getUidForVerifier(VerifierInfo verifierInfo) {
8133        synchronized (mPackages) {
8134            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8135            if (pkg == null) {
8136                return -1;
8137            } else if (pkg.mSignatures.length != 1) {
8138                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8139                        + " has more than one signature; ignoring");
8140                return -1;
8141            }
8142
8143            /*
8144             * If the public key of the package's signature does not match
8145             * our expected public key, then this is a different package and
8146             * we should skip.
8147             */
8148
8149            final byte[] expectedPublicKey;
8150            try {
8151                final Signature verifierSig = pkg.mSignatures[0];
8152                final PublicKey publicKey = verifierSig.getPublicKey();
8153                expectedPublicKey = publicKey.getEncoded();
8154            } catch (CertificateException e) {
8155                return -1;
8156            }
8157
8158            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8159
8160            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8161                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8162                        + " does not have the expected public key; ignoring");
8163                return -1;
8164            }
8165
8166            return pkg.applicationInfo.uid;
8167        }
8168    }
8169
8170    @Override
8171    public void finishPackageInstall(int token) {
8172        enforceSystemOrRoot("Only the system is allowed to finish installs");
8173
8174        if (DEBUG_INSTALL) {
8175            Slog.v(TAG, "BM finishing package install for " + token);
8176        }
8177
8178        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8179        mHandler.sendMessage(msg);
8180    }
8181
8182    /**
8183     * Get the verification agent timeout.
8184     *
8185     * @return verification timeout in milliseconds
8186     */
8187    private long getVerificationTimeout() {
8188        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8189                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8190                DEFAULT_VERIFICATION_TIMEOUT);
8191    }
8192
8193    /**
8194     * Get the default verification agent response code.
8195     *
8196     * @return default verification response code
8197     */
8198    private int getDefaultVerificationResponse() {
8199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8200                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8201                DEFAULT_VERIFICATION_RESPONSE);
8202    }
8203
8204    /**
8205     * Check whether or not package verification has been enabled.
8206     *
8207     * @return true if verification should be performed
8208     */
8209    private boolean isVerificationEnabled(int flags) {
8210        if (!DEFAULT_VERIFY_ENABLE) {
8211            return false;
8212        }
8213
8214        // Check if installing from ADB
8215        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8216            // Do not run verification in a test harness environment
8217            if (ActivityManager.isRunningInTestHarness()) {
8218                return false;
8219            }
8220            // Check if the developer does not want package verification for ADB installs
8221            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8222                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8223                return false;
8224            }
8225        }
8226
8227        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8228                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8229    }
8230
8231    /**
8232     * Get the "allow unknown sources" setting.
8233     *
8234     * @return the current "allow unknown sources" setting
8235     */
8236    private int getUnknownSourcesSettings() {
8237        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8238                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8239                -1);
8240    }
8241
8242    @Override
8243    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8244        final int uid = Binder.getCallingUid();
8245        // writer
8246        synchronized (mPackages) {
8247            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8248            if (targetPackageSetting == null) {
8249                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8250            }
8251
8252            PackageSetting installerPackageSetting;
8253            if (installerPackageName != null) {
8254                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8255                if (installerPackageSetting == null) {
8256                    throw new IllegalArgumentException("Unknown installer package: "
8257                            + installerPackageName);
8258                }
8259            } else {
8260                installerPackageSetting = null;
8261            }
8262
8263            Signature[] callerSignature;
8264            Object obj = mSettings.getUserIdLPr(uid);
8265            if (obj != null) {
8266                if (obj instanceof SharedUserSetting) {
8267                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8268                } else if (obj instanceof PackageSetting) {
8269                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8270                } else {
8271                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8272                }
8273            } else {
8274                throw new SecurityException("Unknown calling uid " + uid);
8275            }
8276
8277            // Verify: can't set installerPackageName to a package that is
8278            // not signed with the same cert as the caller.
8279            if (installerPackageSetting != null) {
8280                if (compareSignatures(callerSignature,
8281                        installerPackageSetting.signatures.mSignatures)
8282                        != PackageManager.SIGNATURE_MATCH) {
8283                    throw new SecurityException(
8284                            "Caller does not have same cert as new installer package "
8285                            + installerPackageName);
8286                }
8287            }
8288
8289            // Verify: if target already has an installer package, it must
8290            // be signed with the same cert as the caller.
8291            if (targetPackageSetting.installerPackageName != null) {
8292                PackageSetting setting = mSettings.mPackages.get(
8293                        targetPackageSetting.installerPackageName);
8294                // If the currently set package isn't valid, then it's always
8295                // okay to change it.
8296                if (setting != null) {
8297                    if (compareSignatures(callerSignature,
8298                            setting.signatures.mSignatures)
8299                            != PackageManager.SIGNATURE_MATCH) {
8300                        throw new SecurityException(
8301                                "Caller does not have same cert as old installer package "
8302                                + targetPackageSetting.installerPackageName);
8303                    }
8304                }
8305            }
8306
8307            // Okay!
8308            targetPackageSetting.installerPackageName = installerPackageName;
8309            scheduleWriteSettingsLocked();
8310        }
8311    }
8312
8313    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8314        // Queue up an async operation since the package installation may take a little while.
8315        mHandler.post(new Runnable() {
8316            public void run() {
8317                mHandler.removeCallbacks(this);
8318                 // Result object to be returned
8319                PackageInstalledInfo res = new PackageInstalledInfo();
8320                res.returnCode = currentStatus;
8321                res.uid = -1;
8322                res.pkg = null;
8323                res.removedInfo = new PackageRemovedInfo();
8324                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8325                    args.doPreInstall(res.returnCode);
8326                    synchronized (mInstallLock) {
8327                        installPackageLI(args, true, res);
8328                    }
8329                    args.doPostInstall(res.returnCode, res.uid);
8330                }
8331
8332                // A restore should be performed at this point if (a) the install
8333                // succeeded, (b) the operation is not an update, and (c) the new
8334                // package has a backupAgent defined.
8335                final boolean update = res.removedInfo.removedPackage != null;
8336                boolean doRestore = (!update
8337                        && res.pkg != null
8338                        && res.pkg.applicationInfo.backupAgentName != null);
8339
8340                // Set up the post-install work request bookkeeping.  This will be used
8341                // and cleaned up by the post-install event handling regardless of whether
8342                // there's a restore pass performed.  Token values are >= 1.
8343                int token;
8344                if (mNextInstallToken < 0) mNextInstallToken = 1;
8345                token = mNextInstallToken++;
8346
8347                PostInstallData data = new PostInstallData(args, res);
8348                mRunningInstalls.put(token, data);
8349                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8350
8351                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8352                    // Pass responsibility to the Backup Manager.  It will perform a
8353                    // restore if appropriate, then pass responsibility back to the
8354                    // Package Manager to run the post-install observer callbacks
8355                    // and broadcasts.
8356                    IBackupManager bm = IBackupManager.Stub.asInterface(
8357                            ServiceManager.getService(Context.BACKUP_SERVICE));
8358                    if (bm != null) {
8359                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8360                                + " to BM for possible restore");
8361                        try {
8362                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8363                        } catch (RemoteException e) {
8364                            // can't happen; the backup manager is local
8365                        } catch (Exception e) {
8366                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8367                            doRestore = false;
8368                        }
8369                    } else {
8370                        Slog.e(TAG, "Backup Manager not found!");
8371                        doRestore = false;
8372                    }
8373                }
8374
8375                if (!doRestore) {
8376                    // No restore possible, or the Backup Manager was mysteriously not
8377                    // available -- just fire the post-install work request directly.
8378                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8379                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8380                    mHandler.sendMessage(msg);
8381                }
8382            }
8383        });
8384    }
8385
8386    private abstract class HandlerParams {
8387        private static final int MAX_RETRIES = 4;
8388
8389        /**
8390         * Number of times startCopy() has been attempted and had a non-fatal
8391         * error.
8392         */
8393        private int mRetries = 0;
8394
8395        /** User handle for the user requesting the information or installation. */
8396        private final UserHandle mUser;
8397
8398        HandlerParams(UserHandle user) {
8399            mUser = user;
8400        }
8401
8402        UserHandle getUser() {
8403            return mUser;
8404        }
8405
8406        final boolean startCopy() {
8407            boolean res;
8408            try {
8409                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8410
8411                if (++mRetries > MAX_RETRIES) {
8412                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8413                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8414                    handleServiceError();
8415                    return false;
8416                } else {
8417                    handleStartCopy();
8418                    res = true;
8419                }
8420            } catch (RemoteException e) {
8421                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8422                mHandler.sendEmptyMessage(MCS_RECONNECT);
8423                res = false;
8424            }
8425            handleReturnCode();
8426            return res;
8427        }
8428
8429        final void serviceError() {
8430            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8431            handleServiceError();
8432            handleReturnCode();
8433        }
8434
8435        abstract void handleStartCopy() throws RemoteException;
8436        abstract void handleServiceError();
8437        abstract void handleReturnCode();
8438    }
8439
8440    class MeasureParams extends HandlerParams {
8441        private final PackageStats mStats;
8442        private boolean mSuccess;
8443
8444        private final IPackageStatsObserver mObserver;
8445
8446        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8447            super(new UserHandle(stats.userHandle));
8448            mObserver = observer;
8449            mStats = stats;
8450        }
8451
8452        @Override
8453        public String toString() {
8454            return "MeasureParams{"
8455                + Integer.toHexString(System.identityHashCode(this))
8456                + " " + mStats.packageName + "}";
8457        }
8458
8459        @Override
8460        void handleStartCopy() throws RemoteException {
8461            synchronized (mInstallLock) {
8462                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8463            }
8464
8465            if (mSuccess) {
8466                final boolean mounted;
8467                if (Environment.isExternalStorageEmulated()) {
8468                    mounted = true;
8469                } else {
8470                    final String status = Environment.getExternalStorageState();
8471                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8472                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8473                }
8474
8475                if (mounted) {
8476                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8477
8478                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8479                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8480
8481                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8482                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8483
8484                    // Always subtract cache size, since it's a subdirectory
8485                    mStats.externalDataSize -= mStats.externalCacheSize;
8486
8487                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8488                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8489
8490                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8491                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8492                }
8493            }
8494        }
8495
8496        @Override
8497        void handleReturnCode() {
8498            if (mObserver != null) {
8499                try {
8500                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8501                } catch (RemoteException e) {
8502                    Slog.i(TAG, "Observer no longer exists.");
8503                }
8504            }
8505        }
8506
8507        @Override
8508        void handleServiceError() {
8509            Slog.e(TAG, "Could not measure application " + mStats.packageName
8510                            + " external storage");
8511        }
8512    }
8513
8514    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8515            throws RemoteException {
8516        long result = 0;
8517        for (File path : paths) {
8518            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8519        }
8520        return result;
8521    }
8522
8523    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8524        for (File path : paths) {
8525            try {
8526                mcs.clearDirectory(path.getAbsolutePath());
8527            } catch (RemoteException e) {
8528            }
8529        }
8530    }
8531
8532    class InstallParams extends HandlerParams {
8533        final IPackageInstallObserver observer;
8534        final IPackageInstallObserver2 observer2;
8535        int flags;
8536
8537        private final Uri mPackageURI;
8538        final String installerPackageName;
8539        final VerificationParams verificationParams;
8540        private InstallArgs mArgs;
8541        private int mRet;
8542        private File mTempPackage;
8543        final ContainerEncryptionParams encryptionParams;
8544        final String packageAbiOverride;
8545        final String packageInstructionSetOverride;
8546
8547        InstallParams(Uri packageURI,
8548                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8549                int flags, String installerPackageName, VerificationParams verificationParams,
8550                ContainerEncryptionParams encryptionParams, UserHandle user,
8551                String packageAbiOverride) {
8552            super(user);
8553            this.mPackageURI = packageURI;
8554            this.flags = flags;
8555            this.observer = observer;
8556            this.observer2 = observer2;
8557            this.installerPackageName = installerPackageName;
8558            this.verificationParams = verificationParams;
8559            this.encryptionParams = encryptionParams;
8560            this.packageAbiOverride = packageAbiOverride;
8561            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8562                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8563        }
8564
8565        @Override
8566        public String toString() {
8567            return "InstallParams{"
8568                + Integer.toHexString(System.identityHashCode(this))
8569                + " " + mPackageURI + "}";
8570        }
8571
8572        public ManifestDigest getManifestDigest() {
8573            if (verificationParams == null) {
8574                return null;
8575            }
8576            return verificationParams.getManifestDigest();
8577        }
8578
8579        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8580            String packageName = pkgLite.packageName;
8581            int installLocation = pkgLite.installLocation;
8582            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8583            // reader
8584            synchronized (mPackages) {
8585                PackageParser.Package pkg = mPackages.get(packageName);
8586                if (pkg != null) {
8587                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8588                        // Check for downgrading.
8589                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8590                            if (pkgLite.versionCode < pkg.mVersionCode) {
8591                                Slog.w(TAG, "Can't install update of " + packageName
8592                                        + " update version " + pkgLite.versionCode
8593                                        + " is older than installed version "
8594                                        + pkg.mVersionCode);
8595                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8596                            }
8597                        }
8598                        // Check for updated system application.
8599                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8600                            if (onSd) {
8601                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8602                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8603                            }
8604                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8605                        } else {
8606                            if (onSd) {
8607                                // Install flag overrides everything.
8608                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8609                            }
8610                            // If current upgrade specifies particular preference
8611                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8612                                // Application explicitly specified internal.
8613                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8614                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8615                                // App explictly prefers external. Let policy decide
8616                            } else {
8617                                // Prefer previous location
8618                                if (isExternal(pkg)) {
8619                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8620                                }
8621                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8622                            }
8623                        }
8624                    } else {
8625                        // Invalid install. Return error code
8626                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8627                    }
8628                }
8629            }
8630            // All the special cases have been taken care of.
8631            // Return result based on recommended install location.
8632            if (onSd) {
8633                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8634            }
8635            return pkgLite.recommendedInstallLocation;
8636        }
8637
8638        private long getMemoryLowThreshold() {
8639            final DeviceStorageMonitorInternal
8640                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8641            if (dsm == null) {
8642                return 0L;
8643            }
8644            return dsm.getMemoryLowThreshold();
8645        }
8646
8647        /*
8648         * Invoke remote method to get package information and install
8649         * location values. Override install location based on default
8650         * policy if needed and then create install arguments based
8651         * on the install location.
8652         */
8653        public void handleStartCopy() throws RemoteException {
8654            int ret = PackageManager.INSTALL_SUCCEEDED;
8655            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8656            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8657            PackageInfoLite pkgLite = null;
8658
8659            if (onInt && onSd) {
8660                // Check if both bits are set.
8661                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8662                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8663            } else {
8664                final long lowThreshold = getMemoryLowThreshold();
8665                if (lowThreshold == 0L) {
8666                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8667                }
8668
8669                try {
8670                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8671                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8672
8673                    final File packageFile;
8674                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8675                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8676                        if (mTempPackage != null) {
8677                            ParcelFileDescriptor out;
8678                            try {
8679                                out = ParcelFileDescriptor.open(mTempPackage,
8680                                        ParcelFileDescriptor.MODE_READ_WRITE);
8681                            } catch (FileNotFoundException e) {
8682                                out = null;
8683                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8684                            }
8685
8686                            // Make a temporary file for decryption.
8687                            ret = mContainerService
8688                                    .copyResource(mPackageURI, encryptionParams, out);
8689                            IoUtils.closeQuietly(out);
8690
8691                            packageFile = mTempPackage;
8692
8693                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8694                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8695                                            | FileUtils.S_IROTH,
8696                                    -1, -1);
8697                        } else {
8698                            packageFile = null;
8699                        }
8700                    } else {
8701                        packageFile = new File(mPackageURI.getPath());
8702                    }
8703
8704                    if (packageFile != null) {
8705                        // Remote call to find out default install location
8706                        final String packageFilePath = packageFile.getAbsolutePath();
8707                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8708                                lowThreshold, packageAbiOverride);
8709
8710                        /*
8711                         * If we have too little free space, try to free cache
8712                         * before giving up.
8713                         */
8714                        if (pkgLite.recommendedInstallLocation
8715                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8716                            final long size = mContainerService.calculateInstalledSize(
8717                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8718                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8719                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8720                                        flags, lowThreshold, packageAbiOverride);
8721                            }
8722                            /*
8723                             * The cache free must have deleted the file we
8724                             * downloaded to install.
8725                             *
8726                             * TODO: fix the "freeCache" call to not delete
8727                             *       the file we care about.
8728                             */
8729                            if (pkgLite.recommendedInstallLocation
8730                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8731                                pkgLite.recommendedInstallLocation
8732                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8733                            }
8734                        }
8735                    }
8736                } finally {
8737                    mContext.revokeUriPermission(mPackageURI,
8738                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8739                }
8740            }
8741
8742            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8743                int loc = pkgLite.recommendedInstallLocation;
8744                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8745                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8746                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8747                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8748                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8749                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8750                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8751                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8752                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8753                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8754                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8755                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8756                } else {
8757                    // Override with defaults if needed.
8758                    loc = installLocationPolicy(pkgLite, flags);
8759                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8760                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8761                    } else if (!onSd && !onInt) {
8762                        // Override install location with flags
8763                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8764                            // Set the flag to install on external media.
8765                            flags |= PackageManager.INSTALL_EXTERNAL;
8766                            flags &= ~PackageManager.INSTALL_INTERNAL;
8767                        } else {
8768                            // Make sure the flag for installing on external
8769                            // media is unset
8770                            flags |= PackageManager.INSTALL_INTERNAL;
8771                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8772                        }
8773                    }
8774                }
8775            }
8776
8777            final InstallArgs args = createInstallArgs(this);
8778            mArgs = args;
8779
8780            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8781                 /*
8782                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8783                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8784                 */
8785                int userIdentifier = getUser().getIdentifier();
8786                if (userIdentifier == UserHandle.USER_ALL
8787                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8788                    userIdentifier = UserHandle.USER_OWNER;
8789                }
8790
8791                /*
8792                 * Determine if we have any installed package verifiers. If we
8793                 * do, then we'll defer to them to verify the packages.
8794                 */
8795                final int requiredUid = mRequiredVerifierPackage == null ? -1
8796                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8797                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8798                    final Intent verification = new Intent(
8799                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8800                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8801                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8802
8803                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8804                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8805                            0 /* TODO: Which userId? */);
8806
8807                    if (DEBUG_VERIFY) {
8808                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8809                                + verification.toString() + " with " + pkgLite.verifiers.length
8810                                + " optional verifiers");
8811                    }
8812
8813                    final int verificationId = mPendingVerificationToken++;
8814
8815                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8816
8817                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8818                            installerPackageName);
8819
8820                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8821
8822                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8823                            pkgLite.packageName);
8824
8825                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8826                            pkgLite.versionCode);
8827
8828                    if (verificationParams != null) {
8829                        if (verificationParams.getVerificationURI() != null) {
8830                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8831                                 verificationParams.getVerificationURI());
8832                        }
8833                        if (verificationParams.getOriginatingURI() != null) {
8834                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8835                                  verificationParams.getOriginatingURI());
8836                        }
8837                        if (verificationParams.getReferrer() != null) {
8838                            verification.putExtra(Intent.EXTRA_REFERRER,
8839                                  verificationParams.getReferrer());
8840                        }
8841                        if (verificationParams.getOriginatingUid() >= 0) {
8842                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8843                                  verificationParams.getOriginatingUid());
8844                        }
8845                        if (verificationParams.getInstallerUid() >= 0) {
8846                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8847                                  verificationParams.getInstallerUid());
8848                        }
8849                    }
8850
8851                    final PackageVerificationState verificationState = new PackageVerificationState(
8852                            requiredUid, args);
8853
8854                    mPendingVerification.append(verificationId, verificationState);
8855
8856                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8857                            receivers, verificationState);
8858
8859                    /*
8860                     * If any sufficient verifiers were listed in the package
8861                     * manifest, attempt to ask them.
8862                     */
8863                    if (sufficientVerifiers != null) {
8864                        final int N = sufficientVerifiers.size();
8865                        if (N == 0) {
8866                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8867                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8868                        } else {
8869                            for (int i = 0; i < N; i++) {
8870                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8871
8872                                final Intent sufficientIntent = new Intent(verification);
8873                                sufficientIntent.setComponent(verifierComponent);
8874
8875                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8876                            }
8877                        }
8878                    }
8879
8880                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8881                            mRequiredVerifierPackage, receivers);
8882                    if (ret == PackageManager.INSTALL_SUCCEEDED
8883                            && mRequiredVerifierPackage != null) {
8884                        /*
8885                         * Send the intent to the required verification agent,
8886                         * but only start the verification timeout after the
8887                         * target BroadcastReceivers have run.
8888                         */
8889                        verification.setComponent(requiredVerifierComponent);
8890                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8891                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8892                                new BroadcastReceiver() {
8893                                    @Override
8894                                    public void onReceive(Context context, Intent intent) {
8895                                        final Message msg = mHandler
8896                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8897                                        msg.arg1 = verificationId;
8898                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8899                                    }
8900                                }, null, 0, null, null);
8901
8902                        /*
8903                         * We don't want the copy to proceed until verification
8904                         * succeeds, so null out this field.
8905                         */
8906                        mArgs = null;
8907                    }
8908                } else {
8909                    /*
8910                     * No package verification is enabled, so immediately start
8911                     * the remote call to initiate copy using temporary file.
8912                     */
8913                    ret = args.copyApk(mContainerService, true);
8914                }
8915            }
8916
8917            mRet = ret;
8918        }
8919
8920        @Override
8921        void handleReturnCode() {
8922            // If mArgs is null, then MCS couldn't be reached. When it
8923            // reconnects, it will try again to install. At that point, this
8924            // will succeed.
8925            if (mArgs != null) {
8926                processPendingInstall(mArgs, mRet);
8927
8928                if (mTempPackage != null) {
8929                    if (!mTempPackage.delete()) {
8930                        Slog.w(TAG, "Couldn't delete temporary file: " +
8931                                mTempPackage.getAbsolutePath());
8932                    }
8933                }
8934            }
8935        }
8936
8937        @Override
8938        void handleServiceError() {
8939            mArgs = createInstallArgs(this);
8940            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8941        }
8942
8943        public boolean isForwardLocked() {
8944            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8945        }
8946
8947        public Uri getPackageUri() {
8948            if (mTempPackage != null) {
8949                return Uri.fromFile(mTempPackage);
8950            } else {
8951                return mPackageURI;
8952            }
8953        }
8954    }
8955
8956    /*
8957     * Utility class used in movePackage api.
8958     * srcArgs and targetArgs are not set for invalid flags and make
8959     * sure to do null checks when invoking methods on them.
8960     * We probably want to return ErrorPrams for both failed installs
8961     * and moves.
8962     */
8963    class MoveParams extends HandlerParams {
8964        final IPackageMoveObserver observer;
8965        final int flags;
8966        final String packageName;
8967        final InstallArgs srcArgs;
8968        final InstallArgs targetArgs;
8969        int uid;
8970        int mRet;
8971
8972        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8973                String packageName, String dataDir, String instructionSet,
8974                int uid, UserHandle user) {
8975            super(user);
8976            this.srcArgs = srcArgs;
8977            this.observer = observer;
8978            this.flags = flags;
8979            this.packageName = packageName;
8980            this.uid = uid;
8981            if (srcArgs != null) {
8982                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8983                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8984            } else {
8985                targetArgs = null;
8986            }
8987        }
8988
8989        @Override
8990        public String toString() {
8991            return "MoveParams{"
8992                + Integer.toHexString(System.identityHashCode(this))
8993                + " " + packageName + "}";
8994        }
8995
8996        public void handleStartCopy() throws RemoteException {
8997            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8998            // Check for storage space on target medium
8999            if (!targetArgs.checkFreeStorage(mContainerService)) {
9000                Log.w(TAG, "Insufficient storage to install");
9001                return;
9002            }
9003
9004            mRet = srcArgs.doPreCopy();
9005            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9006                return;
9007            }
9008
9009            mRet = targetArgs.copyApk(mContainerService, false);
9010            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9011                srcArgs.doPostCopy(uid);
9012                return;
9013            }
9014
9015            mRet = srcArgs.doPostCopy(uid);
9016            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9017                return;
9018            }
9019
9020            mRet = targetArgs.doPreInstall(mRet);
9021            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
9022                return;
9023            }
9024
9025            if (DEBUG_SD_INSTALL) {
9026                StringBuilder builder = new StringBuilder();
9027                if (srcArgs != null) {
9028                    builder.append("src: ");
9029                    builder.append(srcArgs.getCodePath());
9030                }
9031                if (targetArgs != null) {
9032                    builder.append(" target : ");
9033                    builder.append(targetArgs.getCodePath());
9034                }
9035                Log.i(TAG, builder.toString());
9036            }
9037        }
9038
9039        @Override
9040        void handleReturnCode() {
9041            targetArgs.doPostInstall(mRet, uid);
9042            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9043            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9044                currentStatus = PackageManager.MOVE_SUCCEEDED;
9045            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9046                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9047            }
9048            processPendingMove(this, currentStatus);
9049        }
9050
9051        @Override
9052        void handleServiceError() {
9053            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9054        }
9055    }
9056
9057    /**
9058     * Used during creation of InstallArgs
9059     *
9060     * @param flags package installation flags
9061     * @return true if should be installed on external storage
9062     */
9063    private static boolean installOnSd(int flags) {
9064        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9065            return false;
9066        }
9067        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9068            return true;
9069        }
9070        return false;
9071    }
9072
9073    /**
9074     * Used during creation of InstallArgs
9075     *
9076     * @param flags package installation flags
9077     * @return true if should be installed as forward locked
9078     */
9079    private static boolean installForwardLocked(int flags) {
9080        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9081    }
9082
9083    private InstallArgs createInstallArgs(InstallParams params) {
9084        if (installOnSd(params.flags) || params.isForwardLocked()) {
9085            return new AsecInstallArgs(params);
9086        } else {
9087            return new FileInstallArgs(params);
9088        }
9089    }
9090
9091    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
9092            String nativeLibraryPath, String instructionSet) {
9093        final boolean isInAsec;
9094        if (installOnSd(flags)) {
9095            /* Apps on SD card are always in ASEC containers. */
9096            isInAsec = true;
9097        } else if (installForwardLocked(flags)
9098                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9099            /*
9100             * Forward-locked apps are only in ASEC containers if they're the
9101             * new style
9102             */
9103            isInAsec = true;
9104        } else {
9105            isInAsec = false;
9106        }
9107
9108        if (isInAsec) {
9109            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9110                    instructionSet, installOnSd(flags), installForwardLocked(flags));
9111        } else {
9112            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9113                    instructionSet);
9114        }
9115    }
9116
9117    // Used by package mover
9118    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
9119            String instructionSet) {
9120        if (installOnSd(flags) || installForwardLocked(flags)) {
9121            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
9122                    + AsecInstallArgs.RES_FILE_NAME);
9123            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
9124                    installForwardLocked(flags));
9125        } else {
9126            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
9127        }
9128    }
9129
9130    static abstract class InstallArgs {
9131        final IPackageInstallObserver observer;
9132        final IPackageInstallObserver2 observer2;
9133        // Always refers to PackageManager flags only
9134        final int flags;
9135        final Uri packageURI;
9136        final String installerPackageName;
9137        final ManifestDigest manifestDigest;
9138        final UserHandle user;
9139        final String instructionSet;
9140        final String abiOverride;
9141
9142        InstallArgs(Uri packageURI,
9143                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
9144                int flags, String installerPackageName, ManifestDigest manifestDigest,
9145                UserHandle user, String instructionSet, String abiOverride) {
9146            this.packageURI = packageURI;
9147            this.flags = flags;
9148            this.observer = observer;
9149            this.observer2 = observer2;
9150            this.installerPackageName = installerPackageName;
9151            this.manifestDigest = manifestDigest;
9152            this.user = user;
9153            this.instructionSet = instructionSet;
9154            this.abiOverride = abiOverride;
9155        }
9156
9157        abstract void createCopyFile();
9158        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9159        abstract int doPreInstall(int status);
9160        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9161
9162        abstract int doPostInstall(int status, int uid);
9163        abstract String getCodePath();
9164        abstract String getResourcePath();
9165        abstract String getNativeLibraryPath();
9166        // Need installer lock especially for dex file removal.
9167        abstract void cleanUpResourcesLI();
9168        abstract boolean doPostDeleteLI(boolean delete);
9169        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9170
9171        String[] getSplitCodePaths() {
9172            return null;
9173        }
9174
9175        /**
9176         * Called before the source arguments are copied. This is used mostly
9177         * for MoveParams when it needs to read the source file to put it in the
9178         * destination.
9179         */
9180        int doPreCopy() {
9181            return PackageManager.INSTALL_SUCCEEDED;
9182        }
9183
9184        /**
9185         * Called after the source arguments are copied. This is used mostly for
9186         * MoveParams when it needs to read the source file to put it in the
9187         * destination.
9188         *
9189         * @return
9190         */
9191        int doPostCopy(int uid) {
9192            return PackageManager.INSTALL_SUCCEEDED;
9193        }
9194
9195        protected boolean isFwdLocked() {
9196            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9197        }
9198
9199        UserHandle getUser() {
9200            return user;
9201        }
9202    }
9203
9204    class FileInstallArgs extends InstallArgs {
9205        File installDir;
9206        String codeFileName;
9207        String resourceFileName;
9208        String libraryPath;
9209        boolean created = false;
9210
9211        FileInstallArgs(InstallParams params) {
9212            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9213                    params.installerPackageName, params.getManifestDigest(),
9214                    params.getUser(), params.packageInstructionSetOverride,
9215                    params.packageAbiOverride);
9216        }
9217
9218        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9219                String instructionSet) {
9220            super(null, null, null, 0, null, null, null, instructionSet, null);
9221            File codeFile = new File(fullCodePath);
9222            installDir = codeFile.getParentFile();
9223            codeFileName = fullCodePath;
9224            resourceFileName = fullResourcePath;
9225            libraryPath = nativeLibraryPath;
9226        }
9227
9228        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9229            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9230            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9231            String apkName = getNextCodePath(null, pkgName, ".apk");
9232            codeFileName = new File(installDir, apkName + ".apk").getPath();
9233            resourceFileName = getResourcePathFromCodePath();
9234            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9235        }
9236
9237        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9238            final long lowThreshold;
9239
9240            final DeviceStorageMonitorInternal
9241                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9242            if (dsm == null) {
9243                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9244                lowThreshold = 0L;
9245            } else {
9246                if (dsm.isMemoryLow()) {
9247                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9248                    return false;
9249                }
9250
9251                lowThreshold = dsm.getMemoryLowThreshold();
9252            }
9253
9254            try {
9255                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9256                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9257                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9258            } finally {
9259                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9260            }
9261        }
9262
9263        void createCopyFile() {
9264            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9265            codeFileName = createTempPackageFile(installDir).getPath();
9266            resourceFileName = getResourcePathFromCodePath();
9267            libraryPath = getLibraryPathFromCodePath();
9268            created = true;
9269        }
9270
9271        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9272            if (temp) {
9273                // Generate temp file name
9274                createCopyFile();
9275            }
9276            // Get a ParcelFileDescriptor to write to the output file
9277            File codeFile = new File(codeFileName);
9278            if (!created) {
9279                try {
9280                    codeFile.createNewFile();
9281                    // Set permissions
9282                    if (!setPermissions()) {
9283                        // Failed setting permissions.
9284                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9285                    }
9286                } catch (IOException e) {
9287                   Slog.w(TAG, "Failed to create file " + codeFile);
9288                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9289                }
9290            }
9291            ParcelFileDescriptor out = null;
9292            try {
9293                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9294            } catch (FileNotFoundException e) {
9295                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9296                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9297            }
9298            // Copy the resource now
9299            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9300            try {
9301                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9302                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9303                ret = imcs.copyResource(packageURI, null, out);
9304            } finally {
9305                IoUtils.closeQuietly(out);
9306                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9307            }
9308
9309            if (isFwdLocked()) {
9310                final File destResourceFile = new File(getResourcePath());
9311
9312                // Copy the public files
9313                try {
9314                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9315                } catch (IOException e) {
9316                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9317                            + " forward-locked app.");
9318                    destResourceFile.delete();
9319                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9320                }
9321            }
9322
9323            final File nativeLibraryFile = new File(getNativeLibraryPath());
9324            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9325            if (nativeLibraryFile.exists()) {
9326                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9327                nativeLibraryFile.delete();
9328            }
9329
9330            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9331            String[] abiList = (abiOverride != null) ?
9332                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9333            try {
9334                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9335                        abiOverride == null &&
9336                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9337                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9338                }
9339
9340                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9341                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9342                    return copyRet;
9343                }
9344            } catch (IOException e) {
9345                Slog.e(TAG, "Copying native libraries failed", e);
9346                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9347            } finally {
9348                handle.close();
9349            }
9350
9351            return ret;
9352        }
9353
9354        int doPreInstall(int status) {
9355            if (status != PackageManager.INSTALL_SUCCEEDED) {
9356                cleanUp();
9357            }
9358            return status;
9359        }
9360
9361        boolean doRename(int status, final String pkgName, String oldCodePath) {
9362            if (status != PackageManager.INSTALL_SUCCEEDED) {
9363                cleanUp();
9364                return false;
9365            } else {
9366                final File oldCodeFile = new File(getCodePath());
9367                final File oldResourceFile = new File(getResourcePath());
9368                final File oldLibraryFile = new File(getNativeLibraryPath());
9369
9370                // Rename APK file based on packageName
9371                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9372                final File newCodeFile = new File(installDir, apkName + ".apk");
9373                if (!oldCodeFile.renameTo(newCodeFile)) {
9374                    return false;
9375                }
9376                codeFileName = newCodeFile.getPath();
9377
9378                // Rename public resource file if it's forward-locked.
9379                final File newResFile = new File(getResourcePathFromCodePath());
9380                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9381                    return false;
9382                }
9383                resourceFileName = newResFile.getPath();
9384
9385                // Rename library path
9386                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9387                if (newLibraryFile.exists()) {
9388                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9389                    newLibraryFile.delete();
9390                }
9391                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9392                    Slog.e(TAG, "Cannot rename native library directory "
9393                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9394                    return false;
9395                }
9396                libraryPath = newLibraryFile.getPath();
9397
9398                // Attempt to set permissions
9399                if (!setPermissions()) {
9400                    return false;
9401                }
9402
9403                if (!SELinux.restorecon(newCodeFile)) {
9404                    return false;
9405                }
9406
9407                return true;
9408            }
9409        }
9410
9411        int doPostInstall(int status, int uid) {
9412            if (status != PackageManager.INSTALL_SUCCEEDED) {
9413                cleanUp();
9414            }
9415            return status;
9416        }
9417
9418        private String getResourcePathFromCodePath() {
9419            final String codePath = getCodePath();
9420            if (isFwdLocked()) {
9421                final StringBuilder sb = new StringBuilder();
9422
9423                sb.append(mAppInstallDir.getPath());
9424                sb.append('/');
9425                sb.append(getApkName(codePath));
9426                sb.append(".zip");
9427
9428                /*
9429                 * If our APK is a temporary file, mark the resource as a
9430                 * temporary file as well so it can be cleaned up after
9431                 * catastrophic failure.
9432                 */
9433                if (codePath.endsWith(".tmp")) {
9434                    sb.append(".tmp");
9435                }
9436
9437                return sb.toString();
9438            } else {
9439                return codePath;
9440            }
9441        }
9442
9443        private String getLibraryPathFromCodePath() {
9444            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9445        }
9446
9447        @Override
9448        String getCodePath() {
9449            return codeFileName;
9450        }
9451
9452        @Override
9453        String getResourcePath() {
9454            return resourceFileName;
9455        }
9456
9457        @Override
9458        String getNativeLibraryPath() {
9459            if (libraryPath == null) {
9460                libraryPath = getLibraryPathFromCodePath();
9461            }
9462            return libraryPath;
9463        }
9464
9465        private boolean cleanUp() {
9466            boolean ret = true;
9467            String sourceDir = getCodePath();
9468            String publicSourceDir = getResourcePath();
9469            if (sourceDir != null) {
9470                File sourceFile = new File(sourceDir);
9471                if (!sourceFile.exists()) {
9472                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9473                    ret = false;
9474                }
9475                // Delete application's code and resources
9476                sourceFile.delete();
9477            }
9478            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9479                final File publicSourceFile = new File(publicSourceDir);
9480                if (!publicSourceFile.exists()) {
9481                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9482                }
9483                if (publicSourceFile.exists()) {
9484                    publicSourceFile.delete();
9485                }
9486            }
9487
9488            if (libraryPath != null) {
9489                File nativeLibraryFile = new File(libraryPath);
9490                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9491                if (!nativeLibraryFile.delete()) {
9492                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9493                }
9494            }
9495
9496            return ret;
9497        }
9498
9499        void cleanUpResourcesLI() {
9500            String sourceDir = getCodePath();
9501            if (cleanUp()) {
9502                if (instructionSet == null) {
9503                    throw new IllegalStateException("instructionSet == null");
9504                }
9505                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9506                if (retCode < 0) {
9507                    Slog.w(TAG, "Couldn't remove dex file for package: "
9508                            +  " at location "
9509                            + sourceDir + ", retcode=" + retCode);
9510                    // we don't consider this to be a failure of the core package deletion
9511                }
9512            }
9513        }
9514
9515        private boolean setPermissions() {
9516            // TODO Do this in a more elegant way later on. for now just a hack
9517            if (!isFwdLocked()) {
9518                final int filePermissions =
9519                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9520                    |FileUtils.S_IROTH;
9521                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9522                if (retCode != 0) {
9523                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9524                            getCodePath()
9525                            + ". The return code was: " + retCode);
9526                    // TODO Define new internal error
9527                    return false;
9528                }
9529                return true;
9530            }
9531            return true;
9532        }
9533
9534        boolean doPostDeleteLI(boolean delete) {
9535            // XXX err, shouldn't we respect the delete flag?
9536            cleanUpResourcesLI();
9537            return true;
9538        }
9539    }
9540
9541    private boolean isAsecExternal(String cid) {
9542        final String asecPath = PackageHelper.getSdFilesystem(cid);
9543        return !asecPath.startsWith(mAsecInternalPath);
9544    }
9545
9546    /**
9547     * Extract the MountService "container ID" from the full code path of an
9548     * .apk.
9549     */
9550    static String cidFromCodePath(String fullCodePath) {
9551        int eidx = fullCodePath.lastIndexOf("/");
9552        String subStr1 = fullCodePath.substring(0, eidx);
9553        int sidx = subStr1.lastIndexOf("/");
9554        return subStr1.substring(sidx+1, eidx);
9555    }
9556
9557    class AsecInstallArgs extends InstallArgs {
9558        static final String RES_FILE_NAME = "pkg.apk";
9559        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9560
9561        String cid;
9562        String packagePath;
9563        String resourcePath;
9564        String libraryPath;
9565
9566        AsecInstallArgs(InstallParams params) {
9567            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9568                    params.installerPackageName, params.getManifestDigest(),
9569                    params.getUser(), params.packageInstructionSetOverride,
9570                    params.packageAbiOverride);
9571        }
9572
9573        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9574                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9575            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9576                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9577                    null, null, null, instructionSet, null);
9578            // Extract cid from fullCodePath
9579            int eidx = fullCodePath.lastIndexOf("/");
9580            String subStr1 = fullCodePath.substring(0, eidx);
9581            int sidx = subStr1.lastIndexOf("/");
9582            cid = subStr1.substring(sidx+1, eidx);
9583            setCachePath(subStr1);
9584        }
9585
9586        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9587            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9588                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9589                    null, null, null, instructionSet, null);
9590            this.cid = cid;
9591            setCachePath(PackageHelper.getSdDir(cid));
9592        }
9593
9594        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9595                boolean isExternal, boolean isForwardLocked) {
9596            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9597                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9598                    null, null, null, instructionSet, null);
9599            this.cid = cid;
9600        }
9601
9602        void createCopyFile() {
9603            cid = getTempContainerId();
9604        }
9605
9606        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9607            try {
9608                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9609                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9610                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9611            } finally {
9612                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9613            }
9614        }
9615
9616        private final boolean isExternal() {
9617            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9618        }
9619
9620        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9621            if (temp) {
9622                createCopyFile();
9623            } else {
9624                /*
9625                 * Pre-emptively destroy the container since it's destroyed if
9626                 * copying fails due to it existing anyway.
9627                 */
9628                PackageHelper.destroySdDir(cid);
9629            }
9630
9631            final String newCachePath;
9632            try {
9633                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9634                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9635                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9636                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9637                        abiOverride);
9638            } finally {
9639                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9640            }
9641
9642            if (newCachePath != null) {
9643                setCachePath(newCachePath);
9644                return PackageManager.INSTALL_SUCCEEDED;
9645            } else {
9646                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9647            }
9648        }
9649
9650        @Override
9651        String getCodePath() {
9652            return packagePath;
9653        }
9654
9655        @Override
9656        String getResourcePath() {
9657            return resourcePath;
9658        }
9659
9660        @Override
9661        String getNativeLibraryPath() {
9662            return libraryPath;
9663        }
9664
9665        int doPreInstall(int status) {
9666            if (status != PackageManager.INSTALL_SUCCEEDED) {
9667                // Destroy container
9668                PackageHelper.destroySdDir(cid);
9669            } else {
9670                boolean mounted = PackageHelper.isContainerMounted(cid);
9671                if (!mounted) {
9672                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9673                            Process.SYSTEM_UID);
9674                    if (newCachePath != null) {
9675                        setCachePath(newCachePath);
9676                    } else {
9677                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9678                    }
9679                }
9680            }
9681            return status;
9682        }
9683
9684        boolean doRename(int status, final String pkgName,
9685                String oldCodePath) {
9686            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9687            String newCachePath = null;
9688            if (PackageHelper.isContainerMounted(cid)) {
9689                // Unmount the container
9690                if (!PackageHelper.unMountSdDir(cid)) {
9691                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9692                    return false;
9693                }
9694            }
9695            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9696                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9697                        " which might be stale. Will try to clean up.");
9698                // Clean up the stale container and proceed to recreate.
9699                if (!PackageHelper.destroySdDir(newCacheId)) {
9700                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9701                    return false;
9702                }
9703                // Successfully cleaned up stale container. Try to rename again.
9704                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9705                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9706                            + " inspite of cleaning it up.");
9707                    return false;
9708                }
9709            }
9710            if (!PackageHelper.isContainerMounted(newCacheId)) {
9711                Slog.w(TAG, "Mounting container " + newCacheId);
9712                newCachePath = PackageHelper.mountSdDir(newCacheId,
9713                        getEncryptKey(), Process.SYSTEM_UID);
9714            } else {
9715                newCachePath = PackageHelper.getSdDir(newCacheId);
9716            }
9717            if (newCachePath == null) {
9718                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9719                return false;
9720            }
9721            Log.i(TAG, "Succesfully renamed " + cid +
9722                    " to " + newCacheId +
9723                    " at new path: " + newCachePath);
9724            cid = newCacheId;
9725            setCachePath(newCachePath);
9726            return true;
9727        }
9728
9729        private void setCachePath(String newCachePath) {
9730            File cachePath = new File(newCachePath);
9731            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9732            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9733
9734            if (isFwdLocked()) {
9735                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9736            } else {
9737                resourcePath = packagePath;
9738            }
9739        }
9740
9741        int doPostInstall(int status, int uid) {
9742            if (status != PackageManager.INSTALL_SUCCEEDED) {
9743                cleanUp();
9744            } else {
9745                final int groupOwner;
9746                final String protectedFile;
9747                if (isFwdLocked()) {
9748                    groupOwner = UserHandle.getSharedAppGid(uid);
9749                    protectedFile = RES_FILE_NAME;
9750                } else {
9751                    groupOwner = -1;
9752                    protectedFile = null;
9753                }
9754
9755                if (uid < Process.FIRST_APPLICATION_UID
9756                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9757                    Slog.e(TAG, "Failed to finalize " + cid);
9758                    PackageHelper.destroySdDir(cid);
9759                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9760                }
9761
9762                boolean mounted = PackageHelper.isContainerMounted(cid);
9763                if (!mounted) {
9764                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9765                }
9766            }
9767            return status;
9768        }
9769
9770        private void cleanUp() {
9771            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9772
9773            // Destroy secure container
9774            PackageHelper.destroySdDir(cid);
9775        }
9776
9777        void cleanUpResourcesLI() {
9778            String sourceFile = getCodePath();
9779            // Remove dex file
9780            if (instructionSet == null) {
9781                throw new IllegalStateException("instructionSet == null");
9782            }
9783            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9784            if (retCode < 0) {
9785                Slog.w(TAG, "Couldn't remove dex file for package: "
9786                        + " at location "
9787                        + sourceFile.toString() + ", retcode=" + retCode);
9788                // we don't consider this to be a failure of the core package deletion
9789            }
9790            cleanUp();
9791        }
9792
9793        boolean matchContainer(String app) {
9794            if (cid.startsWith(app)) {
9795                return true;
9796            }
9797            return false;
9798        }
9799
9800        String getPackageName() {
9801            return getAsecPackageName(cid);
9802        }
9803
9804        boolean doPostDeleteLI(boolean delete) {
9805            boolean ret = false;
9806            boolean mounted = PackageHelper.isContainerMounted(cid);
9807            if (mounted) {
9808                // Unmount first
9809                ret = PackageHelper.unMountSdDir(cid);
9810            }
9811            if (ret && delete) {
9812                cleanUpResourcesLI();
9813            }
9814            return ret;
9815        }
9816
9817        @Override
9818        int doPreCopy() {
9819            if (isFwdLocked()) {
9820                if (!PackageHelper.fixSdPermissions(cid,
9821                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9822                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9823                }
9824            }
9825
9826            return PackageManager.INSTALL_SUCCEEDED;
9827        }
9828
9829        @Override
9830        int doPostCopy(int uid) {
9831            if (isFwdLocked()) {
9832                if (uid < Process.FIRST_APPLICATION_UID
9833                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9834                                RES_FILE_NAME)) {
9835                    Slog.e(TAG, "Failed to finalize " + cid);
9836                    PackageHelper.destroySdDir(cid);
9837                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9838                }
9839            }
9840
9841            return PackageManager.INSTALL_SUCCEEDED;
9842        }
9843    }
9844
9845    static String getAsecPackageName(String packageCid) {
9846        int idx = packageCid.lastIndexOf("-");
9847        if (idx == -1) {
9848            return packageCid;
9849        }
9850        return packageCid.substring(0, idx);
9851    }
9852
9853    // Utility method used to create code paths based on package name and available index.
9854    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9855        String idxStr = "";
9856        int idx = 1;
9857        // Fall back to default value of idx=1 if prefix is not
9858        // part of oldCodePath
9859        if (oldCodePath != null) {
9860            String subStr = oldCodePath;
9861            // Drop the suffix right away
9862            if (subStr.endsWith(suffix)) {
9863                subStr = subStr.substring(0, subStr.length() - suffix.length());
9864            }
9865            // If oldCodePath already contains prefix find out the
9866            // ending index to either increment or decrement.
9867            int sidx = subStr.lastIndexOf(prefix);
9868            if (sidx != -1) {
9869                subStr = subStr.substring(sidx + prefix.length());
9870                if (subStr != null) {
9871                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9872                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9873                    }
9874                    try {
9875                        idx = Integer.parseInt(subStr);
9876                        if (idx <= 1) {
9877                            idx++;
9878                        } else {
9879                            idx--;
9880                        }
9881                    } catch(NumberFormatException e) {
9882                    }
9883                }
9884            }
9885        }
9886        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9887        return prefix + idxStr;
9888    }
9889
9890    // Utility method used to ignore ADD/REMOVE events
9891    // by directory observer.
9892    private static boolean ignoreCodePath(String fullPathStr) {
9893        String apkName = getApkName(fullPathStr);
9894        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9895        if (idx != -1 && ((idx+1) < apkName.length())) {
9896            // Make sure the package ends with a numeral
9897            String version = apkName.substring(idx+1);
9898            try {
9899                Integer.parseInt(version);
9900                return true;
9901            } catch (NumberFormatException e) {}
9902        }
9903        return false;
9904    }
9905
9906    // Utility method that returns the relative package path with respect
9907    // to the installation directory. Like say for /data/data/com.test-1.apk
9908    // string com.test-1 is returned.
9909    static String getApkName(String codePath) {
9910        if (codePath == null) {
9911            return null;
9912        }
9913        int sidx = codePath.lastIndexOf("/");
9914        int eidx = codePath.lastIndexOf(".");
9915        if (eidx == -1) {
9916            eidx = codePath.length();
9917        } else if (eidx == 0) {
9918            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9919            return null;
9920        }
9921        return codePath.substring(sidx+1, eidx);
9922    }
9923
9924    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9925        String[] splitResPaths = null;
9926        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9927            splitResPaths = new String[splitCodePaths.length];
9928            for (int i = 0; i < splitCodePaths.length; i++) {
9929                final String splitCodePath = splitCodePaths[i];
9930                final String resName = getApkName(splitCodePath) + ".zip";
9931                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9932                        resName).getAbsolutePath();
9933            }
9934        }
9935        return splitResPaths;
9936    }
9937
9938    class PackageInstalledInfo {
9939        String name;
9940        int uid;
9941        // The set of users that originally had this package installed.
9942        int[] origUsers;
9943        // The set of users that now have this package installed.
9944        int[] newUsers;
9945        PackageParser.Package pkg;
9946        int returnCode;
9947        PackageRemovedInfo removedInfo;
9948
9949        // In some error cases we want to convey more info back to the observer
9950        String origPackage;
9951        String origPermission;
9952    }
9953
9954    /*
9955     * Install a non-existing package.
9956     */
9957    private void installNewPackageLI(PackageParser.Package pkg,
9958            int parseFlags, int scanMode, UserHandle user,
9959            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9960        // Remember this for later, in case we need to rollback this install
9961        String pkgName = pkg.packageName;
9962
9963        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9964        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9965        synchronized(mPackages) {
9966            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9967                // A package with the same name is already installed, though
9968                // it has been renamed to an older name.  The package we
9969                // are trying to install should be installed as an update to
9970                // the existing one, but that has not been requested, so bail.
9971                Slog.w(TAG, "Attempt to re-install " + pkgName
9972                        + " without first uninstalling package running as "
9973                        + mSettings.mRenamedPackages.get(pkgName));
9974                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9975                return;
9976            }
9977            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9978                // Don't allow installation over an existing package with the same name.
9979                Slog.w(TAG, "Attempt to re-install " + pkgName
9980                        + " without first uninstalling.");
9981                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9982                return;
9983            }
9984        }
9985        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9986        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9987                System.currentTimeMillis(), user, abiOverride);
9988        if (newPackage == null) {
9989            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9990            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9991                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9992            }
9993        } else {
9994            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9995            // delete the partially installed application. the data directory will have to be
9996            // restored if it was already existing
9997            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9998                // remove package from internal structures.  Note that we want deletePackageX to
9999                // delete the package data and cache directories that it created in
10000                // scanPackageLocked, unless those directories existed before we even tried to
10001                // install.
10002                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10003                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10004                                res.removedInfo, true);
10005            }
10006        }
10007    }
10008
10009    private void replacePackageLI(PackageParser.Package pkg,
10010            int parseFlags, int scanMode, UserHandle user,
10011            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10012
10013        PackageParser.Package oldPackage;
10014        String pkgName = pkg.packageName;
10015        int[] allUsers;
10016        boolean[] perUserInstalled;
10017
10018        // First find the old package info and check signatures
10019        synchronized(mPackages) {
10020            oldPackage = mPackages.get(pkgName);
10021            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10022            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10023                    != PackageManager.SIGNATURE_MATCH) {
10024                Slog.w(TAG, "New package has a different signature: " + pkgName);
10025                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
10026                return;
10027            }
10028
10029            // In case of rollback, remember per-user/profile install state
10030            PackageSetting ps = mSettings.mPackages.get(pkgName);
10031            allUsers = sUserManager.getUserIds();
10032            perUserInstalled = new boolean[allUsers.length];
10033            for (int i = 0; i < allUsers.length; i++) {
10034                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10035            }
10036        }
10037        boolean sysPkg = (isSystemApp(oldPackage));
10038        if (sysPkg) {
10039            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10040                    user, allUsers, perUserInstalled, installerPackageName, res,
10041                    abiOverride);
10042        } else {
10043            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10044                    user, allUsers, perUserInstalled, installerPackageName, res,
10045                    abiOverride);
10046        }
10047    }
10048
10049    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10050            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10051            int[] allUsers, boolean[] perUserInstalled,
10052            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10053        PackageParser.Package newPackage = null;
10054        String pkgName = deletedPackage.packageName;
10055        boolean deletedPkg = true;
10056        boolean updatedSettings = false;
10057
10058        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10059                + deletedPackage);
10060        long origUpdateTime;
10061        if (pkg.mExtras != null) {
10062            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10063        } else {
10064            origUpdateTime = 0;
10065        }
10066
10067        // First delete the existing package while retaining the data directory
10068        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10069                res.removedInfo, true)) {
10070            // If the existing package wasn't successfully deleted
10071            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10072            deletedPkg = false;
10073        } else {
10074            // Successfully deleted the old package. Now proceed with re-installation
10075            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10076            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
10077                    System.currentTimeMillis(), user, abiOverride);
10078            if (newPackage == null) {
10079                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10080                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10081                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10082                }
10083            } else {
10084                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10085                updatedSettings = true;
10086            }
10087        }
10088
10089        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10090            // remove package from internal structures.  Note that we want deletePackageX to
10091            // delete the package data and cache directories that it created in
10092            // scanPackageLocked, unless those directories existed before we even tried to
10093            // install.
10094            if(updatedSettings) {
10095                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10096                deletePackageLI(
10097                        pkgName, null, true, allUsers, perUserInstalled,
10098                        PackageManager.DELETE_KEEP_DATA,
10099                                res.removedInfo, true);
10100            }
10101            // Since we failed to install the new package we need to restore the old
10102            // package that we deleted.
10103            if (deletedPkg) {
10104                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10105                File restoreFile = new File(deletedPackage.codePath);
10106                // Parse old package
10107                boolean oldOnSd = isExternal(deletedPackage);
10108                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10109                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10110                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10111                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10112                        | SCAN_UPDATE_TIME;
10113                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
10114                        origUpdateTime, null, null) == null) {
10115                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
10116                    return;
10117                }
10118                // Restore of old package succeeded. Update permissions.
10119                // writer
10120                synchronized (mPackages) {
10121                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10122                            UPDATE_PERMISSIONS_ALL);
10123                    // can downgrade to reader
10124                    mSettings.writeLPr();
10125                }
10126                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10127            }
10128        }
10129    }
10130
10131    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10132            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10133            int[] allUsers, boolean[] perUserInstalled,
10134            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10135        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10136                + ", old=" + deletedPackage);
10137        PackageParser.Package newPackage = null;
10138        boolean updatedSettings = false;
10139        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10140                PackageParser.PARSE_IS_SYSTEM;
10141        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10142            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10143        }
10144        String packageName = deletedPackage.packageName;
10145        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10146        if (packageName == null) {
10147            Slog.w(TAG, "Attempt to delete null packageName.");
10148            return;
10149        }
10150        PackageParser.Package oldPkg;
10151        PackageSetting oldPkgSetting;
10152        // reader
10153        synchronized (mPackages) {
10154            oldPkg = mPackages.get(packageName);
10155            oldPkgSetting = mSettings.mPackages.get(packageName);
10156            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10157                    (oldPkgSetting == null)) {
10158                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10159                return;
10160            }
10161        }
10162
10163        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10164
10165        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10166        res.removedInfo.removedPackage = packageName;
10167        // Remove existing system package
10168        removePackageLI(oldPkgSetting, true);
10169        // writer
10170        synchronized (mPackages) {
10171            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10172                // We didn't need to disable the .apk as a current system package,
10173                // which means we are replacing another update that is already
10174                // installed.  We need to make sure to delete the older one's .apk.
10175                res.removedInfo.args = createInstallArgs(0,
10176                        deletedPackage.applicationInfo.sourceDir,
10177                        deletedPackage.applicationInfo.publicSourceDir,
10178                        deletedPackage.applicationInfo.nativeLibraryDir,
10179                        getAppInstructionSet(deletedPackage.applicationInfo));
10180            } else {
10181                res.removedInfo.args = null;
10182            }
10183        }
10184
10185        // Successfully disabled the old package. Now proceed with re-installation
10186        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10187        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10188        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10189        if (newPackage == null) {
10190            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10191            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10192                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10193            }
10194        } else {
10195            if (newPackage.mExtras != null) {
10196                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10197                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10198                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10199
10200                // is the update attempting to change shared user? that isn't going to work...
10201                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10202                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10203                            + " to " + newPkgSetting.sharedUser);
10204                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10205                    updatedSettings = true;
10206                }
10207            }
10208
10209            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10210                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10211                updatedSettings = true;
10212            }
10213        }
10214
10215        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10216            // Re installation failed. Restore old information
10217            // Remove new pkg information
10218            if (newPackage != null) {
10219                removeInstalledPackageLI(newPackage, true);
10220            }
10221            // Add back the old system package
10222            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10223            // Restore the old system information in Settings
10224            synchronized(mPackages) {
10225                if (updatedSettings) {
10226                    mSettings.enableSystemPackageLPw(packageName);
10227                    mSettings.setInstallerPackageName(packageName,
10228                            oldPkgSetting.installerPackageName);
10229                }
10230                mSettings.writeLPr();
10231            }
10232        }
10233    }
10234
10235    // Utility method used to move dex files during install.
10236    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10237        // TODO: extend to move split APK dex files
10238        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10239            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10240            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10241                                             instructionSet);
10242            if (retCode != 0) {
10243                /*
10244                 * Programs may be lazily run through dexopt, so the
10245                 * source may not exist. However, something seems to
10246                 * have gone wrong, so note that dexopt needs to be
10247                 * run again and remove the source file. In addition,
10248                 * remove the target to make sure there isn't a stale
10249                 * file from a previous version of the package.
10250                 */
10251                newPackage.mDexOptNeeded = true;
10252                mInstaller.rmdex(oldCodePath, instructionSet);
10253                mInstaller.rmdex(newPackage.codePath, instructionSet);
10254            }
10255        }
10256        return PackageManager.INSTALL_SUCCEEDED;
10257    }
10258
10259    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10260            int[] allUsers, boolean[] perUserInstalled,
10261            PackageInstalledInfo res) {
10262        String pkgName = newPackage.packageName;
10263        synchronized (mPackages) {
10264            //write settings. the installStatus will be incomplete at this stage.
10265            //note that the new package setting would have already been
10266            //added to mPackages. It hasn't been persisted yet.
10267            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10268            mSettings.writeLPr();
10269        }
10270
10271        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10272
10273        synchronized (mPackages) {
10274            updatePermissionsLPw(newPackage.packageName, newPackage,
10275                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10276                            ? UPDATE_PERMISSIONS_ALL : 0));
10277            // For system-bundled packages, we assume that installing an upgraded version
10278            // of the package implies that the user actually wants to run that new code,
10279            // so we enable the package.
10280            if (isSystemApp(newPackage)) {
10281                // NB: implicit assumption that system package upgrades apply to all users
10282                if (DEBUG_INSTALL) {
10283                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10284                }
10285                PackageSetting ps = mSettings.mPackages.get(pkgName);
10286                if (ps != null) {
10287                    if (res.origUsers != null) {
10288                        for (int userHandle : res.origUsers) {
10289                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10290                                    userHandle, installerPackageName);
10291                        }
10292                    }
10293                    // Also convey the prior install/uninstall state
10294                    if (allUsers != null && perUserInstalled != null) {
10295                        for (int i = 0; i < allUsers.length; i++) {
10296                            if (DEBUG_INSTALL) {
10297                                Slog.d(TAG, "    user " + allUsers[i]
10298                                        + " => " + perUserInstalled[i]);
10299                            }
10300                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10301                        }
10302                        // these install state changes will be persisted in the
10303                        // upcoming call to mSettings.writeLPr().
10304                    }
10305                }
10306            }
10307            res.name = pkgName;
10308            res.uid = newPackage.applicationInfo.uid;
10309            res.pkg = newPackage;
10310            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10311            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10312            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10313            //to update install status
10314            mSettings.writeLPr();
10315        }
10316    }
10317
10318    private void installPackageLI(InstallArgs args,
10319            boolean newInstall, PackageInstalledInfo res) {
10320        int pFlags = args.flags;
10321        String installerPackageName = args.installerPackageName;
10322        File tmpPackageFile = new File(args.getCodePath());
10323        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10324        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10325        boolean replace = false;
10326        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10327                | (newInstall ? SCAN_NEW_INSTALL : 0);
10328        // Result object to be returned
10329        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10330
10331        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10332        // Retrieve PackageSettings and parse package
10333        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10334                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10335                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10336        PackageParser pp = new PackageParser();
10337        pp.setSeparateProcesses(mSeparateProcesses);
10338        pp.setDisplayMetrics(mMetrics);
10339
10340        final PackageParser.Package pkg;
10341        try {
10342            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10343        } catch (PackageParserException e) {
10344            res.returnCode = e.error;
10345            return;
10346        }
10347
10348        String pkgName = res.name = pkg.packageName;
10349        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10350            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10351                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10352                return;
10353            }
10354        }
10355
10356        try {
10357            pp.collectCertificates(pkg, parseFlags);
10358            pp.collectManifestDigest(pkg);
10359        } catch (PackageParserException e) {
10360            res.returnCode = e.error;
10361            return;
10362        }
10363
10364        /* If the installer passed in a manifest digest, compare it now. */
10365        if (args.manifestDigest != null) {
10366            if (DEBUG_INSTALL) {
10367                final String parsedManifest = pkg.manifestDigest == null ? "null"
10368                        : pkg.manifestDigest.toString();
10369                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10370                        + parsedManifest);
10371            }
10372
10373            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10374                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10375                return;
10376            }
10377        } else if (DEBUG_INSTALL) {
10378            final String parsedManifest = pkg.manifestDigest == null
10379                    ? "null" : pkg.manifestDigest.toString();
10380            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10381        }
10382
10383        // Get rid of all references to package scan path via parser.
10384        pp = null;
10385        String oldCodePath = null;
10386        boolean systemApp = false;
10387        synchronized (mPackages) {
10388            // Check whether the newly-scanned package wants to define an already-defined perm
10389            int N = pkg.permissions.size();
10390            for (int i = N-1; i >= 0; i--) {
10391                PackageParser.Permission perm = pkg.permissions.get(i);
10392                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10393                if (bp != null) {
10394                    // If the defining package is signed with our cert, it's okay.  This
10395                    // also includes the "updating the same package" case, of course.
10396                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10397                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10398                        // If the owning package is the system itself, we log but allow
10399                        // install to proceed; we fail the install on all other permission
10400                        // redefinitions.
10401                        if (!bp.sourcePackage.equals("android")) {
10402                            Slog.w(TAG, "Package " + pkg.packageName
10403                                    + " attempting to redeclare permission " + perm.info.name
10404                                    + " already owned by " + bp.sourcePackage);
10405                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10406                            res.origPermission = perm.info.name;
10407                            res.origPackage = bp.sourcePackage;
10408                            return;
10409                        } else {
10410                            Slog.w(TAG, "Package " + pkg.packageName
10411                                    + " attempting to redeclare system permission "
10412                                    + perm.info.name + "; ignoring new declaration");
10413                            pkg.permissions.remove(i);
10414                        }
10415                    }
10416                }
10417            }
10418
10419            // Check if installing already existing package
10420            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10421                String oldName = mSettings.mRenamedPackages.get(pkgName);
10422                if (pkg.mOriginalPackages != null
10423                        && pkg.mOriginalPackages.contains(oldName)
10424                        && mPackages.containsKey(oldName)) {
10425                    // This package is derived from an original package,
10426                    // and this device has been updating from that original
10427                    // name.  We must continue using the original name, so
10428                    // rename the new package here.
10429                    pkg.setPackageName(oldName);
10430                    pkgName = pkg.packageName;
10431                    replace = true;
10432                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10433                            + oldName + " pkgName=" + pkgName);
10434                } else if (mPackages.containsKey(pkgName)) {
10435                    // This package, under its official name, already exists
10436                    // on the device; we should replace it.
10437                    replace = true;
10438                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10439                }
10440            }
10441            PackageSetting ps = mSettings.mPackages.get(pkgName);
10442            if (ps != null) {
10443                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10444                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10445                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10446                    systemApp = (ps.pkg.applicationInfo.flags &
10447                            ApplicationInfo.FLAG_SYSTEM) != 0;
10448                }
10449                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10450            }
10451        }
10452
10453        if (systemApp && onSd) {
10454            // Disable updates to system apps on sdcard
10455            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10456            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10457            return;
10458        }
10459
10460        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10461            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10462            return;
10463        }
10464        // Set application objects path explicitly after the rename
10465        pkg.codePath = args.getCodePath();
10466        pkg.applicationInfo.sourceDir = args.getCodePath();
10467        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10468        pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths();
10469        pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths(
10470                pkg.applicationInfo.splitSourceDirs);
10471        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10472        if (replace) {
10473            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10474                    installerPackageName, res, args.abiOverride);
10475        } else {
10476            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10477                    installerPackageName, res, args.abiOverride);
10478        }
10479        synchronized (mPackages) {
10480            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10481            if (ps != null) {
10482                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10483            }
10484        }
10485    }
10486
10487    private static boolean isForwardLocked(PackageParser.Package pkg) {
10488        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10489    }
10490
10491
10492    private boolean isForwardLocked(PackageSetting ps) {
10493        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10494    }
10495
10496    private static boolean isExternal(PackageParser.Package pkg) {
10497        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10498    }
10499
10500    private static boolean isExternal(PackageSetting ps) {
10501        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10502    }
10503
10504    private static boolean isSystemApp(PackageParser.Package pkg) {
10505        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10506    }
10507
10508    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10509        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10510    }
10511
10512    private static boolean isSystemApp(ApplicationInfo info) {
10513        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10514    }
10515
10516    private static boolean isSystemApp(PackageSetting ps) {
10517        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10518    }
10519
10520    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10521        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10522    }
10523
10524    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10525        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10526    }
10527
10528    private int packageFlagsToInstallFlags(PackageSetting ps) {
10529        int installFlags = 0;
10530        if (isExternal(ps)) {
10531            installFlags |= PackageManager.INSTALL_EXTERNAL;
10532        }
10533        if (isForwardLocked(ps)) {
10534            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10535        }
10536        return installFlags;
10537    }
10538
10539    private void deleteTempPackageFiles() {
10540        final FilenameFilter filter = new FilenameFilter() {
10541            public boolean accept(File dir, String name) {
10542                return name.startsWith("vmdl") && name.endsWith(".tmp");
10543            }
10544        };
10545        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10546        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10547    }
10548
10549    private static final void deleteTempPackageFilesInDirectory(File directory,
10550            FilenameFilter filter) {
10551        final String[] tmpFilesList = directory.list(filter);
10552        if (tmpFilesList == null) {
10553            return;
10554        }
10555        for (int i = 0; i < tmpFilesList.length; i++) {
10556            final File tmpFile = new File(directory, tmpFilesList[i]);
10557            tmpFile.delete();
10558        }
10559    }
10560
10561    private File createTempPackageFile(File installDir) {
10562        File tmpPackageFile;
10563        try {
10564            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10565        } catch (IOException e) {
10566            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10567            return null;
10568        }
10569        try {
10570            FileUtils.setPermissions(
10571                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10572                    -1, -1);
10573            if (!SELinux.restorecon(tmpPackageFile)) {
10574                return null;
10575            }
10576        } catch (IOException e) {
10577            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10578            return null;
10579        }
10580        return tmpPackageFile;
10581    }
10582
10583    @Override
10584    public void deletePackageAsUser(final String packageName,
10585                                    final IPackageDeleteObserver observer,
10586                                    final int userId, final int flags) {
10587        mContext.enforceCallingOrSelfPermission(
10588                android.Manifest.permission.DELETE_PACKAGES, null);
10589        final int uid = Binder.getCallingUid();
10590        if (UserHandle.getUserId(uid) != userId) {
10591            mContext.enforceCallingPermission(
10592                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10593                    "deletePackage for user " + userId);
10594        }
10595        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10596            try {
10597                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10598            } catch (RemoteException re) {
10599            }
10600            return;
10601        }
10602
10603        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10604        // Queue up an async operation since the package deletion may take a little while.
10605        mHandler.post(new Runnable() {
10606            public void run() {
10607                mHandler.removeCallbacks(this);
10608                final int returnCode = deletePackageX(packageName, userId, flags);
10609                if (observer != null) {
10610                    try {
10611                        observer.packageDeleted(packageName, returnCode);
10612                    } catch (RemoteException e) {
10613                        Log.i(TAG, "Observer no longer exists.");
10614                    } //end catch
10615                } //end if
10616            } //end run
10617        });
10618    }
10619
10620    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10621        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10622                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10623        try {
10624            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10625                    || dpm.isDeviceOwner(packageName))) {
10626                return true;
10627            }
10628        } catch (RemoteException e) {
10629        }
10630        return false;
10631    }
10632
10633    /**
10634     *  This method is an internal method that could be get invoked either
10635     *  to delete an installed package or to clean up a failed installation.
10636     *  After deleting an installed package, a broadcast is sent to notify any
10637     *  listeners that the package has been installed. For cleaning up a failed
10638     *  installation, the broadcast is not necessary since the package's
10639     *  installation wouldn't have sent the initial broadcast either
10640     *  The key steps in deleting a package are
10641     *  deleting the package information in internal structures like mPackages,
10642     *  deleting the packages base directories through installd
10643     *  updating mSettings to reflect current status
10644     *  persisting settings for later use
10645     *  sending a broadcast if necessary
10646     */
10647    private int deletePackageX(String packageName, int userId, int flags) {
10648        final PackageRemovedInfo info = new PackageRemovedInfo();
10649        final boolean res;
10650
10651        if (isPackageDeviceAdmin(packageName, userId)) {
10652            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10653            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10654        }
10655
10656        boolean removedForAllUsers = false;
10657        boolean systemUpdate = false;
10658
10659        // for the uninstall-updates case and restricted profiles, remember the per-
10660        // userhandle installed state
10661        int[] allUsers;
10662        boolean[] perUserInstalled;
10663        synchronized (mPackages) {
10664            PackageSetting ps = mSettings.mPackages.get(packageName);
10665            allUsers = sUserManager.getUserIds();
10666            perUserInstalled = new boolean[allUsers.length];
10667            for (int i = 0; i < allUsers.length; i++) {
10668                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10669            }
10670        }
10671
10672        synchronized (mInstallLock) {
10673            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10674            res = deletePackageLI(packageName,
10675                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10676                            ? UserHandle.ALL : new UserHandle(userId),
10677                    true, allUsers, perUserInstalled,
10678                    flags | REMOVE_CHATTY, info, true);
10679            systemUpdate = info.isRemovedPackageSystemUpdate;
10680            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10681                removedForAllUsers = true;
10682            }
10683            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10684                    + " removedForAllUsers=" + removedForAllUsers);
10685        }
10686
10687        if (res) {
10688            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10689
10690            // If the removed package was a system update, the old system package
10691            // was re-enabled; we need to broadcast this information
10692            if (systemUpdate) {
10693                Bundle extras = new Bundle(1);
10694                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10695                        ? info.removedAppId : info.uid);
10696                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10697
10698                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10699                        extras, null, null, null);
10700                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10701                        extras, null, null, null);
10702                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10703                        null, packageName, null, null);
10704            }
10705        }
10706        // Force a gc here.
10707        Runtime.getRuntime().gc();
10708        // Delete the resources here after sending the broadcast to let
10709        // other processes clean up before deleting resources.
10710        if (info.args != null) {
10711            synchronized (mInstallLock) {
10712                info.args.doPostDeleteLI(true);
10713            }
10714        }
10715
10716        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10717    }
10718
10719    static class PackageRemovedInfo {
10720        String removedPackage;
10721        int uid = -1;
10722        int removedAppId = -1;
10723        int[] removedUsers = null;
10724        boolean isRemovedPackageSystemUpdate = false;
10725        // Clean up resources deleted packages.
10726        InstallArgs args = null;
10727
10728        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10729            Bundle extras = new Bundle(1);
10730            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10731            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10732            if (replacing) {
10733                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10734            }
10735            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10736            if (removedPackage != null) {
10737                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10738                        extras, null, null, removedUsers);
10739                if (fullRemove && !replacing) {
10740                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10741                            extras, null, null, removedUsers);
10742                }
10743            }
10744            if (removedAppId >= 0) {
10745                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10746                        removedUsers);
10747            }
10748        }
10749    }
10750
10751    /*
10752     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10753     * flag is not set, the data directory is removed as well.
10754     * make sure this flag is set for partially installed apps. If not its meaningless to
10755     * delete a partially installed application.
10756     */
10757    private void removePackageDataLI(PackageSetting ps,
10758            int[] allUserHandles, boolean[] perUserInstalled,
10759            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10760        String packageName = ps.name;
10761        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10762        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10763        // Retrieve object to delete permissions for shared user later on
10764        final PackageSetting deletedPs;
10765        // reader
10766        synchronized (mPackages) {
10767            deletedPs = mSettings.mPackages.get(packageName);
10768            if (outInfo != null) {
10769                outInfo.removedPackage = packageName;
10770                outInfo.removedUsers = deletedPs != null
10771                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10772                        : null;
10773            }
10774        }
10775        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10776            removeDataDirsLI(packageName);
10777            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10778        }
10779        // writer
10780        synchronized (mPackages) {
10781            if (deletedPs != null) {
10782                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10783                    if (outInfo != null) {
10784                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10785                    }
10786                    if (deletedPs != null) {
10787                        updatePermissionsLPw(deletedPs.name, null, 0);
10788                        if (deletedPs.sharedUser != null) {
10789                            // remove permissions associated with package
10790                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10791                        }
10792                    }
10793                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10794                }
10795                // make sure to preserve per-user disabled state if this removal was just
10796                // a downgrade of a system app to the factory package
10797                if (allUserHandles != null && perUserInstalled != null) {
10798                    if (DEBUG_REMOVE) {
10799                        Slog.d(TAG, "Propagating install state across downgrade");
10800                    }
10801                    for (int i = 0; i < allUserHandles.length; i++) {
10802                        if (DEBUG_REMOVE) {
10803                            Slog.d(TAG, "    user " + allUserHandles[i]
10804                                    + " => " + perUserInstalled[i]);
10805                        }
10806                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10807                    }
10808                }
10809            }
10810            // can downgrade to reader
10811            if (writeSettings) {
10812                // Save settings now
10813                mSettings.writeLPr();
10814            }
10815        }
10816        if (outInfo != null) {
10817            // A user ID was deleted here. Go through all users and remove it
10818            // from KeyStore.
10819            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10820        }
10821    }
10822
10823    static boolean locationIsPrivileged(File path) {
10824        try {
10825            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10826                    .getCanonicalPath();
10827            return path.getCanonicalPath().startsWith(privilegedAppDir);
10828        } catch (IOException e) {
10829            Slog.e(TAG, "Unable to access code path " + path);
10830        }
10831        return false;
10832    }
10833
10834    /*
10835     * Tries to delete system package.
10836     */
10837    private boolean deleteSystemPackageLI(PackageSetting newPs,
10838            int[] allUserHandles, boolean[] perUserInstalled,
10839            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10840        final boolean applyUserRestrictions
10841                = (allUserHandles != null) && (perUserInstalled != null);
10842        PackageSetting disabledPs = null;
10843        // Confirm if the system package has been updated
10844        // An updated system app can be deleted. This will also have to restore
10845        // the system pkg from system partition
10846        // reader
10847        synchronized (mPackages) {
10848            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10849        }
10850        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10851                + " disabledPs=" + disabledPs);
10852        if (disabledPs == null) {
10853            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10854            return false;
10855        } else if (DEBUG_REMOVE) {
10856            Slog.d(TAG, "Deleting system pkg from data partition");
10857        }
10858        if (DEBUG_REMOVE) {
10859            if (applyUserRestrictions) {
10860                Slog.d(TAG, "Remembering install states:");
10861                for (int i = 0; i < allUserHandles.length; i++) {
10862                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10863                }
10864            }
10865        }
10866        // Delete the updated package
10867        outInfo.isRemovedPackageSystemUpdate = true;
10868        if (disabledPs.versionCode < newPs.versionCode) {
10869            // Delete data for downgrades
10870            flags &= ~PackageManager.DELETE_KEEP_DATA;
10871        } else {
10872            // Preserve data by setting flag
10873            flags |= PackageManager.DELETE_KEEP_DATA;
10874        }
10875        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10876                allUserHandles, perUserInstalled, outInfo, writeSettings);
10877        if (!ret) {
10878            return false;
10879        }
10880        // writer
10881        synchronized (mPackages) {
10882            // Reinstate the old system package
10883            mSettings.enableSystemPackageLPw(newPs.name);
10884            // Remove any native libraries from the upgraded package.
10885            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10886        }
10887        // Install the system package
10888        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10889        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10890        if (locationIsPrivileged(disabledPs.codePath)) {
10891            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10892        }
10893        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10894                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10895
10896        if (newPkg == null) {
10897            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10898                    + " with error:" + mLastScanError);
10899            return false;
10900        }
10901        // writer
10902        synchronized (mPackages) {
10903            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10904            setInternalAppNativeLibraryPath(newPkg, ps);
10905            updatePermissionsLPw(newPkg.packageName, newPkg,
10906                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10907            if (applyUserRestrictions) {
10908                if (DEBUG_REMOVE) {
10909                    Slog.d(TAG, "Propagating install state across reinstall");
10910                }
10911                for (int i = 0; i < allUserHandles.length; i++) {
10912                    if (DEBUG_REMOVE) {
10913                        Slog.d(TAG, "    user " + allUserHandles[i]
10914                                + " => " + perUserInstalled[i]);
10915                    }
10916                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10917                }
10918                // Regardless of writeSettings we need to ensure that this restriction
10919                // state propagation is persisted
10920                mSettings.writeAllUsersPackageRestrictionsLPr();
10921            }
10922            // can downgrade to reader here
10923            if (writeSettings) {
10924                mSettings.writeLPr();
10925            }
10926        }
10927        return true;
10928    }
10929
10930    private boolean deleteInstalledPackageLI(PackageSetting ps,
10931            boolean deleteCodeAndResources, int flags,
10932            int[] allUserHandles, boolean[] perUserInstalled,
10933            PackageRemovedInfo outInfo, boolean writeSettings) {
10934        if (outInfo != null) {
10935            outInfo.uid = ps.appId;
10936        }
10937
10938        // Delete package data from internal structures and also remove data if flag is set
10939        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10940
10941        // Delete application code and resources
10942        if (deleteCodeAndResources && (outInfo != null)) {
10943            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10944                    ps.resourcePathString, ps.nativeLibraryPathString,
10945                    getAppInstructionSetFromSettings(ps));
10946        }
10947        return true;
10948    }
10949
10950    /*
10951     * This method handles package deletion in general
10952     */
10953    private boolean deletePackageLI(String packageName, UserHandle user,
10954            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10955            int flags, PackageRemovedInfo outInfo,
10956            boolean writeSettings) {
10957        if (packageName == null) {
10958            Slog.w(TAG, "Attempt to delete null packageName.");
10959            return false;
10960        }
10961        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10962        PackageSetting ps;
10963        boolean dataOnly = false;
10964        int removeUser = -1;
10965        int appId = -1;
10966        synchronized (mPackages) {
10967            ps = mSettings.mPackages.get(packageName);
10968            if (ps == null) {
10969                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10970                return false;
10971            }
10972            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10973                    && user.getIdentifier() != UserHandle.USER_ALL) {
10974                // The caller is asking that the package only be deleted for a single
10975                // user.  To do this, we just mark its uninstalled state and delete
10976                // its data.  If this is a system app, we only allow this to happen if
10977                // they have set the special DELETE_SYSTEM_APP which requests different
10978                // semantics than normal for uninstalling system apps.
10979                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10980                ps.setUserState(user.getIdentifier(),
10981                        COMPONENT_ENABLED_STATE_DEFAULT,
10982                        false, //installed
10983                        true,  //stopped
10984                        true,  //notLaunched
10985                        false, //blocked
10986                        null, null, null);
10987                if (!isSystemApp(ps)) {
10988                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10989                        // Other user still have this package installed, so all
10990                        // we need to do is clear this user's data and save that
10991                        // it is uninstalled.
10992                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10993                        removeUser = user.getIdentifier();
10994                        appId = ps.appId;
10995                        mSettings.writePackageRestrictionsLPr(removeUser);
10996                    } else {
10997                        // We need to set it back to 'installed' so the uninstall
10998                        // broadcasts will be sent correctly.
10999                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11000                        ps.setInstalled(true, user.getIdentifier());
11001                    }
11002                } else {
11003                    // This is a system app, so we assume that the
11004                    // other users still have this package installed, so all
11005                    // we need to do is clear this user's data and save that
11006                    // it is uninstalled.
11007                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11008                    removeUser = user.getIdentifier();
11009                    appId = ps.appId;
11010                    mSettings.writePackageRestrictionsLPr(removeUser);
11011                }
11012            }
11013        }
11014
11015        if (removeUser >= 0) {
11016            // From above, we determined that we are deleting this only
11017            // for a single user.  Continue the work here.
11018            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11019            if (outInfo != null) {
11020                outInfo.removedPackage = packageName;
11021                outInfo.removedAppId = appId;
11022                outInfo.removedUsers = new int[] {removeUser};
11023            }
11024            mInstaller.clearUserData(packageName, removeUser);
11025            removeKeystoreDataIfNeeded(removeUser, appId);
11026            schedulePackageCleaning(packageName, removeUser, false);
11027            return true;
11028        }
11029
11030        if (dataOnly) {
11031            // Delete application data first
11032            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11033            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11034            return true;
11035        }
11036
11037        boolean ret = false;
11038        mSettings.mKeySetManager.removeAppKeySetData(packageName);
11039        if (isSystemApp(ps)) {
11040            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11041            // When an updated system application is deleted we delete the existing resources as well and
11042            // fall back to existing code in system partition
11043            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11044                    flags, outInfo, writeSettings);
11045        } else {
11046            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11047            // Kill application pre-emptively especially for apps on sd.
11048            killApplication(packageName, ps.appId, "uninstall pkg");
11049            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11050                    allUserHandles, perUserInstalled,
11051                    outInfo, writeSettings);
11052        }
11053
11054        return ret;
11055    }
11056
11057    private final class ClearStorageConnection implements ServiceConnection {
11058        IMediaContainerService mContainerService;
11059
11060        @Override
11061        public void onServiceConnected(ComponentName name, IBinder service) {
11062            synchronized (this) {
11063                mContainerService = IMediaContainerService.Stub.asInterface(service);
11064                notifyAll();
11065            }
11066        }
11067
11068        @Override
11069        public void onServiceDisconnected(ComponentName name) {
11070        }
11071    }
11072
11073    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11074        final boolean mounted;
11075        if (Environment.isExternalStorageEmulated()) {
11076            mounted = true;
11077        } else {
11078            final String status = Environment.getExternalStorageState();
11079
11080            mounted = status.equals(Environment.MEDIA_MOUNTED)
11081                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11082        }
11083
11084        if (!mounted) {
11085            return;
11086        }
11087
11088        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11089        int[] users;
11090        if (userId == UserHandle.USER_ALL) {
11091            users = sUserManager.getUserIds();
11092        } else {
11093            users = new int[] { userId };
11094        }
11095        final ClearStorageConnection conn = new ClearStorageConnection();
11096        if (mContext.bindServiceAsUser(
11097                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11098            try {
11099                for (int curUser : users) {
11100                    long timeout = SystemClock.uptimeMillis() + 5000;
11101                    synchronized (conn) {
11102                        long now = SystemClock.uptimeMillis();
11103                        while (conn.mContainerService == null && now < timeout) {
11104                            try {
11105                                conn.wait(timeout - now);
11106                            } catch (InterruptedException e) {
11107                            }
11108                        }
11109                    }
11110                    if (conn.mContainerService == null) {
11111                        return;
11112                    }
11113
11114                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11115                    clearDirectory(conn.mContainerService,
11116                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11117                    if (allData) {
11118                        clearDirectory(conn.mContainerService,
11119                                userEnv.buildExternalStorageAppDataDirs(packageName));
11120                        clearDirectory(conn.mContainerService,
11121                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11122                    }
11123                }
11124            } finally {
11125                mContext.unbindService(conn);
11126            }
11127        }
11128    }
11129
11130    @Override
11131    public void clearApplicationUserData(final String packageName,
11132            final IPackageDataObserver observer, final int userId) {
11133        mContext.enforceCallingOrSelfPermission(
11134                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11135        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11136        // Queue up an async operation since the package deletion may take a little while.
11137        mHandler.post(new Runnable() {
11138            public void run() {
11139                mHandler.removeCallbacks(this);
11140                final boolean succeeded;
11141                synchronized (mInstallLock) {
11142                    succeeded = clearApplicationUserDataLI(packageName, userId);
11143                }
11144                clearExternalStorageDataSync(packageName, userId, true);
11145                if (succeeded) {
11146                    // invoke DeviceStorageMonitor's update method to clear any notifications
11147                    DeviceStorageMonitorInternal
11148                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11149                    if (dsm != null) {
11150                        dsm.checkMemory();
11151                    }
11152                }
11153                if(observer != null) {
11154                    try {
11155                        observer.onRemoveCompleted(packageName, succeeded);
11156                    } catch (RemoteException e) {
11157                        Log.i(TAG, "Observer no longer exists.");
11158                    }
11159                } //end if observer
11160            } //end run
11161        });
11162    }
11163
11164    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11165        if (packageName == null) {
11166            Slog.w(TAG, "Attempt to delete null packageName.");
11167            return false;
11168        }
11169        PackageParser.Package p;
11170        boolean dataOnly = false;
11171        final int appId;
11172        synchronized (mPackages) {
11173            p = mPackages.get(packageName);
11174            if (p == null) {
11175                dataOnly = true;
11176                PackageSetting ps = mSettings.mPackages.get(packageName);
11177                if ((ps == null) || (ps.pkg == null)) {
11178                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11179                    return false;
11180                }
11181                p = ps.pkg;
11182            }
11183            if (!dataOnly) {
11184                // need to check this only for fully installed applications
11185                if (p == null) {
11186                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11187                    return false;
11188                }
11189                final ApplicationInfo applicationInfo = p.applicationInfo;
11190                if (applicationInfo == null) {
11191                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11192                    return false;
11193                }
11194            }
11195            if (p != null && p.applicationInfo != null) {
11196                appId = p.applicationInfo.uid;
11197            } else {
11198                appId = -1;
11199            }
11200        }
11201        int retCode = mInstaller.clearUserData(packageName, userId);
11202        if (retCode < 0) {
11203            Slog.w(TAG, "Couldn't remove cache files for package: "
11204                    + packageName);
11205            return false;
11206        }
11207        removeKeystoreDataIfNeeded(userId, appId);
11208        return true;
11209    }
11210
11211    /**
11212     * Remove entries from the keystore daemon. Will only remove it if the
11213     * {@code appId} is valid.
11214     */
11215    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11216        if (appId < 0) {
11217            return;
11218        }
11219
11220        final KeyStore keyStore = KeyStore.getInstance();
11221        if (keyStore != null) {
11222            if (userId == UserHandle.USER_ALL) {
11223                for (final int individual : sUserManager.getUserIds()) {
11224                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11225                }
11226            } else {
11227                keyStore.clearUid(UserHandle.getUid(userId, appId));
11228            }
11229        } else {
11230            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11231        }
11232    }
11233
11234    @Override
11235    public void deleteApplicationCacheFiles(final String packageName,
11236            final IPackageDataObserver observer) {
11237        mContext.enforceCallingOrSelfPermission(
11238                android.Manifest.permission.DELETE_CACHE_FILES, null);
11239        // Queue up an async operation since the package deletion may take a little while.
11240        final int userId = UserHandle.getCallingUserId();
11241        mHandler.post(new Runnable() {
11242            public void run() {
11243                mHandler.removeCallbacks(this);
11244                final boolean succeded;
11245                synchronized (mInstallLock) {
11246                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11247                }
11248                clearExternalStorageDataSync(packageName, userId, false);
11249                if(observer != null) {
11250                    try {
11251                        observer.onRemoveCompleted(packageName, succeded);
11252                    } catch (RemoteException e) {
11253                        Log.i(TAG, "Observer no longer exists.");
11254                    }
11255                } //end if observer
11256            } //end run
11257        });
11258    }
11259
11260    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11261        if (packageName == null) {
11262            Slog.w(TAG, "Attempt to delete null packageName.");
11263            return false;
11264        }
11265        PackageParser.Package p;
11266        synchronized (mPackages) {
11267            p = mPackages.get(packageName);
11268        }
11269        if (p == null) {
11270            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11271            return false;
11272        }
11273        final ApplicationInfo applicationInfo = p.applicationInfo;
11274        if (applicationInfo == null) {
11275            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11276            return false;
11277        }
11278        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11279        if (retCode < 0) {
11280            Slog.w(TAG, "Couldn't remove cache files for package: "
11281                       + packageName + " u" + userId);
11282            return false;
11283        }
11284        return true;
11285    }
11286
11287    @Override
11288    public void getPackageSizeInfo(final String packageName, int userHandle,
11289            final IPackageStatsObserver observer) {
11290        mContext.enforceCallingOrSelfPermission(
11291                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11292        if (packageName == null) {
11293            throw new IllegalArgumentException("Attempt to get size of null packageName");
11294        }
11295
11296        PackageStats stats = new PackageStats(packageName, userHandle);
11297
11298        /*
11299         * Queue up an async operation since the package measurement may take a
11300         * little while.
11301         */
11302        Message msg = mHandler.obtainMessage(INIT_COPY);
11303        msg.obj = new MeasureParams(stats, observer);
11304        mHandler.sendMessage(msg);
11305    }
11306
11307    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11308            PackageStats pStats) {
11309        if (packageName == null) {
11310            Slog.w(TAG, "Attempt to get size of null packageName.");
11311            return false;
11312        }
11313        PackageParser.Package p;
11314        boolean dataOnly = false;
11315        String libDirPath = null;
11316        String asecPath = null;
11317        PackageSetting ps = null;
11318        synchronized (mPackages) {
11319            p = mPackages.get(packageName);
11320            ps = mSettings.mPackages.get(packageName);
11321            if(p == null) {
11322                dataOnly = true;
11323                if((ps == null) || (ps.pkg == null)) {
11324                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11325                    return false;
11326                }
11327                p = ps.pkg;
11328            }
11329            if (ps != null) {
11330                libDirPath = ps.nativeLibraryPathString;
11331            }
11332            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11333                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11334                if (secureContainerId != null) {
11335                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11336                }
11337            }
11338        }
11339        String publicSrcDir = null;
11340        if(!dataOnly) {
11341            final ApplicationInfo applicationInfo = p.applicationInfo;
11342            if (applicationInfo == null) {
11343                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11344                return false;
11345            }
11346            if (isForwardLocked(p)) {
11347                publicSrcDir = applicationInfo.publicSourceDir;
11348            }
11349        }
11350        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11351                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11352                pStats);
11353        if (res < 0) {
11354            return false;
11355        }
11356
11357        // Fix-up for forward-locked applications in ASEC containers.
11358        if (!isExternal(p)) {
11359            pStats.codeSize += pStats.externalCodeSize;
11360            pStats.externalCodeSize = 0L;
11361        }
11362
11363        return true;
11364    }
11365
11366
11367    @Override
11368    public void addPackageToPreferred(String packageName) {
11369        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11370    }
11371
11372    @Override
11373    public void removePackageFromPreferred(String packageName) {
11374        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11375    }
11376
11377    @Override
11378    public List<PackageInfo> getPreferredPackages(int flags) {
11379        return new ArrayList<PackageInfo>();
11380    }
11381
11382    private int getUidTargetSdkVersionLockedLPr(int uid) {
11383        Object obj = mSettings.getUserIdLPr(uid);
11384        if (obj instanceof SharedUserSetting) {
11385            final SharedUserSetting sus = (SharedUserSetting) obj;
11386            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11387            final Iterator<PackageSetting> it = sus.packages.iterator();
11388            while (it.hasNext()) {
11389                final PackageSetting ps = it.next();
11390                if (ps.pkg != null) {
11391                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11392                    if (v < vers) vers = v;
11393                }
11394            }
11395            return vers;
11396        } else if (obj instanceof PackageSetting) {
11397            final PackageSetting ps = (PackageSetting) obj;
11398            if (ps.pkg != null) {
11399                return ps.pkg.applicationInfo.targetSdkVersion;
11400            }
11401        }
11402        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11403    }
11404
11405    @Override
11406    public void addPreferredActivity(IntentFilter filter, int match,
11407            ComponentName[] set, ComponentName activity, int userId) {
11408        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11409    }
11410
11411    private void addPreferredActivityInternal(IntentFilter filter, int match,
11412            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11413        // writer
11414        int callingUid = Binder.getCallingUid();
11415        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11416        if (filter.countActions() == 0) {
11417            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11418            return;
11419        }
11420        synchronized (mPackages) {
11421            if (mContext.checkCallingOrSelfPermission(
11422                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11423                    != PackageManager.PERMISSION_GRANTED) {
11424                if (getUidTargetSdkVersionLockedLPr(callingUid)
11425                        < Build.VERSION_CODES.FROYO) {
11426                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11427                            + callingUid);
11428                    return;
11429                }
11430                mContext.enforceCallingOrSelfPermission(
11431                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11432            }
11433
11434            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11435            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11436            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11437                    new PreferredActivity(filter, match, set, activity, always));
11438            mSettings.writePackageRestrictionsLPr(userId);
11439        }
11440    }
11441
11442    @Override
11443    public void replacePreferredActivity(IntentFilter filter, int match,
11444            ComponentName[] set, ComponentName activity) {
11445        if (filter.countActions() != 1) {
11446            throw new IllegalArgumentException(
11447                    "replacePreferredActivity expects filter to have only 1 action.");
11448        }
11449        if (filter.countDataAuthorities() != 0
11450                || filter.countDataPaths() != 0
11451                || filter.countDataSchemes() > 1
11452                || filter.countDataTypes() != 0) {
11453            throw new IllegalArgumentException(
11454                    "replacePreferredActivity expects filter to have no data authorities, " +
11455                    "paths, or types; and at most one scheme.");
11456        }
11457        synchronized (mPackages) {
11458            if (mContext.checkCallingOrSelfPermission(
11459                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11460                    != PackageManager.PERMISSION_GRANTED) {
11461                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11462                        < Build.VERSION_CODES.FROYO) {
11463                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11464                            + Binder.getCallingUid());
11465                    return;
11466                }
11467                mContext.enforceCallingOrSelfPermission(
11468                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11469            }
11470
11471            final int callingUserId = UserHandle.getCallingUserId();
11472            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11473            if (pir != null) {
11474                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11475                if (filter.countDataSchemes() == 1) {
11476                    Uri.Builder builder = new Uri.Builder();
11477                    builder.scheme(filter.getDataScheme(0));
11478                    intent.setData(builder.build());
11479                }
11480                List<PreferredActivity> matches = pir.queryIntent(
11481                        intent, null, true, callingUserId);
11482                if (DEBUG_PREFERRED) {
11483                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11484                }
11485                for (int i = 0; i < matches.size(); i++) {
11486                    PreferredActivity pa = matches.get(i);
11487                    if (DEBUG_PREFERRED) {
11488                        Slog.i(TAG, "Removing preferred activity "
11489                                + pa.mPref.mComponent + ":");
11490                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11491                    }
11492                    pir.removeFilter(pa);
11493                }
11494            }
11495            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11496        }
11497    }
11498
11499    @Override
11500    public void clearPackagePreferredActivities(String packageName) {
11501        final int uid = Binder.getCallingUid();
11502        // writer
11503        synchronized (mPackages) {
11504            PackageParser.Package pkg = mPackages.get(packageName);
11505            if (pkg == null || pkg.applicationInfo.uid != uid) {
11506                if (mContext.checkCallingOrSelfPermission(
11507                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11508                        != PackageManager.PERMISSION_GRANTED) {
11509                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11510                            < Build.VERSION_CODES.FROYO) {
11511                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11512                                + Binder.getCallingUid());
11513                        return;
11514                    }
11515                    mContext.enforceCallingOrSelfPermission(
11516                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11517                }
11518            }
11519
11520            int user = UserHandle.getCallingUserId();
11521            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11522                mSettings.writePackageRestrictionsLPr(user);
11523                scheduleWriteSettingsLocked();
11524            }
11525        }
11526    }
11527
11528    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11529    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11530        ArrayList<PreferredActivity> removed = null;
11531        boolean changed = false;
11532        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11533            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11534            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11535            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11536                continue;
11537            }
11538            Iterator<PreferredActivity> it = pir.filterIterator();
11539            while (it.hasNext()) {
11540                PreferredActivity pa = it.next();
11541                // Mark entry for removal only if it matches the package name
11542                // and the entry is of type "always".
11543                if (packageName == null ||
11544                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11545                                && pa.mPref.mAlways)) {
11546                    if (removed == null) {
11547                        removed = new ArrayList<PreferredActivity>();
11548                    }
11549                    removed.add(pa);
11550                }
11551            }
11552            if (removed != null) {
11553                for (int j=0; j<removed.size(); j++) {
11554                    PreferredActivity pa = removed.get(j);
11555                    pir.removeFilter(pa);
11556                }
11557                changed = true;
11558            }
11559        }
11560        return changed;
11561    }
11562
11563    @Override
11564    public void resetPreferredActivities(int userId) {
11565        mContext.enforceCallingOrSelfPermission(
11566                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11567        // writer
11568        synchronized (mPackages) {
11569            int user = UserHandle.getCallingUserId();
11570            clearPackagePreferredActivitiesLPw(null, user);
11571            mSettings.readDefaultPreferredAppsLPw(this, user);
11572            mSettings.writePackageRestrictionsLPr(user);
11573            scheduleWriteSettingsLocked();
11574        }
11575    }
11576
11577    @Override
11578    public int getPreferredActivities(List<IntentFilter> outFilters,
11579            List<ComponentName> outActivities, String packageName) {
11580
11581        int num = 0;
11582        final int userId = UserHandle.getCallingUserId();
11583        // reader
11584        synchronized (mPackages) {
11585            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11586            if (pir != null) {
11587                final Iterator<PreferredActivity> it = pir.filterIterator();
11588                while (it.hasNext()) {
11589                    final PreferredActivity pa = it.next();
11590                    if (packageName == null
11591                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11592                                    && pa.mPref.mAlways)) {
11593                        if (outFilters != null) {
11594                            outFilters.add(new IntentFilter(pa));
11595                        }
11596                        if (outActivities != null) {
11597                            outActivities.add(pa.mPref.mComponent);
11598                        }
11599                    }
11600                }
11601            }
11602        }
11603
11604        return num;
11605    }
11606
11607    @Override
11608    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11609            int userId) {
11610        int callingUid = Binder.getCallingUid();
11611        if (callingUid != Process.SYSTEM_UID) {
11612            throw new SecurityException(
11613                    "addPersistentPreferredActivity can only be run by the system");
11614        }
11615        if (filter.countActions() == 0) {
11616            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11617            return;
11618        }
11619        synchronized (mPackages) {
11620            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11621                    " :");
11622            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11623            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11624                    new PersistentPreferredActivity(filter, activity));
11625            mSettings.writePackageRestrictionsLPr(userId);
11626        }
11627    }
11628
11629    @Override
11630    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11631        int callingUid = Binder.getCallingUid();
11632        if (callingUid != Process.SYSTEM_UID) {
11633            throw new SecurityException(
11634                    "clearPackagePersistentPreferredActivities can only be run by the system");
11635        }
11636        ArrayList<PersistentPreferredActivity> removed = null;
11637        boolean changed = false;
11638        synchronized (mPackages) {
11639            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11640                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11641                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11642                        .valueAt(i);
11643                if (userId != thisUserId) {
11644                    continue;
11645                }
11646                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11647                while (it.hasNext()) {
11648                    PersistentPreferredActivity ppa = it.next();
11649                    // Mark entry for removal only if it matches the package name.
11650                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11651                        if (removed == null) {
11652                            removed = new ArrayList<PersistentPreferredActivity>();
11653                        }
11654                        removed.add(ppa);
11655                    }
11656                }
11657                if (removed != null) {
11658                    for (int j=0; j<removed.size(); j++) {
11659                        PersistentPreferredActivity ppa = removed.get(j);
11660                        ppir.removeFilter(ppa);
11661                    }
11662                    changed = true;
11663                }
11664            }
11665
11666            if (changed) {
11667                mSettings.writePackageRestrictionsLPr(userId);
11668            }
11669        }
11670    }
11671
11672    @Override
11673    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11674            int targetUserId, int flags) {
11675        mContext.enforceCallingOrSelfPermission(
11676                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11677        if (intentFilter.countActions() == 0) {
11678            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11679            return;
11680        }
11681        synchronized (mPackages) {
11682            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11683                    targetUserId, flags);
11684            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11685            mSettings.writePackageRestrictionsLPr(sourceUserId);
11686        }
11687    }
11688
11689    public void addCrossProfileIntentsForPackage(String packageName,
11690            int sourceUserId, int targetUserId) {
11691        mContext.enforceCallingOrSelfPermission(
11692                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11693        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11694        mSettings.writePackageRestrictionsLPr(sourceUserId);
11695    }
11696
11697    public void removeCrossProfileIntentsForPackage(String packageName,
11698            int sourceUserId, int targetUserId) {
11699        mContext.enforceCallingOrSelfPermission(
11700                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11701        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11702        mSettings.writePackageRestrictionsLPr(sourceUserId);
11703    }
11704
11705    @Override
11706    public void clearCrossProfileIntentFilters(int sourceUserId) {
11707        mContext.enforceCallingOrSelfPermission(
11708                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11709        synchronized (mPackages) {
11710            CrossProfileIntentResolver resolver =
11711                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11712            HashSet<CrossProfileIntentFilter> set =
11713                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11714            for (CrossProfileIntentFilter filter : set) {
11715                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11716                    resolver.removeFilter(filter);
11717                }
11718            }
11719            mSettings.writePackageRestrictionsLPr(sourceUserId);
11720        }
11721    }
11722
11723    @Override
11724    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11725        Intent intent = new Intent(Intent.ACTION_MAIN);
11726        intent.addCategory(Intent.CATEGORY_HOME);
11727
11728        final int callingUserId = UserHandle.getCallingUserId();
11729        List<ResolveInfo> list = queryIntentActivities(intent, null,
11730                PackageManager.GET_META_DATA, callingUserId);
11731        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11732                true, false, false, callingUserId);
11733
11734        allHomeCandidates.clear();
11735        if (list != null) {
11736            for (ResolveInfo ri : list) {
11737                allHomeCandidates.add(ri);
11738            }
11739        }
11740        return (preferred == null || preferred.activityInfo == null)
11741                ? null
11742                : new ComponentName(preferred.activityInfo.packageName,
11743                        preferred.activityInfo.name);
11744    }
11745
11746    @Override
11747    public void setApplicationEnabledSetting(String appPackageName,
11748            int newState, int flags, int userId, String callingPackage) {
11749        if (!sUserManager.exists(userId)) return;
11750        if (callingPackage == null) {
11751            callingPackage = Integer.toString(Binder.getCallingUid());
11752        }
11753        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11754    }
11755
11756    @Override
11757    public void setComponentEnabledSetting(ComponentName componentName,
11758            int newState, int flags, int userId) {
11759        if (!sUserManager.exists(userId)) return;
11760        setEnabledSetting(componentName.getPackageName(),
11761                componentName.getClassName(), newState, flags, userId, null);
11762    }
11763
11764    private void setEnabledSetting(final String packageName, String className, int newState,
11765            final int flags, int userId, String callingPackage) {
11766        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11767              || newState == COMPONENT_ENABLED_STATE_ENABLED
11768              || newState == COMPONENT_ENABLED_STATE_DISABLED
11769              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11770              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11771            throw new IllegalArgumentException("Invalid new component state: "
11772                    + newState);
11773        }
11774        PackageSetting pkgSetting;
11775        final int uid = Binder.getCallingUid();
11776        final int permission = mContext.checkCallingOrSelfPermission(
11777                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11778        enforceCrossUserPermission(uid, userId, false, "set enabled");
11779        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11780        boolean sendNow = false;
11781        boolean isApp = (className == null);
11782        String componentName = isApp ? packageName : className;
11783        int packageUid = -1;
11784        ArrayList<String> components;
11785
11786        // writer
11787        synchronized (mPackages) {
11788            pkgSetting = mSettings.mPackages.get(packageName);
11789            if (pkgSetting == null) {
11790                if (className == null) {
11791                    throw new IllegalArgumentException(
11792                            "Unknown package: " + packageName);
11793                }
11794                throw new IllegalArgumentException(
11795                        "Unknown component: " + packageName
11796                        + "/" + className);
11797            }
11798            // Allow root and verify that userId is not being specified by a different user
11799            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11800                throw new SecurityException(
11801                        "Permission Denial: attempt to change component state from pid="
11802                        + Binder.getCallingPid()
11803                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11804            }
11805            if (className == null) {
11806                // We're dealing with an application/package level state change
11807                if (pkgSetting.getEnabled(userId) == newState) {
11808                    // Nothing to do
11809                    return;
11810                }
11811                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11812                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11813                    // Don't care about who enables an app.
11814                    callingPackage = null;
11815                }
11816                pkgSetting.setEnabled(newState, userId, callingPackage);
11817                // pkgSetting.pkg.mSetEnabled = newState;
11818            } else {
11819                // We're dealing with a component level state change
11820                // First, verify that this is a valid class name.
11821                PackageParser.Package pkg = pkgSetting.pkg;
11822                if (pkg == null || !pkg.hasComponentClassName(className)) {
11823                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11824                        throw new IllegalArgumentException("Component class " + className
11825                                + " does not exist in " + packageName);
11826                    } else {
11827                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11828                                + className + " does not exist in " + packageName);
11829                    }
11830                }
11831                switch (newState) {
11832                case COMPONENT_ENABLED_STATE_ENABLED:
11833                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11834                        return;
11835                    }
11836                    break;
11837                case COMPONENT_ENABLED_STATE_DISABLED:
11838                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11839                        return;
11840                    }
11841                    break;
11842                case COMPONENT_ENABLED_STATE_DEFAULT:
11843                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11844                        return;
11845                    }
11846                    break;
11847                default:
11848                    Slog.e(TAG, "Invalid new component state: " + newState);
11849                    return;
11850                }
11851            }
11852            mSettings.writePackageRestrictionsLPr(userId);
11853            components = mPendingBroadcasts.get(userId, packageName);
11854            final boolean newPackage = components == null;
11855            if (newPackage) {
11856                components = new ArrayList<String>();
11857            }
11858            if (!components.contains(componentName)) {
11859                components.add(componentName);
11860            }
11861            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11862                sendNow = true;
11863                // Purge entry from pending broadcast list if another one exists already
11864                // since we are sending one right away.
11865                mPendingBroadcasts.remove(userId, packageName);
11866            } else {
11867                if (newPackage) {
11868                    mPendingBroadcasts.put(userId, packageName, components);
11869                }
11870                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11871                    // Schedule a message
11872                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11873                }
11874            }
11875        }
11876
11877        long callingId = Binder.clearCallingIdentity();
11878        try {
11879            if (sendNow) {
11880                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11881                sendPackageChangedBroadcast(packageName,
11882                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11883            }
11884        } finally {
11885            Binder.restoreCallingIdentity(callingId);
11886        }
11887    }
11888
11889    private void sendPackageChangedBroadcast(String packageName,
11890            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11891        if (DEBUG_INSTALL)
11892            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11893                    + componentNames);
11894        Bundle extras = new Bundle(4);
11895        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11896        String nameList[] = new String[componentNames.size()];
11897        componentNames.toArray(nameList);
11898        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11899        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11900        extras.putInt(Intent.EXTRA_UID, packageUid);
11901        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11902                new int[] {UserHandle.getUserId(packageUid)});
11903    }
11904
11905    @Override
11906    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11907        if (!sUserManager.exists(userId)) return;
11908        final int uid = Binder.getCallingUid();
11909        final int permission = mContext.checkCallingOrSelfPermission(
11910                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11911        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11912        enforceCrossUserPermission(uid, userId, true, "stop package");
11913        // writer
11914        synchronized (mPackages) {
11915            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11916                    uid, userId)) {
11917                scheduleWritePackageRestrictionsLocked(userId);
11918            }
11919        }
11920    }
11921
11922    @Override
11923    public String getInstallerPackageName(String packageName) {
11924        // reader
11925        synchronized (mPackages) {
11926            return mSettings.getInstallerPackageNameLPr(packageName);
11927        }
11928    }
11929
11930    @Override
11931    public int getApplicationEnabledSetting(String packageName, int userId) {
11932        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11933        int uid = Binder.getCallingUid();
11934        enforceCrossUserPermission(uid, userId, false, "get enabled");
11935        // reader
11936        synchronized (mPackages) {
11937            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11938        }
11939    }
11940
11941    @Override
11942    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11943        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11944        int uid = Binder.getCallingUid();
11945        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11946        // reader
11947        synchronized (mPackages) {
11948            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11949        }
11950    }
11951
11952    @Override
11953    public void enterSafeMode() {
11954        enforceSystemOrRoot("Only the system can request entering safe mode");
11955
11956        if (!mSystemReady) {
11957            mSafeMode = true;
11958        }
11959    }
11960
11961    @Override
11962    public void systemReady() {
11963        mSystemReady = true;
11964
11965        // Read the compatibilty setting when the system is ready.
11966        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11967                mContext.getContentResolver(),
11968                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11969        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11970        if (DEBUG_SETTINGS) {
11971            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11972        }
11973
11974        synchronized (mPackages) {
11975            // Verify that all of the preferred activity components actually
11976            // exist.  It is possible for applications to be updated and at
11977            // that point remove a previously declared activity component that
11978            // had been set as a preferred activity.  We try to clean this up
11979            // the next time we encounter that preferred activity, but it is
11980            // possible for the user flow to never be able to return to that
11981            // situation so here we do a sanity check to make sure we haven't
11982            // left any junk around.
11983            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11984            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11985                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11986                removed.clear();
11987                for (PreferredActivity pa : pir.filterSet()) {
11988                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11989                        removed.add(pa);
11990                    }
11991                }
11992                if (removed.size() > 0) {
11993                    for (int r=0; r<removed.size(); r++) {
11994                        PreferredActivity pa = removed.get(r);
11995                        Slog.w(TAG, "Removing dangling preferred activity: "
11996                                + pa.mPref.mComponent);
11997                        pir.removeFilter(pa);
11998                    }
11999                    mSettings.writePackageRestrictionsLPr(
12000                            mSettings.mPreferredActivities.keyAt(i));
12001                }
12002            }
12003        }
12004        sUserManager.systemReady();
12005    }
12006
12007    @Override
12008    public boolean isSafeMode() {
12009        return mSafeMode;
12010    }
12011
12012    @Override
12013    public boolean hasSystemUidErrors() {
12014        return mHasSystemUidErrors;
12015    }
12016
12017    static String arrayToString(int[] array) {
12018        StringBuffer buf = new StringBuffer(128);
12019        buf.append('[');
12020        if (array != null) {
12021            for (int i=0; i<array.length; i++) {
12022                if (i > 0) buf.append(", ");
12023                buf.append(array[i]);
12024            }
12025        }
12026        buf.append(']');
12027        return buf.toString();
12028    }
12029
12030    static class DumpState {
12031        public static final int DUMP_LIBS = 1 << 0;
12032
12033        public static final int DUMP_FEATURES = 1 << 1;
12034
12035        public static final int DUMP_RESOLVERS = 1 << 2;
12036
12037        public static final int DUMP_PERMISSIONS = 1 << 3;
12038
12039        public static final int DUMP_PACKAGES = 1 << 4;
12040
12041        public static final int DUMP_SHARED_USERS = 1 << 5;
12042
12043        public static final int DUMP_MESSAGES = 1 << 6;
12044
12045        public static final int DUMP_PROVIDERS = 1 << 7;
12046
12047        public static final int DUMP_VERIFIERS = 1 << 8;
12048
12049        public static final int DUMP_PREFERRED = 1 << 9;
12050
12051        public static final int DUMP_PREFERRED_XML = 1 << 10;
12052
12053        public static final int DUMP_KEYSETS = 1 << 11;
12054
12055        public static final int DUMP_VERSION = 1 << 12;
12056
12057        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12058
12059        private int mTypes;
12060
12061        private int mOptions;
12062
12063        private boolean mTitlePrinted;
12064
12065        private SharedUserSetting mSharedUser;
12066
12067        public boolean isDumping(int type) {
12068            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12069                return true;
12070            }
12071
12072            return (mTypes & type) != 0;
12073        }
12074
12075        public void setDump(int type) {
12076            mTypes |= type;
12077        }
12078
12079        public boolean isOptionEnabled(int option) {
12080            return (mOptions & option) != 0;
12081        }
12082
12083        public void setOptionEnabled(int option) {
12084            mOptions |= option;
12085        }
12086
12087        public boolean onTitlePrinted() {
12088            final boolean printed = mTitlePrinted;
12089            mTitlePrinted = true;
12090            return printed;
12091        }
12092
12093        public boolean getTitlePrinted() {
12094            return mTitlePrinted;
12095        }
12096
12097        public void setTitlePrinted(boolean enabled) {
12098            mTitlePrinted = enabled;
12099        }
12100
12101        public SharedUserSetting getSharedUser() {
12102            return mSharedUser;
12103        }
12104
12105        public void setSharedUser(SharedUserSetting user) {
12106            mSharedUser = user;
12107        }
12108    }
12109
12110    @Override
12111    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12112        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12113                != PackageManager.PERMISSION_GRANTED) {
12114            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12115                    + Binder.getCallingPid()
12116                    + ", uid=" + Binder.getCallingUid()
12117                    + " without permission "
12118                    + android.Manifest.permission.DUMP);
12119            return;
12120        }
12121
12122        DumpState dumpState = new DumpState();
12123        boolean fullPreferred = false;
12124        boolean checkin = false;
12125
12126        String packageName = null;
12127
12128        int opti = 0;
12129        while (opti < args.length) {
12130            String opt = args[opti];
12131            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12132                break;
12133            }
12134            opti++;
12135            if ("-a".equals(opt)) {
12136                // Right now we only know how to print all.
12137            } else if ("-h".equals(opt)) {
12138                pw.println("Package manager dump options:");
12139                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12140                pw.println("    --checkin: dump for a checkin");
12141                pw.println("    -f: print details of intent filters");
12142                pw.println("    -h: print this help");
12143                pw.println("  cmd may be one of:");
12144                pw.println("    l[ibraries]: list known shared libraries");
12145                pw.println("    f[ibraries]: list device features");
12146                pw.println("    k[eysets]: print known keysets");
12147                pw.println("    r[esolvers]: dump intent resolvers");
12148                pw.println("    perm[issions]: dump permissions");
12149                pw.println("    pref[erred]: print preferred package settings");
12150                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12151                pw.println("    prov[iders]: dump content providers");
12152                pw.println("    p[ackages]: dump installed packages");
12153                pw.println("    s[hared-users]: dump shared user IDs");
12154                pw.println("    m[essages]: print collected runtime messages");
12155                pw.println("    v[erifiers]: print package verifier info");
12156                pw.println("    version: print database version info");
12157                pw.println("    write: write current settings now");
12158                pw.println("    <package.name>: info about given package");
12159                return;
12160            } else if ("--checkin".equals(opt)) {
12161                checkin = true;
12162            } else if ("-f".equals(opt)) {
12163                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12164            } else {
12165                pw.println("Unknown argument: " + opt + "; use -h for help");
12166            }
12167        }
12168
12169        // Is the caller requesting to dump a particular piece of data?
12170        if (opti < args.length) {
12171            String cmd = args[opti];
12172            opti++;
12173            // Is this a package name?
12174            if ("android".equals(cmd) || cmd.contains(".")) {
12175                packageName = cmd;
12176                // When dumping a single package, we always dump all of its
12177                // filter information since the amount of data will be reasonable.
12178                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12179            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_LIBS);
12181            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_FEATURES);
12183            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12185            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12187            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12188                dumpState.setDump(DumpState.DUMP_PREFERRED);
12189            } else if ("preferred-xml".equals(cmd)) {
12190                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12191                if (opti < args.length && "--full".equals(args[opti])) {
12192                    fullPreferred = true;
12193                    opti++;
12194                }
12195            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12196                dumpState.setDump(DumpState.DUMP_PACKAGES);
12197            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12198                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12199            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12200                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12201            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12202                dumpState.setDump(DumpState.DUMP_MESSAGES);
12203            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12204                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12205            } else if ("version".equals(cmd)) {
12206                dumpState.setDump(DumpState.DUMP_VERSION);
12207            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12208                dumpState.setDump(DumpState.DUMP_KEYSETS);
12209            } else if ("write".equals(cmd)) {
12210                synchronized (mPackages) {
12211                    mSettings.writeLPr();
12212                    pw.println("Settings written.");
12213                    return;
12214                }
12215            }
12216        }
12217
12218        if (checkin) {
12219            pw.println("vers,1");
12220        }
12221
12222        // reader
12223        synchronized (mPackages) {
12224            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12225                if (!checkin) {
12226                    if (dumpState.onTitlePrinted())
12227                        pw.println();
12228                    pw.println("Database versions:");
12229                    pw.print("  SDK Version:");
12230                    pw.print(" internal=");
12231                    pw.print(mSettings.mInternalSdkPlatform);
12232                    pw.print(" external=");
12233                    pw.println(mSettings.mExternalSdkPlatform);
12234                    pw.print("  DB Version:");
12235                    pw.print(" internal=");
12236                    pw.print(mSettings.mInternalDatabaseVersion);
12237                    pw.print(" external=");
12238                    pw.println(mSettings.mExternalDatabaseVersion);
12239                }
12240            }
12241
12242            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12243                if (!checkin) {
12244                    if (dumpState.onTitlePrinted())
12245                        pw.println();
12246                    pw.println("Verifiers:");
12247                    pw.print("  Required: ");
12248                    pw.print(mRequiredVerifierPackage);
12249                    pw.print(" (uid=");
12250                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12251                    pw.println(")");
12252                } else if (mRequiredVerifierPackage != null) {
12253                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12254                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12255                }
12256            }
12257
12258            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12259                boolean printedHeader = false;
12260                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12261                while (it.hasNext()) {
12262                    String name = it.next();
12263                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12264                    if (!checkin) {
12265                        if (!printedHeader) {
12266                            if (dumpState.onTitlePrinted())
12267                                pw.println();
12268                            pw.println("Libraries:");
12269                            printedHeader = true;
12270                        }
12271                        pw.print("  ");
12272                    } else {
12273                        pw.print("lib,");
12274                    }
12275                    pw.print(name);
12276                    if (!checkin) {
12277                        pw.print(" -> ");
12278                    }
12279                    if (ent.path != null) {
12280                        if (!checkin) {
12281                            pw.print("(jar) ");
12282                            pw.print(ent.path);
12283                        } else {
12284                            pw.print(",jar,");
12285                            pw.print(ent.path);
12286                        }
12287                    } else {
12288                        if (!checkin) {
12289                            pw.print("(apk) ");
12290                            pw.print(ent.apk);
12291                        } else {
12292                            pw.print(",apk,");
12293                            pw.print(ent.apk);
12294                        }
12295                    }
12296                    pw.println();
12297                }
12298            }
12299
12300            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12301                if (dumpState.onTitlePrinted())
12302                    pw.println();
12303                if (!checkin) {
12304                    pw.println("Features:");
12305                }
12306                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12307                while (it.hasNext()) {
12308                    String name = it.next();
12309                    if (!checkin) {
12310                        pw.print("  ");
12311                    } else {
12312                        pw.print("feat,");
12313                    }
12314                    pw.println(name);
12315                }
12316            }
12317
12318            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12319                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12320                        : "Activity Resolver Table:", "  ", packageName,
12321                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12322                    dumpState.setTitlePrinted(true);
12323                }
12324                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12325                        : "Receiver Resolver Table:", "  ", packageName,
12326                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12327                    dumpState.setTitlePrinted(true);
12328                }
12329                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12330                        : "Service Resolver Table:", "  ", packageName,
12331                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12332                    dumpState.setTitlePrinted(true);
12333                }
12334                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12335                        : "Provider Resolver Table:", "  ", packageName,
12336                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12337                    dumpState.setTitlePrinted(true);
12338                }
12339            }
12340
12341            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12342                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12343                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12344                    int user = mSettings.mPreferredActivities.keyAt(i);
12345                    if (pir.dump(pw,
12346                            dumpState.getTitlePrinted()
12347                                ? "\nPreferred Activities User " + user + ":"
12348                                : "Preferred Activities User " + user + ":", "  ",
12349                            packageName, true)) {
12350                        dumpState.setTitlePrinted(true);
12351                    }
12352                }
12353            }
12354
12355            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12356                pw.flush();
12357                FileOutputStream fout = new FileOutputStream(fd);
12358                BufferedOutputStream str = new BufferedOutputStream(fout);
12359                XmlSerializer serializer = new FastXmlSerializer();
12360                try {
12361                    serializer.setOutput(str, "utf-8");
12362                    serializer.startDocument(null, true);
12363                    serializer.setFeature(
12364                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12365                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12366                    serializer.endDocument();
12367                    serializer.flush();
12368                } catch (IllegalArgumentException e) {
12369                    pw.println("Failed writing: " + e);
12370                } catch (IllegalStateException e) {
12371                    pw.println("Failed writing: " + e);
12372                } catch (IOException e) {
12373                    pw.println("Failed writing: " + e);
12374                }
12375            }
12376
12377            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12378                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12379            }
12380
12381            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12382                boolean printedSomething = false;
12383                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12384                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12385                        continue;
12386                    }
12387                    if (!printedSomething) {
12388                        if (dumpState.onTitlePrinted())
12389                            pw.println();
12390                        pw.println("Registered ContentProviders:");
12391                        printedSomething = true;
12392                    }
12393                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12394                    pw.print("    "); pw.println(p.toString());
12395                }
12396                printedSomething = false;
12397                for (Map.Entry<String, PackageParser.Provider> entry :
12398                        mProvidersByAuthority.entrySet()) {
12399                    PackageParser.Provider p = entry.getValue();
12400                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12401                        continue;
12402                    }
12403                    if (!printedSomething) {
12404                        if (dumpState.onTitlePrinted())
12405                            pw.println();
12406                        pw.println("ContentProvider Authorities:");
12407                        printedSomething = true;
12408                    }
12409                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12410                    pw.print("    "); pw.println(p.toString());
12411                    if (p.info != null && p.info.applicationInfo != null) {
12412                        final String appInfo = p.info.applicationInfo.toString();
12413                        pw.print("      applicationInfo="); pw.println(appInfo);
12414                    }
12415                }
12416            }
12417
12418            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12419                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12420            }
12421
12422            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12423                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12424            }
12425
12426            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12427                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12428            }
12429
12430            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12431                if (dumpState.onTitlePrinted())
12432                    pw.println();
12433                mSettings.dumpReadMessagesLPr(pw, dumpState);
12434
12435                pw.println();
12436                pw.println("Package warning messages:");
12437                final File fname = getSettingsProblemFile();
12438                FileInputStream in = null;
12439                try {
12440                    in = new FileInputStream(fname);
12441                    final int avail = in.available();
12442                    final byte[] data = new byte[avail];
12443                    in.read(data);
12444                    pw.print(new String(data));
12445                } catch (FileNotFoundException e) {
12446                } catch (IOException e) {
12447                } finally {
12448                    if (in != null) {
12449                        try {
12450                            in.close();
12451                        } catch (IOException e) {
12452                        }
12453                    }
12454                }
12455            }
12456        }
12457    }
12458
12459    // ------- apps on sdcard specific code -------
12460    static final boolean DEBUG_SD_INSTALL = false;
12461
12462    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12463
12464    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12465
12466    private boolean mMediaMounted = false;
12467
12468    private String getEncryptKey() {
12469        try {
12470            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12471                    SD_ENCRYPTION_KEYSTORE_NAME);
12472            if (sdEncKey == null) {
12473                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12474                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12475                if (sdEncKey == null) {
12476                    Slog.e(TAG, "Failed to create encryption keys");
12477                    return null;
12478                }
12479            }
12480            return sdEncKey;
12481        } catch (NoSuchAlgorithmException nsae) {
12482            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12483            return null;
12484        } catch (IOException ioe) {
12485            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12486            return null;
12487        }
12488
12489    }
12490
12491    /* package */static String getTempContainerId() {
12492        int tmpIdx = 1;
12493        String list[] = PackageHelper.getSecureContainerList();
12494        if (list != null) {
12495            for (final String name : list) {
12496                // Ignore null and non-temporary container entries
12497                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12498                    continue;
12499                }
12500
12501                String subStr = name.substring(mTempContainerPrefix.length());
12502                try {
12503                    int cid = Integer.parseInt(subStr);
12504                    if (cid >= tmpIdx) {
12505                        tmpIdx = cid + 1;
12506                    }
12507                } catch (NumberFormatException e) {
12508                }
12509            }
12510        }
12511        return mTempContainerPrefix + tmpIdx;
12512    }
12513
12514    /*
12515     * Update media status on PackageManager.
12516     */
12517    @Override
12518    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12519        int callingUid = Binder.getCallingUid();
12520        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12521            throw new SecurityException("Media status can only be updated by the system");
12522        }
12523        // reader; this apparently protects mMediaMounted, but should probably
12524        // be a different lock in that case.
12525        synchronized (mPackages) {
12526            Log.i(TAG, "Updating external media status from "
12527                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12528                    + (mediaStatus ? "mounted" : "unmounted"));
12529            if (DEBUG_SD_INSTALL)
12530                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12531                        + ", mMediaMounted=" + mMediaMounted);
12532            if (mediaStatus == mMediaMounted) {
12533                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12534                        : 0, -1);
12535                mHandler.sendMessage(msg);
12536                return;
12537            }
12538            mMediaMounted = mediaStatus;
12539        }
12540        // Queue up an async operation since the package installation may take a
12541        // little while.
12542        mHandler.post(new Runnable() {
12543            public void run() {
12544                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12545            }
12546        });
12547    }
12548
12549    /**
12550     * Called by MountService when the initial ASECs to scan are available.
12551     * Should block until all the ASEC containers are finished being scanned.
12552     */
12553    public void scanAvailableAsecs() {
12554        updateExternalMediaStatusInner(true, false, false);
12555        if (mShouldRestoreconData) {
12556            SELinuxMMAC.setRestoreconDone();
12557            mShouldRestoreconData = false;
12558        }
12559    }
12560
12561    /*
12562     * Collect information of applications on external media, map them against
12563     * existing containers and update information based on current mount status.
12564     * Please note that we always have to report status if reportStatus has been
12565     * set to true especially when unloading packages.
12566     */
12567    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12568            boolean externalStorage) {
12569        // Collection of uids
12570        int uidArr[] = null;
12571        // Collection of stale containers
12572        HashSet<String> removeCids = new HashSet<String>();
12573        // Collection of packages on external media with valid containers.
12574        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12575        // Get list of secure containers.
12576        final String list[] = PackageHelper.getSecureContainerList();
12577        if (list == null || list.length == 0) {
12578            Log.i(TAG, "No secure containers on sdcard");
12579        } else {
12580            // Process list of secure containers and categorize them
12581            // as active or stale based on their package internal state.
12582            int uidList[] = new int[list.length];
12583            int num = 0;
12584            // reader
12585            synchronized (mPackages) {
12586                for (String cid : list) {
12587                    if (DEBUG_SD_INSTALL)
12588                        Log.i(TAG, "Processing container " + cid);
12589                    String pkgName = getAsecPackageName(cid);
12590                    if (pkgName == null) {
12591                        if (DEBUG_SD_INSTALL)
12592                            Log.i(TAG, "Container : " + cid + " stale");
12593                        removeCids.add(cid);
12594                        continue;
12595                    }
12596                    if (DEBUG_SD_INSTALL)
12597                        Log.i(TAG, "Looking for pkg : " + pkgName);
12598
12599                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12600                    if (ps == null) {
12601                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12602                        removeCids.add(cid);
12603                        continue;
12604                    }
12605
12606                    /*
12607                     * Skip packages that are not external if we're unmounting
12608                     * external storage.
12609                     */
12610                    if (externalStorage && !isMounted && !isExternal(ps)) {
12611                        continue;
12612                    }
12613
12614                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12615                            getAppInstructionSetFromSettings(ps),
12616                            isForwardLocked(ps));
12617                    // The package status is changed only if the code path
12618                    // matches between settings and the container id.
12619                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12620                        if (DEBUG_SD_INSTALL) {
12621                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12622                                    + " at code path: " + ps.codePathString);
12623                        }
12624
12625                        // We do have a valid package installed on sdcard
12626                        processCids.put(args, ps.codePathString);
12627                        final int uid = ps.appId;
12628                        if (uid != -1) {
12629                            uidList[num++] = uid;
12630                        }
12631                    } else {
12632                        Log.i(TAG, "Deleting stale container for " + cid);
12633                        removeCids.add(cid);
12634                    }
12635                }
12636            }
12637
12638            if (num > 0) {
12639                // Sort uid list
12640                Arrays.sort(uidList, 0, num);
12641                // Throw away duplicates
12642                uidArr = new int[num];
12643                uidArr[0] = uidList[0];
12644                int di = 0;
12645                for (int i = 1; i < num; i++) {
12646                    if (uidList[i - 1] != uidList[i]) {
12647                        uidArr[di++] = uidList[i];
12648                    }
12649                }
12650            }
12651        }
12652        // Process packages with valid entries.
12653        if (isMounted) {
12654            if (DEBUG_SD_INSTALL)
12655                Log.i(TAG, "Loading packages");
12656            loadMediaPackages(processCids, uidArr, removeCids);
12657            startCleaningPackages();
12658        } else {
12659            if (DEBUG_SD_INSTALL)
12660                Log.i(TAG, "Unloading packages");
12661            unloadMediaPackages(processCids, uidArr, reportStatus);
12662        }
12663    }
12664
12665   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12666           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12667        int size = pkgList.size();
12668        if (size > 0) {
12669            // Send broadcasts here
12670            Bundle extras = new Bundle();
12671            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12672                    .toArray(new String[size]));
12673            if (uidArr != null) {
12674                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12675            }
12676            if (replacing) {
12677                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12678            }
12679            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12680                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12681            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12682        }
12683    }
12684
12685   /*
12686     * Look at potentially valid container ids from processCids If package
12687     * information doesn't match the one on record or package scanning fails,
12688     * the cid is added to list of removeCids. We currently don't delete stale
12689     * containers.
12690     */
12691   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12692            HashSet<String> removeCids) {
12693        ArrayList<String> pkgList = new ArrayList<String>();
12694        Set<AsecInstallArgs> keys = processCids.keySet();
12695        boolean doGc = false;
12696        for (AsecInstallArgs args : keys) {
12697            String codePath = processCids.get(args);
12698            if (DEBUG_SD_INSTALL)
12699                Log.i(TAG, "Loading container : " + args.cid);
12700            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12701            try {
12702                // Make sure there are no container errors first.
12703                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12704                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12705                            + " when installing from sdcard");
12706                    continue;
12707                }
12708                // Check code path here.
12709                if (codePath == null || !codePath.equals(args.getCodePath())) {
12710                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12711                            + " does not match one in settings " + codePath);
12712                    continue;
12713                }
12714                // Parse package
12715                int parseFlags = mDefParseFlags;
12716                if (args.isExternal()) {
12717                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12718                }
12719                if (args.isFwdLocked()) {
12720                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12721                }
12722
12723                doGc = true;
12724                synchronized (mInstallLock) {
12725                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12726                            0, 0, null, null);
12727                    // Scan the package
12728                    if (pkg != null) {
12729                        /*
12730                         * TODO why is the lock being held? doPostInstall is
12731                         * called in other places without the lock. This needs
12732                         * to be straightened out.
12733                         */
12734                        // writer
12735                        synchronized (mPackages) {
12736                            retCode = PackageManager.INSTALL_SUCCEEDED;
12737                            pkgList.add(pkg.packageName);
12738                            // Post process args
12739                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12740                                    pkg.applicationInfo.uid);
12741                        }
12742                    } else {
12743                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12744                    }
12745                }
12746
12747            } finally {
12748                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12749                    // Don't destroy container here. Wait till gc clears things
12750                    // up.
12751                    removeCids.add(args.cid);
12752                }
12753            }
12754        }
12755        // writer
12756        synchronized (mPackages) {
12757            // If the platform SDK has changed since the last time we booted,
12758            // we need to re-grant app permission to catch any new ones that
12759            // appear. This is really a hack, and means that apps can in some
12760            // cases get permissions that the user didn't initially explicitly
12761            // allow... it would be nice to have some better way to handle
12762            // this situation.
12763            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12764            if (regrantPermissions)
12765                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12766                        + mSdkVersion + "; regranting permissions for external storage");
12767            mSettings.mExternalSdkPlatform = mSdkVersion;
12768
12769            // Make sure group IDs have been assigned, and any permission
12770            // changes in other apps are accounted for
12771            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12772                    | (regrantPermissions
12773                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12774                            : 0));
12775
12776            mSettings.updateExternalDatabaseVersion();
12777
12778            // can downgrade to reader
12779            // Persist settings
12780            mSettings.writeLPr();
12781        }
12782        // Send a broadcast to let everyone know we are done processing
12783        if (pkgList.size() > 0) {
12784            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12785        }
12786        // Force gc to avoid any stale parser references that we might have.
12787        if (doGc) {
12788            Runtime.getRuntime().gc();
12789        }
12790        // List stale containers and destroy stale temporary containers.
12791        if (removeCids != null) {
12792            for (String cid : removeCids) {
12793                if (cid.startsWith(mTempContainerPrefix)) {
12794                    Log.i(TAG, "Destroying stale temporary container " + cid);
12795                    PackageHelper.destroySdDir(cid);
12796                } else {
12797                    Log.w(TAG, "Container " + cid + " is stale");
12798               }
12799           }
12800        }
12801    }
12802
12803   /*
12804     * Utility method to unload a list of specified containers
12805     */
12806    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12807        // Just unmount all valid containers.
12808        for (AsecInstallArgs arg : cidArgs) {
12809            synchronized (mInstallLock) {
12810                arg.doPostDeleteLI(false);
12811           }
12812       }
12813   }
12814
12815    /*
12816     * Unload packages mounted on external media. This involves deleting package
12817     * data from internal structures, sending broadcasts about diabled packages,
12818     * gc'ing to free up references, unmounting all secure containers
12819     * corresponding to packages on external media, and posting a
12820     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12821     * that we always have to post this message if status has been requested no
12822     * matter what.
12823     */
12824    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12825            final boolean reportStatus) {
12826        if (DEBUG_SD_INSTALL)
12827            Log.i(TAG, "unloading media packages");
12828        ArrayList<String> pkgList = new ArrayList<String>();
12829        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12830        final Set<AsecInstallArgs> keys = processCids.keySet();
12831        for (AsecInstallArgs args : keys) {
12832            String pkgName = args.getPackageName();
12833            if (DEBUG_SD_INSTALL)
12834                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12835            // Delete package internally
12836            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12837            synchronized (mInstallLock) {
12838                boolean res = deletePackageLI(pkgName, null, false, null, null,
12839                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12840                if (res) {
12841                    pkgList.add(pkgName);
12842                } else {
12843                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12844                    failedList.add(args);
12845                }
12846            }
12847        }
12848
12849        // reader
12850        synchronized (mPackages) {
12851            // We didn't update the settings after removing each package;
12852            // write them now for all packages.
12853            mSettings.writeLPr();
12854        }
12855
12856        // We have to absolutely send UPDATED_MEDIA_STATUS only
12857        // after confirming that all the receivers processed the ordered
12858        // broadcast when packages get disabled, force a gc to clean things up.
12859        // and unload all the containers.
12860        if (pkgList.size() > 0) {
12861            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12862                    new IIntentReceiver.Stub() {
12863                public void performReceive(Intent intent, int resultCode, String data,
12864                        Bundle extras, boolean ordered, boolean sticky,
12865                        int sendingUser) throws RemoteException {
12866                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12867                            reportStatus ? 1 : 0, 1, keys);
12868                    mHandler.sendMessage(msg);
12869                }
12870            });
12871        } else {
12872            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12873                    keys);
12874            mHandler.sendMessage(msg);
12875        }
12876    }
12877
12878    /** Binder call */
12879    @Override
12880    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12881            final int flags) {
12882        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12883        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12884        int returnCode = PackageManager.MOVE_SUCCEEDED;
12885        int currFlags = 0;
12886        int newFlags = 0;
12887        // reader
12888        synchronized (mPackages) {
12889            PackageParser.Package pkg = mPackages.get(packageName);
12890            if (pkg == null) {
12891                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12892            } else {
12893                // Disable moving fwd locked apps and system packages
12894                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12895                    Slog.w(TAG, "Cannot move system application");
12896                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12897                } else if (pkg.mOperationPending) {
12898                    Slog.w(TAG, "Attempt to move package which has pending operations");
12899                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12900                } else {
12901                    // Find install location first
12902                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12903                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12904                        Slog.w(TAG, "Ambigous flags specified for move location.");
12905                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12906                    } else {
12907                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12908                                : PackageManager.INSTALL_INTERNAL;
12909                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12910                                : PackageManager.INSTALL_INTERNAL;
12911
12912                        if (newFlags == currFlags) {
12913                            Slog.w(TAG, "No move required. Trying to move to same location");
12914                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12915                        } else {
12916                            if (isForwardLocked(pkg)) {
12917                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12918                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12919                            }
12920                        }
12921                    }
12922                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12923                        pkg.mOperationPending = true;
12924                    }
12925                }
12926            }
12927
12928            /*
12929             * TODO this next block probably shouldn't be inside the lock. We
12930             * can't guarantee these won't change after this is fired off
12931             * anyway.
12932             */
12933            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12934                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12935                        null, -1, user),
12936                        returnCode);
12937            } else {
12938                Message msg = mHandler.obtainMessage(INIT_COPY);
12939                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12940                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12941                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12942                        instructionSet);
12943                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12944                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12945                msg.obj = mp;
12946                mHandler.sendMessage(msg);
12947            }
12948        }
12949    }
12950
12951    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12952        // Queue up an async operation since the package deletion may take a
12953        // little while.
12954        mHandler.post(new Runnable() {
12955            public void run() {
12956                // TODO fix this; this does nothing.
12957                mHandler.removeCallbacks(this);
12958                int returnCode = currentStatus;
12959                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12960                    int uidArr[] = null;
12961                    ArrayList<String> pkgList = null;
12962                    synchronized (mPackages) {
12963                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12964                        if (pkg == null) {
12965                            Slog.w(TAG, " Package " + mp.packageName
12966                                    + " doesn't exist. Aborting move");
12967                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12968                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12969                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12970                                    + mp.srcArgs.getCodePath() + " to "
12971                                    + pkg.applicationInfo.sourceDir
12972                                    + " Aborting move and returning error");
12973                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12974                        } else {
12975                            uidArr = new int[] {
12976                                pkg.applicationInfo.uid
12977                            };
12978                            pkgList = new ArrayList<String>();
12979                            pkgList.add(mp.packageName);
12980                        }
12981                    }
12982                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12983                        // Send resources unavailable broadcast
12984                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12985                        // Update package code and resource paths
12986                        synchronized (mInstallLock) {
12987                            synchronized (mPackages) {
12988                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12989                                // Recheck for package again.
12990                                if (pkg == null) {
12991                                    Slog.w(TAG, " Package " + mp.packageName
12992                                            + " doesn't exist. Aborting move");
12993                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12994                                } else if (!mp.srcArgs.getCodePath().equals(
12995                                        pkg.applicationInfo.sourceDir)) {
12996                                    Slog.w(TAG, "Package " + mp.packageName
12997                                            + " code path changed from " + mp.srcArgs.getCodePath()
12998                                            + " to " + pkg.applicationInfo.sourceDir
12999                                            + " Aborting move and returning error");
13000                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13001                                } else {
13002                                    final String oldCodePath = pkg.codePath;
13003                                    final String newCodePath = mp.targetArgs.getCodePath();
13004                                    final String newResPath = mp.targetArgs.getResourcePath();
13005                                    final String newNativePath = mp.targetArgs
13006                                            .getNativeLibraryPath();
13007
13008                                    final File newNativeDir = new File(newNativePath);
13009
13010                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13011                                        // NOTE: We do not report any errors from the APK scan and library
13012                                        // copy at this point.
13013                                        NativeLibraryHelper.ApkHandle handle =
13014                                                new NativeLibraryHelper.ApkHandle(newCodePath);
13015                                        final int abi = NativeLibraryHelper.findSupportedAbi(
13016                                                handle, Build.SUPPORTED_ABIS);
13017                                        if (abi >= 0) {
13018                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13019                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13020                                        }
13021                                        handle.close();
13022                                    }
13023                                    final int[] users = sUserManager.getUserIds();
13024                                    for (int user : users) {
13025                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13026                                                newNativePath, user) < 0) {
13027                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13028                                        }
13029                                    }
13030
13031                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13032                                        pkg.codePath = newCodePath;
13033                                        // Move dex files around
13034                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13035                                            // Moving of dex files failed. Set
13036                                            // error code and abort move.
13037                                            pkg.codePath = oldCodePath;
13038                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13039                                        }
13040                                    }
13041
13042                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13043                                        pkg.applicationInfo.sourceDir = newCodePath;
13044                                        pkg.applicationInfo.publicSourceDir = newResPath;
13045                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
13046                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13047                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
13048                                        ps.codePathString = ps.codePath.getPath();
13049                                        ps.resourcePath = new File(
13050                                                pkg.applicationInfo.publicSourceDir);
13051                                        ps.resourcePathString = ps.resourcePath.getPath();
13052                                        ps.nativeLibraryPathString = newNativePath;
13053                                        // Set the application info flag
13054                                        // correctly.
13055                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13056                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13057                                        } else {
13058                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13059                                        }
13060                                        ps.setFlags(pkg.applicationInfo.flags);
13061                                        mAppDirs.remove(oldCodePath);
13062                                        mAppDirs.put(newCodePath, pkg);
13063                                        // Persist settings
13064                                        mSettings.writeLPr();
13065                                    }
13066                                }
13067                            }
13068                        }
13069                        // Send resources available broadcast
13070                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13071                    }
13072                }
13073                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13074                    // Clean up failed installation
13075                    if (mp.targetArgs != null) {
13076                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13077                                -1);
13078                    }
13079                } else {
13080                    // Force a gc to clear things up.
13081                    Runtime.getRuntime().gc();
13082                    // Delete older code
13083                    synchronized (mInstallLock) {
13084                        mp.srcArgs.doPostDeleteLI(true);
13085                    }
13086                }
13087
13088                // Allow more operations on this file if we didn't fail because
13089                // an operation was already pending for this package.
13090                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13091                    synchronized (mPackages) {
13092                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13093                        if (pkg != null) {
13094                            pkg.mOperationPending = false;
13095                       }
13096                   }
13097                }
13098
13099                IPackageMoveObserver observer = mp.observer;
13100                if (observer != null) {
13101                    try {
13102                        observer.packageMoved(mp.packageName, returnCode);
13103                    } catch (RemoteException e) {
13104                        Log.i(TAG, "Observer no longer exists.");
13105                    }
13106                }
13107            }
13108        });
13109    }
13110
13111    @Override
13112    public boolean setInstallLocation(int loc) {
13113        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13114                null);
13115        if (getInstallLocation() == loc) {
13116            return true;
13117        }
13118        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13119                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13120            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13121                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13122            return true;
13123        }
13124        return false;
13125   }
13126
13127    @Override
13128    public int getInstallLocation() {
13129        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13130                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13131                PackageHelper.APP_INSTALL_AUTO);
13132    }
13133
13134    /** Called by UserManagerService */
13135    void cleanUpUserLILPw(int userHandle) {
13136        mDirtyUsers.remove(userHandle);
13137        mSettings.removeUserLPr(userHandle);
13138        mPendingBroadcasts.remove(userHandle);
13139        if (mInstaller != null) {
13140            // Technically, we shouldn't be doing this with the package lock
13141            // held.  However, this is very rare, and there is already so much
13142            // other disk I/O going on, that we'll let it slide for now.
13143            mInstaller.removeUserDataDirs(userHandle);
13144        }
13145    }
13146
13147    /** Called by UserManagerService */
13148    void createNewUserLILPw(int userHandle, File path) {
13149        if (mInstaller != null) {
13150            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13151        }
13152    }
13153
13154    @Override
13155    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13156        mContext.enforceCallingOrSelfPermission(
13157                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13158                "Only package verification agents can read the verifier device identity");
13159
13160        synchronized (mPackages) {
13161            return mSettings.getVerifierDeviceIdentityLPw();
13162        }
13163    }
13164
13165    @Override
13166    public void setPermissionEnforced(String permission, boolean enforced) {
13167        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13168        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13169            synchronized (mPackages) {
13170                if (mSettings.mReadExternalStorageEnforced == null
13171                        || mSettings.mReadExternalStorageEnforced != enforced) {
13172                    mSettings.mReadExternalStorageEnforced = enforced;
13173                    mSettings.writeLPr();
13174                }
13175            }
13176            // kill any non-foreground processes so we restart them and
13177            // grant/revoke the GID.
13178            final IActivityManager am = ActivityManagerNative.getDefault();
13179            if (am != null) {
13180                final long token = Binder.clearCallingIdentity();
13181                try {
13182                    am.killProcessesBelowForeground("setPermissionEnforcement");
13183                } catch (RemoteException e) {
13184                } finally {
13185                    Binder.restoreCallingIdentity(token);
13186                }
13187            }
13188        } else {
13189            throw new IllegalArgumentException("No selective enforcement for " + permission);
13190        }
13191    }
13192
13193    @Override
13194    @Deprecated
13195    public boolean isPermissionEnforced(String permission) {
13196        return true;
13197    }
13198
13199    @Override
13200    public boolean isStorageLow() {
13201        final long token = Binder.clearCallingIdentity();
13202        try {
13203            final DeviceStorageMonitorInternal
13204                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13205            if (dsm != null) {
13206                return dsm.isMemoryLow();
13207            } else {
13208                return false;
13209            }
13210        } finally {
13211            Binder.restoreCallingIdentity(token);
13212        }
13213    }
13214
13215    @Override
13216    public IPackageInstaller getPackageInstaller() {
13217        return mInstallerService;
13218    }
13219}
13220