PackageManagerService.java revision b87de28f50e9f02a365f35348f8da6cc2629bc1c
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.FastPrintWriter;
46import com.android.internal.util.FastXmlSerializer;
47import com.android.internal.util.XmlUtils;
48import com.android.server.EventLogTags;
49import com.android.server.IntentResolver;
50import com.android.server.LocalServices;
51import com.android.server.ServiceThread;
52import com.android.server.Watchdog;
53import com.android.server.pm.Settings.DatabaseVersion;
54import com.android.server.storage.DeviceStorageMonitorInternal;
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.PackageInstallerParams;
94import android.content.pm.PackageManager;
95import android.content.pm.PackageParser.ActivityIntentInfo;
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.Xml;
149import android.view.Display;
150
151import java.io.BufferedInputStream;
152import java.io.BufferedOutputStream;
153import java.io.File;
154import java.io.FileDescriptor;
155import java.io.FileInputStream;
156import java.io.FileNotFoundException;
157import java.io.FileOutputStream;
158import java.io.FileReader;
159import java.io.FilenameFilter;
160import java.io.IOException;
161import java.io.InputStream;
162import java.io.PrintWriter;
163import java.nio.charset.StandardCharsets;
164import java.security.NoSuchAlgorithmException;
165import java.security.PublicKey;
166import java.security.cert.CertificateEncodingException;
167import java.security.cert.CertificateException;
168import java.text.SimpleDateFormat;
169import java.util.ArrayList;
170import java.util.Arrays;
171import java.util.Collection;
172import java.util.Collections;
173import java.util.Comparator;
174import java.util.Date;
175import java.util.HashMap;
176import java.util.HashSet;
177import java.util.Iterator;
178import java.util.List;
179import java.util.Map;
180import java.util.Set;
181import java.util.concurrent.atomic.AtomicBoolean;
182import java.util.concurrent.atomic.AtomicLong;
183
184import dalvik.system.DexFile;
185import dalvik.system.StaleDexCacheError;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189
190/**
191 * Keep track of all those .apks everywhere.
192 *
193 * This is very central to the platform's security; please run the unit
194 * tests whenever making modifications here:
195 *
196mmm frameworks/base/tests/AndroidTests
197adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
198adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
199 *
200 * {@hide}
201 */
202public class PackageManagerService extends IPackageManager.Stub {
203    static final String TAG = "PackageManager";
204    static final boolean DEBUG_SETTINGS = false;
205    static final boolean DEBUG_PREFERRED = false;
206    static final boolean DEBUG_UPGRADE = false;
207    private static final boolean DEBUG_INSTALL = false;
208    private static final boolean DEBUG_REMOVE = false;
209    private static final boolean DEBUG_BROADCASTS = false;
210    private static final boolean DEBUG_SHOW_INFO = false;
211    private static final boolean DEBUG_PACKAGE_INFO = false;
212    private static final boolean DEBUG_INTENT_MATCHING = false;
213    private static final boolean DEBUG_PACKAGE_SCANNING = false;
214    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
215    private static final boolean DEBUG_VERIFY = false;
216    private static final boolean DEBUG_DEXOPT = false;
217
218    private static final int RADIO_UID = Process.PHONE_UID;
219    private static final int LOG_UID = Process.LOG_UID;
220    private static final int NFC_UID = Process.NFC_UID;
221    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
222    private static final int SHELL_UID = Process.SHELL_UID;
223
224    // Cap the size of permission trees that 3rd party apps can define
225    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
226
227    private static final int REMOVE_EVENTS =
228        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
229    private static final int ADD_EVENTS =
230        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
231
232    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
233    // Suffix used during package installation when copying/moving
234    // package apks to install directory.
235    private static final String INSTALL_PACKAGE_SUFFIX = "-";
236
237    static final int SCAN_MONITOR = 1<<0;
238    static final int SCAN_NO_DEX = 1<<1;
239    static final int SCAN_FORCE_DEX = 1<<2;
240    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
241    static final int SCAN_NEW_INSTALL = 1<<4;
242    static final int SCAN_NO_PATHS = 1<<5;
243    static final int SCAN_UPDATE_TIME = 1<<6;
244    static final int SCAN_DEFER_DEX = 1<<7;
245    static final int SCAN_BOOTING = 1<<8;
246    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
247    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
248
249    static final int REMOVE_CHATTY = 1<<16;
250
251    /**
252     * Timeout (in milliseconds) after which the watchdog should declare that
253     * our handler thread is wedged.  The usual default for such things is one
254     * minute but we sometimes do very lengthy I/O operations on this thread,
255     * such as installing multi-gigabyte applications, so ours needs to be longer.
256     */
257    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
258
259    /**
260     * Whether verification is enabled by default.
261     */
262    private static final boolean DEFAULT_VERIFY_ENABLE = true;
263
264    /**
265     * The default maximum time to wait for the verification agent to return in
266     * milliseconds.
267     */
268    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
269
270    /**
271     * The default response for package verification timeout.
272     *
273     * This can be either PackageManager.VERIFICATION_ALLOW or
274     * PackageManager.VERIFICATION_REJECT.
275     */
276    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
277
278    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
279
280    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
281            DEFAULT_CONTAINER_PACKAGE,
282            "com.android.defcontainer.DefaultContainerService");
283
284    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
285
286    private static final String LIB_DIR_NAME = "lib";
287    private static final String LIB64_DIR_NAME = "lib64";
288
289    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
290
291    static final String mTempContainerPrefix = "smdl2tmp";
292
293    private static String sPreferredInstructionSet;
294
295    final ServiceThread mHandlerThread;
296
297    private static final String IDMAP_PREFIX = "/data/resource-cache/";
298    private static final String IDMAP_SUFFIX = "@idmap";
299
300    final PackageHandler mHandler;
301
302    final int mSdkVersion = Build.VERSION.SDK_INT;
303
304    final Context mContext;
305    final boolean mFactoryTest;
306    final boolean mOnlyCore;
307    final DisplayMetrics mMetrics;
308    final int mDefParseFlags;
309    final String[] mSeparateProcesses;
310
311    // This is where all application persistent data goes.
312    final File mAppDataDir;
313
314    // This is where all application persistent data goes for secondary users.
315    final File mUserAppDataDir;
316
317    /** The location for ASEC container files on internal storage. */
318    final String mAsecInternalPath;
319
320    // This is the object monitoring the framework dir.
321    final FileObserver mFrameworkInstallObserver;
322
323    // This is the object monitoring the system app dir.
324    final FileObserver mSystemInstallObserver;
325
326    // This is the object monitoring the privileged system app dir.
327    final FileObserver mPrivilegedInstallObserver;
328
329    // This is the object monitoring the vendor app dir.
330    final FileObserver mVendorInstallObserver;
331
332    // This is the object monitoring the vendor overlay package dir.
333    final FileObserver mVendorOverlayInstallObserver;
334
335    // This is the object monitoring the OEM app dir.
336    final FileObserver mOemInstallObserver;
337
338    // This is the object monitoring mAppInstallDir.
339    final FileObserver mAppInstallObserver;
340
341    // This is the object monitoring mDrmAppPrivateInstallDir.
342    final FileObserver mDrmAppInstallObserver;
343
344    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
345    // LOCK HELD.  Can be called with mInstallLock held.
346    final Installer mInstaller;
347
348    final File mAppInstallDir;
349
350    /**
351     * Directory to which applications installed internally have native
352     * libraries copied.
353     */
354    private File mAppLibInstallDir;
355
356    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
357    // apps.
358    final File mDrmAppPrivateInstallDir;
359
360    final File mAppStagingDir;
361
362    // ----------------------------------------------------------------
363
364    // Lock for state used when installing and doing other long running
365    // operations.  Methods that must be called with this lock held have
366    // the suffix "LI".
367    final Object mInstallLock = new Object();
368
369    // These are the directories in the 3rd party applications installed dir
370    // that we have currently loaded packages from.  Keys are the application's
371    // installed zip file (absolute codePath), and values are Package.
372    final HashMap<String, PackageParser.Package> mAppDirs =
373            new HashMap<String, PackageParser.Package>();
374
375    // Information for the parser to write more useful error messages.
376    int mLastScanError;
377
378    // ----------------------------------------------------------------
379
380    // Keys are String (package name), values are Package.  This also serves
381    // as the lock for the global state.  Methods that must be called with
382    // this lock held have the prefix "LP".
383    final HashMap<String, PackageParser.Package> mPackages =
384            new HashMap<String, PackageParser.Package>();
385
386    // Tracks available target package names -> overlay package paths.
387    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
388        new HashMap<String, HashMap<String, PackageParser.Package>>();
389
390    final Settings mSettings;
391    boolean mRestoredSettings;
392
393    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
394    int[] mGlobalGids;
395
396    // These are the built-in uid -> permission mappings that were read from the
397    // etc/permissions.xml file.
398    final SparseArray<HashSet<String>> mSystemPermissions =
399            new SparseArray<HashSet<String>>();
400
401    static final class SharedLibraryEntry {
402        final String path;
403        final String apk;
404
405        SharedLibraryEntry(String _path, String _apk) {
406            path = _path;
407            apk = _apk;
408        }
409    }
410
411    // These are the built-in shared libraries that were read from the
412    // etc/permissions.xml file.
413    final HashMap<String, SharedLibraryEntry> mSharedLibraries
414            = new HashMap<String, SharedLibraryEntry>();
415
416    // These are the features this devices supports that were read from the
417    // etc/permissions.xml file.
418    final HashMap<String, FeatureInfo> mAvailableFeatures =
419            new HashMap<String, FeatureInfo>();
420
421    // If mac_permissions.xml was found for seinfo labeling.
422    boolean mFoundPolicyFile;
423
424    // If a recursive restorecon of /data/data/<pkg> is needed.
425    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
426
427    // All available activities, for your resolving pleasure.
428    final ActivityIntentResolver mActivities =
429            new ActivityIntentResolver();
430
431    // All available receivers, for your resolving pleasure.
432    final ActivityIntentResolver mReceivers =
433            new ActivityIntentResolver();
434
435    // All available services, for your resolving pleasure.
436    final ServiceIntentResolver mServices = new ServiceIntentResolver();
437
438    // All available providers, for your resolving pleasure.
439    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
440
441    // Mapping from provider base names (first directory in content URI codePath)
442    // to the provider information.
443    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
444            new HashMap<String, PackageParser.Provider>();
445
446    // Mapping from instrumentation class names to info about them.
447    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
448            new HashMap<ComponentName, PackageParser.Instrumentation>();
449
450    // Mapping from permission names to info about them.
451    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
452            new HashMap<String, PackageParser.PermissionGroup>();
453
454    // Packages whose data we have transfered into another package, thus
455    // should no longer exist.
456    final HashSet<String> mTransferedPackages = new HashSet<String>();
457
458    // Broadcast actions that are only available to the system.
459    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
460
461    /** List of packages waiting for verification. */
462    final SparseArray<PackageVerificationState> mPendingVerification
463            = new SparseArray<PackageVerificationState>();
464
465    final PackageInstallerService mInstallerService;
466
467    HashSet<PackageParser.Package> mDeferredDexOpt = null;
468
469    /** Token for keys in mPendingVerification. */
470    private int mPendingVerificationToken = 0;
471
472    boolean mSystemReady;
473    boolean mSafeMode;
474    boolean mHasSystemUidErrors;
475
476    ApplicationInfo mAndroidApplication;
477    final ActivityInfo mResolveActivity = new ActivityInfo();
478    final ResolveInfo mResolveInfo = new ResolveInfo();
479    ComponentName mResolveComponentName;
480    PackageParser.Package mPlatformPackage;
481    ComponentName mCustomResolverComponentName;
482
483    boolean mResolverReplaced = false;
484
485    // Set of pending broadcasts for aggregating enable/disable of components.
486    static class PendingPackageBroadcasts {
487        // for each user id, a map of <package name -> components within that package>
488        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
489
490        public PendingPackageBroadcasts() {
491            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
492        }
493
494        public ArrayList<String> get(int userId, String packageName) {
495            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
496            return packages.get(packageName);
497        }
498
499        public void put(int userId, String packageName, ArrayList<String> components) {
500            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
501            packages.put(packageName, components);
502        }
503
504        public void remove(int userId, String packageName) {
505            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
506            if (packages != null) {
507                packages.remove(packageName);
508            }
509        }
510
511        public void remove(int userId) {
512            mUidMap.remove(userId);
513        }
514
515        public int userIdCount() {
516            return mUidMap.size();
517        }
518
519        public int userIdAt(int n) {
520            return mUidMap.keyAt(n);
521        }
522
523        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
524            return mUidMap.get(userId);
525        }
526
527        public int size() {
528            // total number of pending broadcast entries across all userIds
529            int num = 0;
530            for (int i = 0; i< mUidMap.size(); i++) {
531                num += mUidMap.valueAt(i).size();
532            }
533            return num;
534        }
535
536        public void clear() {
537            mUidMap.clear();
538        }
539
540        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
541            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
542            if (map == null) {
543                map = new HashMap<String, ArrayList<String>>();
544                mUidMap.put(userId, map);
545            }
546            return map;
547        }
548    }
549    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
550
551    // Service Connection to remote media container service to copy
552    // package uri's from external media onto secure containers
553    // or internal storage.
554    private IMediaContainerService mContainerService = null;
555
556    static final int SEND_PENDING_BROADCAST = 1;
557    static final int MCS_BOUND = 3;
558    static final int END_COPY = 4;
559    static final int INIT_COPY = 5;
560    static final int MCS_UNBIND = 6;
561    static final int START_CLEANING_PACKAGE = 7;
562    static final int FIND_INSTALL_LOC = 8;
563    static final int POST_INSTALL = 9;
564    static final int MCS_RECONNECT = 10;
565    static final int MCS_GIVE_UP = 11;
566    static final int UPDATED_MEDIA_STATUS = 12;
567    static final int WRITE_SETTINGS = 13;
568    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
569    static final int PACKAGE_VERIFIED = 15;
570    static final int CHECK_PENDING_VERIFICATION = 16;
571
572    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
573
574    // Delay time in millisecs
575    static final int BROADCAST_DELAY = 10 * 1000;
576
577    static UserManagerService sUserManager;
578
579    // Stores a list of users whose package restrictions file needs to be updated
580    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
581
582    final private DefaultContainerConnection mDefContainerConn =
583            new DefaultContainerConnection();
584    class DefaultContainerConnection implements ServiceConnection {
585        public void onServiceConnected(ComponentName name, IBinder service) {
586            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
587            IMediaContainerService imcs =
588                IMediaContainerService.Stub.asInterface(service);
589            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
590        }
591
592        public void onServiceDisconnected(ComponentName name) {
593            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
594        }
595    };
596
597    // Recordkeeping of restore-after-install operations that are currently in flight
598    // between the Package Manager and the Backup Manager
599    class PostInstallData {
600        public InstallArgs args;
601        public PackageInstalledInfo res;
602
603        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
604            args = _a;
605            res = _r;
606        }
607    };
608    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
609    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
610
611    private final String mRequiredVerifierPackage;
612
613    private final PackageUsage mPackageUsage = new PackageUsage();
614
615    private class PackageUsage {
616        private static final int WRITE_INTERVAL
617            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
618
619        private final Object mFileLock = new Object();
620        private final AtomicLong mLastWritten = new AtomicLong(0);
621        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
622
623        private boolean mIsFirstBoot = false;
624
625        boolean isFirstBoot() {
626            return mIsFirstBoot;
627        }
628
629        void write(boolean force) {
630            if (force) {
631                writeInternal();
632                return;
633            }
634            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
635                && !DEBUG_DEXOPT) {
636                return;
637            }
638            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
639                new Thread("PackageUsage_DiskWriter") {
640                    @Override
641                    public void run() {
642                        try {
643                            writeInternal();
644                        } finally {
645                            mBackgroundWriteRunning.set(false);
646                        }
647                    }
648                }.start();
649            }
650        }
651
652        private void writeInternal() {
653            synchronized (mPackages) {
654                synchronized (mFileLock) {
655                    AtomicFile file = getFile();
656                    FileOutputStream f = null;
657                    try {
658                        f = file.startWrite();
659                        BufferedOutputStream out = new BufferedOutputStream(f);
660                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
661                        StringBuilder sb = new StringBuilder();
662                        for (PackageParser.Package pkg : mPackages.values()) {
663                            if (pkg.mLastPackageUsageTimeInMills == 0) {
664                                continue;
665                            }
666                            sb.setLength(0);
667                            sb.append(pkg.packageName);
668                            sb.append(' ');
669                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
670                            sb.append('\n');
671                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
672                        }
673                        out.flush();
674                        file.finishWrite(f);
675                    } catch (IOException e) {
676                        if (f != null) {
677                            file.failWrite(f);
678                        }
679                        Log.e(TAG, "Failed to write package usage times", e);
680                    }
681                }
682            }
683            mLastWritten.set(SystemClock.elapsedRealtime());
684        }
685
686        void readLP() {
687            synchronized (mFileLock) {
688                AtomicFile file = getFile();
689                BufferedInputStream in = null;
690                try {
691                    in = new BufferedInputStream(file.openRead());
692                    StringBuffer sb = new StringBuffer();
693                    while (true) {
694                        String packageName = readToken(in, sb, ' ');
695                        if (packageName == null) {
696                            break;
697                        }
698                        String timeInMillisString = readToken(in, sb, '\n');
699                        if (timeInMillisString == null) {
700                            throw new IOException("Failed to find last usage time for package "
701                                                  + packageName);
702                        }
703                        PackageParser.Package pkg = mPackages.get(packageName);
704                        if (pkg == null) {
705                            continue;
706                        }
707                        long timeInMillis;
708                        try {
709                            timeInMillis = Long.parseLong(timeInMillisString.toString());
710                        } catch (NumberFormatException e) {
711                            throw new IOException("Failed to parse " + timeInMillisString
712                                                  + " as a long.", e);
713                        }
714                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
715                    }
716                } catch (FileNotFoundException expected) {
717                    mIsFirstBoot = true;
718                } catch (IOException e) {
719                    Log.w(TAG, "Failed to read package usage times", e);
720                } finally {
721                    IoUtils.closeQuietly(in);
722                }
723            }
724            mLastWritten.set(SystemClock.elapsedRealtime());
725        }
726
727        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
728                throws IOException {
729            sb.setLength(0);
730            while (true) {
731                int ch = in.read();
732                if (ch == -1) {
733                    if (sb.length() == 0) {
734                        return null;
735                    }
736                    throw new IOException("Unexpected EOF");
737                }
738                if (ch == endOfToken) {
739                    return sb.toString();
740                }
741                sb.append((char)ch);
742            }
743        }
744
745        private AtomicFile getFile() {
746            File dataDir = Environment.getDataDirectory();
747            File systemDir = new File(dataDir, "system");
748            File fname = new File(systemDir, "package-usage.list");
749            return new AtomicFile(fname);
750        }
751    }
752
753    class PackageHandler extends Handler {
754        private boolean mBound = false;
755        final ArrayList<HandlerParams> mPendingInstalls =
756            new ArrayList<HandlerParams>();
757
758        private boolean connectToService() {
759            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
760                    " DefaultContainerService");
761            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
762            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
763            if (mContext.bindServiceAsUser(service, mDefContainerConn,
764                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
765                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
766                mBound = true;
767                return true;
768            }
769            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
770            return false;
771        }
772
773        private void disconnectService() {
774            mContainerService = null;
775            mBound = false;
776            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
777            mContext.unbindService(mDefContainerConn);
778            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
779        }
780
781        PackageHandler(Looper looper) {
782            super(looper);
783        }
784
785        public void handleMessage(Message msg) {
786            try {
787                doHandleMessage(msg);
788            } finally {
789                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
790            }
791        }
792
793        void doHandleMessage(Message msg) {
794            switch (msg.what) {
795                case INIT_COPY: {
796                    HandlerParams params = (HandlerParams) msg.obj;
797                    int idx = mPendingInstalls.size();
798                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
799                    // If a bind was already initiated we dont really
800                    // need to do anything. The pending install
801                    // will be processed later on.
802                    if (!mBound) {
803                        // If this is the only one pending we might
804                        // have to bind to the service again.
805                        if (!connectToService()) {
806                            Slog.e(TAG, "Failed to bind to media container service");
807                            params.serviceError();
808                            return;
809                        } else {
810                            // Once we bind to the service, the first
811                            // pending request will be processed.
812                            mPendingInstalls.add(idx, params);
813                        }
814                    } else {
815                        mPendingInstalls.add(idx, params);
816                        // Already bound to the service. Just make
817                        // sure we trigger off processing the first request.
818                        if (idx == 0) {
819                            mHandler.sendEmptyMessage(MCS_BOUND);
820                        }
821                    }
822                    break;
823                }
824                case MCS_BOUND: {
825                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
826                    if (msg.obj != null) {
827                        mContainerService = (IMediaContainerService) msg.obj;
828                    }
829                    if (mContainerService == null) {
830                        // Something seriously wrong. Bail out
831                        Slog.e(TAG, "Cannot bind to media container service");
832                        for (HandlerParams params : mPendingInstalls) {
833                            // Indicate service bind error
834                            params.serviceError();
835                        }
836                        mPendingInstalls.clear();
837                    } else if (mPendingInstalls.size() > 0) {
838                        HandlerParams params = mPendingInstalls.get(0);
839                        if (params != null) {
840                            if (params.startCopy()) {
841                                // We are done...  look for more work or to
842                                // go idle.
843                                if (DEBUG_SD_INSTALL) Log.i(TAG,
844                                        "Checking for more work or unbind...");
845                                // Delete pending install
846                                if (mPendingInstalls.size() > 0) {
847                                    mPendingInstalls.remove(0);
848                                }
849                                if (mPendingInstalls.size() == 0) {
850                                    if (mBound) {
851                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
852                                                "Posting delayed MCS_UNBIND");
853                                        removeMessages(MCS_UNBIND);
854                                        Message ubmsg = obtainMessage(MCS_UNBIND);
855                                        // Unbind after a little delay, to avoid
856                                        // continual thrashing.
857                                        sendMessageDelayed(ubmsg, 10000);
858                                    }
859                                } else {
860                                    // There are more pending requests in queue.
861                                    // Just post MCS_BOUND message to trigger processing
862                                    // of next pending install.
863                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
864                                            "Posting MCS_BOUND for next work");
865                                    mHandler.sendEmptyMessage(MCS_BOUND);
866                                }
867                            }
868                        }
869                    } else {
870                        // Should never happen ideally.
871                        Slog.w(TAG, "Empty queue");
872                    }
873                    break;
874                }
875                case MCS_RECONNECT: {
876                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
877                    if (mPendingInstalls.size() > 0) {
878                        if (mBound) {
879                            disconnectService();
880                        }
881                        if (!connectToService()) {
882                            Slog.e(TAG, "Failed to bind to media container service");
883                            for (HandlerParams params : mPendingInstalls) {
884                                // Indicate service bind error
885                                params.serviceError();
886                            }
887                            mPendingInstalls.clear();
888                        }
889                    }
890                    break;
891                }
892                case MCS_UNBIND: {
893                    // If there is no actual work left, then time to unbind.
894                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
895
896                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
897                        if (mBound) {
898                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
899
900                            disconnectService();
901                        }
902                    } else if (mPendingInstalls.size() > 0) {
903                        // There are more pending requests in queue.
904                        // Just post MCS_BOUND message to trigger processing
905                        // of next pending install.
906                        mHandler.sendEmptyMessage(MCS_BOUND);
907                    }
908
909                    break;
910                }
911                case MCS_GIVE_UP: {
912                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
913                    mPendingInstalls.remove(0);
914                    break;
915                }
916                case SEND_PENDING_BROADCAST: {
917                    String packages[];
918                    ArrayList<String> components[];
919                    int size = 0;
920                    int uids[];
921                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
922                    synchronized (mPackages) {
923                        if (mPendingBroadcasts == null) {
924                            return;
925                        }
926                        size = mPendingBroadcasts.size();
927                        if (size <= 0) {
928                            // Nothing to be done. Just return
929                            return;
930                        }
931                        packages = new String[size];
932                        components = new ArrayList[size];
933                        uids = new int[size];
934                        int i = 0;  // filling out the above arrays
935
936                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
937                            int packageUserId = mPendingBroadcasts.userIdAt(n);
938                            Iterator<Map.Entry<String, ArrayList<String>>> it
939                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
940                                            .entrySet().iterator();
941                            while (it.hasNext() && i < size) {
942                                Map.Entry<String, ArrayList<String>> ent = it.next();
943                                packages[i] = ent.getKey();
944                                components[i] = ent.getValue();
945                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
946                                uids[i] = (ps != null)
947                                        ? UserHandle.getUid(packageUserId, ps.appId)
948                                        : -1;
949                                i++;
950                            }
951                        }
952                        size = i;
953                        mPendingBroadcasts.clear();
954                    }
955                    // Send broadcasts
956                    for (int i = 0; i < size; i++) {
957                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
958                    }
959                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
960                    break;
961                }
962                case START_CLEANING_PACKAGE: {
963                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
964                    final String packageName = (String)msg.obj;
965                    final int userId = msg.arg1;
966                    final boolean andCode = msg.arg2 != 0;
967                    synchronized (mPackages) {
968                        if (userId == UserHandle.USER_ALL) {
969                            int[] users = sUserManager.getUserIds();
970                            for (int user : users) {
971                                mSettings.addPackageToCleanLPw(
972                                        new PackageCleanItem(user, packageName, andCode));
973                            }
974                        } else {
975                            mSettings.addPackageToCleanLPw(
976                                    new PackageCleanItem(userId, packageName, andCode));
977                        }
978                    }
979                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
980                    startCleaningPackages();
981                } break;
982                case POST_INSTALL: {
983                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
984                    PostInstallData data = mRunningInstalls.get(msg.arg1);
985                    mRunningInstalls.delete(msg.arg1);
986                    boolean deleteOld = false;
987
988                    if (data != null) {
989                        InstallArgs args = data.args;
990                        PackageInstalledInfo res = data.res;
991
992                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
993                            res.removedInfo.sendBroadcast(false, true, false);
994                            Bundle extras = new Bundle(1);
995                            extras.putInt(Intent.EXTRA_UID, res.uid);
996                            // Determine the set of users who are adding this
997                            // package for the first time vs. those who are seeing
998                            // an update.
999                            int[] firstUsers;
1000                            int[] updateUsers = new int[0];
1001                            if (res.origUsers == null || res.origUsers.length == 0) {
1002                                firstUsers = res.newUsers;
1003                            } else {
1004                                firstUsers = new int[0];
1005                                for (int i=0; i<res.newUsers.length; i++) {
1006                                    int user = res.newUsers[i];
1007                                    boolean isNew = true;
1008                                    for (int j=0; j<res.origUsers.length; j++) {
1009                                        if (res.origUsers[j] == user) {
1010                                            isNew = false;
1011                                            break;
1012                                        }
1013                                    }
1014                                    if (isNew) {
1015                                        int[] newFirst = new int[firstUsers.length+1];
1016                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1017                                                firstUsers.length);
1018                                        newFirst[firstUsers.length] = user;
1019                                        firstUsers = newFirst;
1020                                    } else {
1021                                        int[] newUpdate = new int[updateUsers.length+1];
1022                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1023                                                updateUsers.length);
1024                                        newUpdate[updateUsers.length] = user;
1025                                        updateUsers = newUpdate;
1026                                    }
1027                                }
1028                            }
1029                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1030                                    res.pkg.applicationInfo.packageName,
1031                                    extras, null, null, firstUsers);
1032                            final boolean update = res.removedInfo.removedPackage != null;
1033                            if (update) {
1034                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1035                            }
1036                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1037                                    res.pkg.applicationInfo.packageName,
1038                                    extras, null, null, updateUsers);
1039                            if (update) {
1040                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1041                                        res.pkg.applicationInfo.packageName,
1042                                        extras, null, null, updateUsers);
1043                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1044                                        null, null,
1045                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1046
1047                                // treat asec-hosted packages like removable media on upgrade
1048                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1049                                    if (DEBUG_INSTALL) {
1050                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1051                                                + " is ASEC-hosted -> AVAILABLE");
1052                                    }
1053                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1054                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1055                                    pkgList.add(res.pkg.applicationInfo.packageName);
1056                                    sendResourcesChangedBroadcast(true, true,
1057                                            pkgList,uidArray, null);
1058                                }
1059                            }
1060                            if (res.removedInfo.args != null) {
1061                                // Remove the replaced package's older resources safely now
1062                                deleteOld = true;
1063                            }
1064
1065                            // Log current value of "unknown sources" setting
1066                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1067                                getUnknownSourcesSettings());
1068                        }
1069                        // Force a gc to clear up things
1070                        Runtime.getRuntime().gc();
1071                        // We delete after a gc for applications  on sdcard.
1072                        if (deleteOld) {
1073                            synchronized (mInstallLock) {
1074                                res.removedInfo.args.doPostDeleteLI(true);
1075                            }
1076                        }
1077                        if (args.observer != null) {
1078                            try {
1079                                args.observer.packageInstalled(res.name, res.returnCode);
1080                            } catch (RemoteException e) {
1081                                Slog.i(TAG, "Observer no longer exists.");
1082                            }
1083                        }
1084                        if (args.observer2 != null) {
1085                            try {
1086                                Bundle extras = extrasForInstallResult(res);
1087                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1088                            } catch (RemoteException e) {
1089                                Slog.i(TAG, "Observer no longer exists.");
1090                            }
1091                        }
1092                    } else {
1093                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1094                    }
1095                } break;
1096                case UPDATED_MEDIA_STATUS: {
1097                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1098                    boolean reportStatus = msg.arg1 == 1;
1099                    boolean doGc = msg.arg2 == 1;
1100                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1101                    if (doGc) {
1102                        // Force a gc to clear up stale containers.
1103                        Runtime.getRuntime().gc();
1104                    }
1105                    if (msg.obj != null) {
1106                        @SuppressWarnings("unchecked")
1107                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1108                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1109                        // Unload containers
1110                        unloadAllContainers(args);
1111                    }
1112                    if (reportStatus) {
1113                        try {
1114                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1115                            PackageHelper.getMountService().finishMediaUpdate();
1116                        } catch (RemoteException e) {
1117                            Log.e(TAG, "MountService not running?");
1118                        }
1119                    }
1120                } break;
1121                case WRITE_SETTINGS: {
1122                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123                    synchronized (mPackages) {
1124                        removeMessages(WRITE_SETTINGS);
1125                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1126                        mSettings.writeLPr();
1127                        mDirtyUsers.clear();
1128                    }
1129                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130                } break;
1131                case WRITE_PACKAGE_RESTRICTIONS: {
1132                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1133                    synchronized (mPackages) {
1134                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1135                        for (int userId : mDirtyUsers) {
1136                            mSettings.writePackageRestrictionsLPr(userId);
1137                        }
1138                        mDirtyUsers.clear();
1139                    }
1140                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1141                } break;
1142                case CHECK_PENDING_VERIFICATION: {
1143                    final int verificationId = msg.arg1;
1144                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1145
1146                    if ((state != null) && !state.timeoutExtended()) {
1147                        final InstallArgs args = state.getInstallArgs();
1148                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1149                        mPendingVerification.remove(verificationId);
1150
1151                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1152
1153                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1154                            Slog.i(TAG, "Continuing with installation of "
1155                                    + args.packageURI.toString());
1156                            state.setVerifierResponse(Binder.getCallingUid(),
1157                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1158                            broadcastPackageVerified(verificationId, args.packageURI,
1159                                    PackageManager.VERIFICATION_ALLOW,
1160                                    state.getInstallArgs().getUser());
1161                            try {
1162                                ret = args.copyApk(mContainerService, true);
1163                            } catch (RemoteException e) {
1164                                Slog.e(TAG, "Could not contact the ContainerService");
1165                            }
1166                        } else {
1167                            broadcastPackageVerified(verificationId, args.packageURI,
1168                                    PackageManager.VERIFICATION_REJECT,
1169                                    state.getInstallArgs().getUser());
1170                        }
1171
1172                        processPendingInstall(args, ret);
1173                        mHandler.sendEmptyMessage(MCS_UNBIND);
1174                    }
1175                    break;
1176                }
1177                case PACKAGE_VERIFIED: {
1178                    final int verificationId = msg.arg1;
1179
1180                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1181                    if (state == null) {
1182                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1183                        break;
1184                    }
1185
1186                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1187
1188                    state.setVerifierResponse(response.callerUid, response.code);
1189
1190                    if (state.isVerificationComplete()) {
1191                        mPendingVerification.remove(verificationId);
1192
1193                        final InstallArgs args = state.getInstallArgs();
1194
1195                        int ret;
1196                        if (state.isInstallAllowed()) {
1197                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1198                            broadcastPackageVerified(verificationId, args.packageURI,
1199                                    response.code, state.getInstallArgs().getUser());
1200                            try {
1201                                ret = args.copyApk(mContainerService, true);
1202                            } catch (RemoteException e) {
1203                                Slog.e(TAG, "Could not contact the ContainerService");
1204                            }
1205                        } else {
1206                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1207                        }
1208
1209                        processPendingInstall(args, ret);
1210
1211                        mHandler.sendEmptyMessage(MCS_UNBIND);
1212                    }
1213
1214                    break;
1215                }
1216            }
1217        }
1218    }
1219
1220    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1221        Bundle extras = null;
1222        switch (res.returnCode) {
1223            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1224                extras = new Bundle();
1225                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1226                        res.origPermission);
1227                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1228                        res.origPackage);
1229                break;
1230            }
1231        }
1232        return extras;
1233    }
1234
1235    void scheduleWriteSettingsLocked() {
1236        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1237            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1238        }
1239    }
1240
1241    void scheduleWritePackageRestrictionsLocked(int userId) {
1242        if (!sUserManager.exists(userId)) return;
1243        mDirtyUsers.add(userId);
1244        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1245            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1246        }
1247    }
1248
1249    public static final IPackageManager main(Context context, Installer installer,
1250            boolean factoryTest, boolean onlyCore) {
1251        PackageManagerService m = new PackageManagerService(context, installer,
1252                factoryTest, onlyCore);
1253        ServiceManager.addService("package", m);
1254        return m;
1255    }
1256
1257    static String[] splitString(String str, char sep) {
1258        int count = 1;
1259        int i = 0;
1260        while ((i=str.indexOf(sep, i)) >= 0) {
1261            count++;
1262            i++;
1263        }
1264
1265        String[] res = new String[count];
1266        i=0;
1267        count = 0;
1268        int lastI=0;
1269        while ((i=str.indexOf(sep, i)) >= 0) {
1270            res[count] = str.substring(lastI, i);
1271            count++;
1272            i++;
1273            lastI = i;
1274        }
1275        res[count] = str.substring(lastI, str.length());
1276        return res;
1277    }
1278
1279    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1280        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1281                Context.DISPLAY_SERVICE);
1282        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1283    }
1284
1285    public PackageManagerService(Context context, Installer installer,
1286            boolean factoryTest, boolean onlyCore) {
1287        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1288                SystemClock.uptimeMillis());
1289
1290        if (mSdkVersion <= 0) {
1291            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1292        }
1293
1294        mContext = context;
1295        mFactoryTest = factoryTest;
1296        mOnlyCore = onlyCore;
1297        mMetrics = new DisplayMetrics();
1298        mSettings = new Settings(context);
1299        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1300                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311
1312        String separateProcesses = SystemProperties.get("debug.separate_processes");
1313        if (separateProcesses != null && separateProcesses.length() > 0) {
1314            if ("*".equals(separateProcesses)) {
1315                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1316                mSeparateProcesses = null;
1317                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1318            } else {
1319                mDefParseFlags = 0;
1320                mSeparateProcesses = separateProcesses.split(",");
1321                Slog.w(TAG, "Running with debug.separate_processes: "
1322                        + separateProcesses);
1323            }
1324        } else {
1325            mDefParseFlags = 0;
1326            mSeparateProcesses = null;
1327        }
1328
1329        mInstaller = installer;
1330
1331        getDefaultDisplayMetrics(context, mMetrics);
1332
1333        synchronized (mInstallLock) {
1334        // writer
1335        synchronized (mPackages) {
1336            mHandlerThread = new ServiceThread(TAG,
1337                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1338            mHandlerThread.start();
1339            mHandler = new PackageHandler(mHandlerThread.getLooper());
1340            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1341
1342            File dataDir = Environment.getDataDirectory();
1343            mAppDataDir = new File(dataDir, "data");
1344            mAppInstallDir = new File(dataDir, "app");
1345            mAppLibInstallDir = new File(dataDir, "app-lib");
1346            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1347            mUserAppDataDir = new File(dataDir, "user");
1348            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1349            mAppStagingDir = new File(dataDir, "app-staging");
1350
1351            sUserManager = new UserManagerService(context, this,
1352                    mInstallLock, mPackages);
1353
1354            // Read permissions and features from system
1355            readPermissions(Environment.buildPath(
1356                    Environment.getRootDirectory(), "etc", "permissions"), false);
1357            // Only read features from OEM
1358            readPermissions(Environment.buildPath(
1359                    Environment.getOemDirectory(), "etc", "permissions"), true);
1360
1361            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1362
1363            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1364                    mSdkVersion, mOnlyCore);
1365
1366            String customResolverActivity = Resources.getSystem().getString(
1367                    R.string.config_customResolverActivity);
1368            if (TextUtils.isEmpty(customResolverActivity)) {
1369                customResolverActivity = null;
1370            } else {
1371                mCustomResolverComponentName = ComponentName.unflattenFromString(
1372                        customResolverActivity);
1373            }
1374
1375            long startTime = SystemClock.uptimeMillis();
1376
1377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1378                    startTime);
1379
1380            // Set flag to monitor and not change apk file paths when
1381            // scanning install directories.
1382            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1383
1384            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1385
1386            /**
1387             * Add everything in the in the boot class path to the
1388             * list of process files because dexopt will have been run
1389             * if necessary during zygote startup.
1390             */
1391            String bootClassPath = System.getProperty("java.boot.class.path");
1392            if (bootClassPath != null) {
1393                String[] paths = splitString(bootClassPath, ':');
1394                for (int i=0; i<paths.length; i++) {
1395                    alreadyDexOpted.add(paths[i]);
1396                }
1397            } else {
1398                Slog.w(TAG, "No BOOTCLASSPATH found!");
1399            }
1400
1401            boolean didDexOptLibraryOrTool = false;
1402
1403            final List<String> instructionSets = getAllInstructionSets();
1404
1405            /**
1406             * Ensure all external libraries have had dexopt run on them.
1407             */
1408            if (mSharedLibraries.size() > 0) {
1409                // NOTE: For now, we're compiling these system "shared libraries"
1410                // (and framework jars) into all available architectures. It's possible
1411                // to compile them only when we come across an app that uses them (there's
1412                // already logic for that in scanPackageLI) but that adds some complexity.
1413                for (String instructionSet : instructionSets) {
1414                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1415                        final String lib = libEntry.path;
1416                        if (lib == null) {
1417                            continue;
1418                        }
1419
1420                        try {
1421                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1422                                alreadyDexOpted.add(lib);
1423
1424                                // The list of "shared libraries" we have at this point is
1425                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1426                                didDexOptLibraryOrTool = true;
1427                            }
1428                        } catch (FileNotFoundException e) {
1429                            Slog.w(TAG, "Library not found: " + lib);
1430                        } catch (IOException e) {
1431                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1432                                    + e.getMessage());
1433                        }
1434                    }
1435                }
1436            }
1437
1438            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1439
1440            // Gross hack for now: we know this file doesn't contain any
1441            // code, so don't dexopt it to avoid the resulting log spew.
1442            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1443
1444            // Gross hack for now: we know this file is only part of
1445            // the boot class path for art, so don't dexopt it to
1446            // avoid the resulting log spew.
1447            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1448
1449            /**
1450             * And there are a number of commands implemented in Java, which
1451             * we currently need to do the dexopt on so that they can be
1452             * run from a non-root shell.
1453             */
1454            String[] frameworkFiles = frameworkDir.list();
1455            if (frameworkFiles != null) {
1456                // TODO: We could compile these only for the most preferred ABI. We should
1457                // first double check that the dex files for these commands are not referenced
1458                // by other system apps.
1459                for (String instructionSet : instructionSets) {
1460                    for (int i=0; i<frameworkFiles.length; i++) {
1461                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1462                        String path = libPath.getPath();
1463                        // Skip the file if we already did it.
1464                        if (alreadyDexOpted.contains(path)) {
1465                            continue;
1466                        }
1467                        // Skip the file if it is not a type we want to dexopt.
1468                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1469                            continue;
1470                        }
1471                        try {
1472                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1473                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1474                                didDexOptLibraryOrTool = true;
1475                            }
1476                        } catch (FileNotFoundException e) {
1477                            Slog.w(TAG, "Jar not found: " + path);
1478                        } catch (IOException e) {
1479                            Slog.w(TAG, "Exception reading jar: " + path, e);
1480                        }
1481                    }
1482                }
1483            }
1484
1485            if (didDexOptLibraryOrTool) {
1486                // If we dexopted a library or tool, then something on the system has
1487                // changed. Consider this significant, and wipe away all other
1488                // existing dexopt files to ensure we don't leave any dangling around.
1489                //
1490                // Additionally, delete all dex files from the root directory
1491                // since there shouldn't be any there anyway.
1492                //
1493                // TODO: This should be revisited because it isn't as good an indicator
1494                // as it used to be. It used to include the boot classpath but at some point
1495                // DexFile.isDexOptNeeded started returning false for the boot
1496                // class path files in all cases. It is very possible in a
1497                // small maintenance release update that the library and tool
1498                // jars may be unchanged but APK could be removed resulting in
1499                // unused dalvik-cache files.
1500                mInstaller.pruneDexCache();
1501            }
1502
1503            // Collect vendor overlay packages.
1504            // (Do this before scanning any apps.)
1505            // For security and version matching reason, only consider
1506            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1507            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1508            mVendorOverlayInstallObserver = new AppDirObserver(
1509                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1510            mVendorOverlayInstallObserver.startWatching();
1511            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1513
1514            // Find base frameworks (resource packages without code).
1515            mFrameworkInstallObserver = new AppDirObserver(
1516                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1517            mFrameworkInstallObserver.startWatching();
1518            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1519                    | PackageParser.PARSE_IS_SYSTEM_DIR
1520                    | PackageParser.PARSE_IS_PRIVILEGED,
1521                    scanMode | SCAN_NO_DEX, 0);
1522
1523            // Collected privileged system packages.
1524            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1525            mPrivilegedInstallObserver = new AppDirObserver(
1526                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1527            mPrivilegedInstallObserver.startWatching();
1528                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1529                        | PackageParser.PARSE_IS_SYSTEM_DIR
1530                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1531
1532            // Collect ordinary system packages.
1533            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1534            mSystemInstallObserver = new AppDirObserver(
1535                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1536            mSystemInstallObserver.startWatching();
1537            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1538                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1539
1540            // Collect all vendor packages.
1541            File vendorAppDir = new File("/vendor/app");
1542            try {
1543                vendorAppDir = vendorAppDir.getCanonicalFile();
1544            } catch (IOException e) {
1545                // failed to look up canonical path, continue with original one
1546            }
1547            mVendorInstallObserver = new AppDirObserver(
1548                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1549            mVendorInstallObserver.startWatching();
1550            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1551                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1552
1553            // Collect all OEM packages.
1554            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1555            mOemInstallObserver = new AppDirObserver(
1556                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1557            mOemInstallObserver.startWatching();
1558            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1559                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1560
1561            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1562            mInstaller.moveFiles();
1563
1564            // Prune any system packages that no longer exist.
1565            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1566            if (!mOnlyCore) {
1567                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1568                while (psit.hasNext()) {
1569                    PackageSetting ps = psit.next();
1570
1571                    /*
1572                     * If this is not a system app, it can't be a
1573                     * disable system app.
1574                     */
1575                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1576                        continue;
1577                    }
1578
1579                    /*
1580                     * If the package is scanned, it's not erased.
1581                     */
1582                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1583                    if (scannedPkg != null) {
1584                        /*
1585                         * If the system app is both scanned and in the
1586                         * disabled packages list, then it must have been
1587                         * added via OTA. Remove it from the currently
1588                         * scanned package so the previously user-installed
1589                         * application can be scanned.
1590                         */
1591                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1592                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1593                                    + "; removing system app");
1594                            removePackageLI(ps, true);
1595                        }
1596
1597                        continue;
1598                    }
1599
1600                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1601                        psit.remove();
1602                        String msg = "System package " + ps.name
1603                                + " no longer exists; wiping its data";
1604                        reportSettingsProblem(Log.WARN, msg);
1605                        removeDataDirsLI(ps.name);
1606                    } else {
1607                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1608                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1609                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1610                        }
1611                    }
1612                }
1613            }
1614
1615            //look for any incomplete package installations
1616            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1617            //clean up list
1618            for(int i = 0; i < deletePkgsList.size(); i++) {
1619                //clean up here
1620                cleanupInstallFailedPackage(deletePkgsList.get(i));
1621            }
1622            //delete tmp files
1623            deleteTempPackageFiles();
1624
1625            // Remove any shared userIDs that have no associated packages
1626            mSettings.pruneSharedUsersLPw();
1627
1628            if (!mOnlyCore) {
1629                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1630                        SystemClock.uptimeMillis());
1631                mAppInstallObserver = new AppDirObserver(
1632                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1633                mAppInstallObserver.startWatching();
1634                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1635
1636                mDrmAppInstallObserver = new AppDirObserver(
1637                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1638                mDrmAppInstallObserver.startWatching();
1639                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1640                        scanMode, 0);
1641
1642                /**
1643                 * Remove disable package settings for any updated system
1644                 * apps that were removed via an OTA. If they're not a
1645                 * previously-updated app, remove them completely.
1646                 * Otherwise, just revoke their system-level permissions.
1647                 */
1648                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1649                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1650                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1651
1652                    String msg;
1653                    if (deletedPkg == null) {
1654                        msg = "Updated system package " + deletedAppName
1655                                + " no longer exists; wiping its data";
1656                        removeDataDirsLI(deletedAppName);
1657                    } else {
1658                        msg = "Updated system app + " + deletedAppName
1659                                + " no longer present; removing system privileges for "
1660                                + deletedAppName;
1661
1662                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1663
1664                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1665                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1666                    }
1667                    reportSettingsProblem(Log.WARN, msg);
1668                }
1669            } else {
1670                mAppInstallObserver = null;
1671                mDrmAppInstallObserver = null;
1672            }
1673
1674            // Now that we know all of the shared libraries, update all clients to have
1675            // the correct library paths.
1676            updateAllSharedLibrariesLPw();
1677
1678            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1679                // NOTE: We ignore potential failures here during a system scan (like
1680                // the rest of the commands above) because there's precious little we
1681                // can do about it. A settings error is reported, though.
1682                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1683                        false /* force dexopt */, false /* defer dexopt */);
1684            }
1685
1686            // Now that we know all the packages we are keeping,
1687            // read and update their last usage times.
1688            mPackageUsage.readLP();
1689
1690            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1691                    SystemClock.uptimeMillis());
1692            Slog.i(TAG, "Time to scan packages: "
1693                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1694                    + " seconds");
1695
1696            // If the platform SDK has changed since the last time we booted,
1697            // we need to re-grant app permission to catch any new ones that
1698            // appear.  This is really a hack, and means that apps can in some
1699            // cases get permissions that the user didn't initially explicitly
1700            // allow...  it would be nice to have some better way to handle
1701            // this situation.
1702            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1703                    != mSdkVersion;
1704            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1705                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1706                    + "; regranting permissions for internal storage");
1707            mSettings.mInternalSdkPlatform = mSdkVersion;
1708
1709            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1710                    | (regrantPermissions
1711                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1712                            : 0));
1713
1714            // If this is the first boot, and it is a normal boot, then
1715            // we need to initialize the default preferred apps.
1716            if (!mRestoredSettings && !onlyCore) {
1717                mSettings.readDefaultPreferredAppsLPw(this, 0);
1718            }
1719
1720            // All the changes are done during package scanning.
1721            mSettings.updateInternalDatabaseVersion();
1722
1723            // can downgrade to reader
1724            mSettings.writeLPr();
1725
1726            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1727                    SystemClock.uptimeMillis());
1728
1729
1730            mRequiredVerifierPackage = getRequiredVerifierLPr();
1731        } // synchronized (mPackages)
1732        } // synchronized (mInstallLock)
1733
1734        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1735
1736        // Now after opening every single application zip, make sure they
1737        // are all flushed.  Not really needed, but keeps things nice and
1738        // tidy.
1739        Runtime.getRuntime().gc();
1740    }
1741
1742    @Override
1743    public boolean isFirstBoot() {
1744        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1745    }
1746
1747    @Override
1748    public boolean isOnlyCoreApps() {
1749        return mOnlyCore;
1750    }
1751
1752    private String getRequiredVerifierLPr() {
1753        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1754        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1755                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1756
1757        String requiredVerifier = null;
1758
1759        final int N = receivers.size();
1760        for (int i = 0; i < N; i++) {
1761            final ResolveInfo info = receivers.get(i);
1762
1763            if (info.activityInfo == null) {
1764                continue;
1765            }
1766
1767            final String packageName = info.activityInfo.packageName;
1768
1769            final PackageSetting ps = mSettings.mPackages.get(packageName);
1770            if (ps == null) {
1771                continue;
1772            }
1773
1774            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1775            if (!gp.grantedPermissions
1776                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1777                continue;
1778            }
1779
1780            if (requiredVerifier != null) {
1781                throw new RuntimeException("There can be only one required verifier");
1782            }
1783
1784            requiredVerifier = packageName;
1785        }
1786
1787        return requiredVerifier;
1788    }
1789
1790    @Override
1791    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1792            throws RemoteException {
1793        try {
1794            return super.onTransact(code, data, reply, flags);
1795        } catch (RuntimeException e) {
1796            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1797                Slog.wtf(TAG, "Package Manager Crash", e);
1798            }
1799            throw e;
1800        }
1801    }
1802
1803    void cleanupInstallFailedPackage(PackageSetting ps) {
1804        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1805        removeDataDirsLI(ps.name);
1806        if (ps.codePath != null) {
1807            if (!ps.codePath.delete()) {
1808                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1809            }
1810        }
1811        if (ps.resourcePath != null) {
1812            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1813                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1814            }
1815        }
1816        mSettings.removePackageLPw(ps.name);
1817    }
1818
1819    void readPermissions(File libraryDir, boolean onlyFeatures) {
1820        // Read permissions from .../etc/permission directory.
1821        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1822            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1823            return;
1824        }
1825        if (!libraryDir.canRead()) {
1826            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1827            return;
1828        }
1829
1830        // Iterate over the files in the directory and scan .xml files
1831        for (File f : libraryDir.listFiles()) {
1832            // We'll read platform.xml last
1833            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1834                continue;
1835            }
1836
1837            if (!f.getPath().endsWith(".xml")) {
1838                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1839                continue;
1840            }
1841            if (!f.canRead()) {
1842                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1843                continue;
1844            }
1845
1846            readPermissionsFromXml(f, onlyFeatures);
1847        }
1848
1849        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1850        final File permFile = new File(Environment.getRootDirectory(),
1851                "etc/permissions/platform.xml");
1852        readPermissionsFromXml(permFile, onlyFeatures);
1853    }
1854
1855    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1856        FileReader permReader = null;
1857        try {
1858            permReader = new FileReader(permFile);
1859        } catch (FileNotFoundException e) {
1860            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1861            return;
1862        }
1863
1864        try {
1865            XmlPullParser parser = Xml.newPullParser();
1866            parser.setInput(permReader);
1867
1868            XmlUtils.beginDocument(parser, "permissions");
1869
1870            while (true) {
1871                XmlUtils.nextElement(parser);
1872                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1873                    break;
1874                }
1875
1876                String name = parser.getName();
1877                if ("group".equals(name) && !onlyFeatures) {
1878                    String gidStr = parser.getAttributeValue(null, "gid");
1879                    if (gidStr != null) {
1880                        int gid = Process.getGidForName(gidStr);
1881                        mGlobalGids = appendInt(mGlobalGids, gid);
1882                    } else {
1883                        Slog.w(TAG, "<group> without gid at "
1884                                + parser.getPositionDescription());
1885                    }
1886
1887                    XmlUtils.skipCurrentTag(parser);
1888                    continue;
1889                } else if ("permission".equals(name) && !onlyFeatures) {
1890                    String perm = parser.getAttributeValue(null, "name");
1891                    if (perm == null) {
1892                        Slog.w(TAG, "<permission> without name at "
1893                                + parser.getPositionDescription());
1894                        XmlUtils.skipCurrentTag(parser);
1895                        continue;
1896                    }
1897                    perm = perm.intern();
1898                    readPermission(parser, perm);
1899
1900                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1901                    String perm = parser.getAttributeValue(null, "name");
1902                    if (perm == null) {
1903                        Slog.w(TAG, "<assign-permission> without name at "
1904                                + parser.getPositionDescription());
1905                        XmlUtils.skipCurrentTag(parser);
1906                        continue;
1907                    }
1908                    String uidStr = parser.getAttributeValue(null, "uid");
1909                    if (uidStr == null) {
1910                        Slog.w(TAG, "<assign-permission> without uid at "
1911                                + parser.getPositionDescription());
1912                        XmlUtils.skipCurrentTag(parser);
1913                        continue;
1914                    }
1915                    int uid = Process.getUidForName(uidStr);
1916                    if (uid < 0) {
1917                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1918                                + uidStr + "\" at "
1919                                + parser.getPositionDescription());
1920                        XmlUtils.skipCurrentTag(parser);
1921                        continue;
1922                    }
1923                    perm = perm.intern();
1924                    HashSet<String> perms = mSystemPermissions.get(uid);
1925                    if (perms == null) {
1926                        perms = new HashSet<String>();
1927                        mSystemPermissions.put(uid, perms);
1928                    }
1929                    perms.add(perm);
1930                    XmlUtils.skipCurrentTag(parser);
1931
1932                } else if ("library".equals(name) && !onlyFeatures) {
1933                    String lname = parser.getAttributeValue(null, "name");
1934                    String lfile = parser.getAttributeValue(null, "file");
1935                    if (lname == null) {
1936                        Slog.w(TAG, "<library> without name at "
1937                                + parser.getPositionDescription());
1938                    } else if (lfile == null) {
1939                        Slog.w(TAG, "<library> without file at "
1940                                + parser.getPositionDescription());
1941                    } else {
1942                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1943                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1944                    }
1945                    XmlUtils.skipCurrentTag(parser);
1946                    continue;
1947
1948                } else if ("feature".equals(name)) {
1949                    String fname = parser.getAttributeValue(null, "name");
1950                    if (fname == null) {
1951                        Slog.w(TAG, "<feature> without name at "
1952                                + parser.getPositionDescription());
1953                    } else {
1954                        //Log.i(TAG, "Got feature " + fname);
1955                        FeatureInfo fi = new FeatureInfo();
1956                        fi.name = fname;
1957                        mAvailableFeatures.put(fname, fi);
1958                    }
1959                    XmlUtils.skipCurrentTag(parser);
1960                    continue;
1961
1962                } else {
1963                    XmlUtils.skipCurrentTag(parser);
1964                    continue;
1965                }
1966
1967            }
1968            permReader.close();
1969        } catch (XmlPullParserException e) {
1970            Slog.w(TAG, "Got execption parsing permissions.", e);
1971        } catch (IOException e) {
1972            Slog.w(TAG, "Got execption parsing permissions.", e);
1973        }
1974    }
1975
1976    void readPermission(XmlPullParser parser, String name)
1977            throws IOException, XmlPullParserException {
1978
1979        name = name.intern();
1980
1981        BasePermission bp = mSettings.mPermissions.get(name);
1982        if (bp == null) {
1983            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1984            mSettings.mPermissions.put(name, bp);
1985        }
1986        int outerDepth = parser.getDepth();
1987        int type;
1988        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1989               && (type != XmlPullParser.END_TAG
1990                       || parser.getDepth() > outerDepth)) {
1991            if (type == XmlPullParser.END_TAG
1992                    || type == XmlPullParser.TEXT) {
1993                continue;
1994            }
1995
1996            String tagName = parser.getName();
1997            if ("group".equals(tagName)) {
1998                String gidStr = parser.getAttributeValue(null, "gid");
1999                if (gidStr != null) {
2000                    int gid = Process.getGidForName(gidStr);
2001                    bp.gids = appendInt(bp.gids, gid);
2002                } else {
2003                    Slog.w(TAG, "<group> without gid at "
2004                            + parser.getPositionDescription());
2005                }
2006            }
2007            XmlUtils.skipCurrentTag(parser);
2008        }
2009    }
2010
2011    static int[] appendInts(int[] cur, int[] add) {
2012        if (add == null) return cur;
2013        if (cur == null) return add;
2014        final int N = add.length;
2015        for (int i=0; i<N; i++) {
2016            cur = appendInt(cur, add[i]);
2017        }
2018        return cur;
2019    }
2020
2021    static int[] removeInts(int[] cur, int[] rem) {
2022        if (rem == null) return cur;
2023        if (cur == null) return cur;
2024        final int N = rem.length;
2025        for (int i=0; i<N; i++) {
2026            cur = removeInt(cur, rem[i]);
2027        }
2028        return cur;
2029    }
2030
2031    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2032        if (!sUserManager.exists(userId)) return null;
2033        final PackageSetting ps = (PackageSetting) p.mExtras;
2034        if (ps == null) {
2035            return null;
2036        }
2037        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2038        final PackageUserState state = ps.readUserState(userId);
2039        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2040                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2041                state, userId);
2042    }
2043
2044    @Override
2045    public boolean isPackageAvailable(String packageName, int userId) {
2046        if (!sUserManager.exists(userId)) return false;
2047        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2048        synchronized (mPackages) {
2049            PackageParser.Package p = mPackages.get(packageName);
2050            if (p != null) {
2051                final PackageSetting ps = (PackageSetting) p.mExtras;
2052                if (ps != null) {
2053                    final PackageUserState state = ps.readUserState(userId);
2054                    if (state != null) {
2055                        return PackageParser.isAvailable(state);
2056                    }
2057                }
2058            }
2059        }
2060        return false;
2061    }
2062
2063    @Override
2064    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2065        if (!sUserManager.exists(userId)) return null;
2066        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2067        // reader
2068        synchronized (mPackages) {
2069            PackageParser.Package p = mPackages.get(packageName);
2070            if (DEBUG_PACKAGE_INFO)
2071                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2072            if (p != null) {
2073                return generatePackageInfo(p, flags, userId);
2074            }
2075            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2076                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2077            }
2078        }
2079        return null;
2080    }
2081
2082    @Override
2083    public String[] currentToCanonicalPackageNames(String[] names) {
2084        String[] out = new String[names.length];
2085        // reader
2086        synchronized (mPackages) {
2087            for (int i=names.length-1; i>=0; i--) {
2088                PackageSetting ps = mSettings.mPackages.get(names[i]);
2089                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2090            }
2091        }
2092        return out;
2093    }
2094
2095    @Override
2096    public String[] canonicalToCurrentPackageNames(String[] names) {
2097        String[] out = new String[names.length];
2098        // reader
2099        synchronized (mPackages) {
2100            for (int i=names.length-1; i>=0; i--) {
2101                String cur = mSettings.mRenamedPackages.get(names[i]);
2102                out[i] = cur != null ? cur : names[i];
2103            }
2104        }
2105        return out;
2106    }
2107
2108    @Override
2109    public int getPackageUid(String packageName, int userId) {
2110        if (!sUserManager.exists(userId)) return -1;
2111        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2112        // reader
2113        synchronized (mPackages) {
2114            PackageParser.Package p = mPackages.get(packageName);
2115            if(p != null) {
2116                return UserHandle.getUid(userId, p.applicationInfo.uid);
2117            }
2118            PackageSetting ps = mSettings.mPackages.get(packageName);
2119            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2120                return -1;
2121            }
2122            p = ps.pkg;
2123            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2124        }
2125    }
2126
2127    @Override
2128    public int[] getPackageGids(String packageName) {
2129        // reader
2130        synchronized (mPackages) {
2131            PackageParser.Package p = mPackages.get(packageName);
2132            if (DEBUG_PACKAGE_INFO)
2133                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2134            if (p != null) {
2135                final PackageSetting ps = (PackageSetting)p.mExtras;
2136                return ps.getGids();
2137            }
2138        }
2139        // stupid thing to indicate an error.
2140        return new int[0];
2141    }
2142
2143    static final PermissionInfo generatePermissionInfo(
2144            BasePermission bp, int flags) {
2145        if (bp.perm != null) {
2146            return PackageParser.generatePermissionInfo(bp.perm, flags);
2147        }
2148        PermissionInfo pi = new PermissionInfo();
2149        pi.name = bp.name;
2150        pi.packageName = bp.sourcePackage;
2151        pi.nonLocalizedLabel = bp.name;
2152        pi.protectionLevel = bp.protectionLevel;
2153        return pi;
2154    }
2155
2156    @Override
2157    public PermissionInfo getPermissionInfo(String name, int flags) {
2158        // reader
2159        synchronized (mPackages) {
2160            final BasePermission p = mSettings.mPermissions.get(name);
2161            if (p != null) {
2162                return generatePermissionInfo(p, flags);
2163            }
2164            return null;
2165        }
2166    }
2167
2168    @Override
2169    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2170        // reader
2171        synchronized (mPackages) {
2172            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2173            for (BasePermission p : mSettings.mPermissions.values()) {
2174                if (group == null) {
2175                    if (p.perm == null || p.perm.info.group == null) {
2176                        out.add(generatePermissionInfo(p, flags));
2177                    }
2178                } else {
2179                    if (p.perm != null && group.equals(p.perm.info.group)) {
2180                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2181                    }
2182                }
2183            }
2184
2185            if (out.size() > 0) {
2186                return out;
2187            }
2188            return mPermissionGroups.containsKey(group) ? out : null;
2189        }
2190    }
2191
2192    @Override
2193    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2194        // reader
2195        synchronized (mPackages) {
2196            return PackageParser.generatePermissionGroupInfo(
2197                    mPermissionGroups.get(name), flags);
2198        }
2199    }
2200
2201    @Override
2202    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2203        // reader
2204        synchronized (mPackages) {
2205            final int N = mPermissionGroups.size();
2206            ArrayList<PermissionGroupInfo> out
2207                    = new ArrayList<PermissionGroupInfo>(N);
2208            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2209                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2210            }
2211            return out;
2212        }
2213    }
2214
2215    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2216            int userId) {
2217        if (!sUserManager.exists(userId)) return null;
2218        PackageSetting ps = mSettings.mPackages.get(packageName);
2219        if (ps != null) {
2220            if (ps.pkg == null) {
2221                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2222                        flags, userId);
2223                if (pInfo != null) {
2224                    return pInfo.applicationInfo;
2225                }
2226                return null;
2227            }
2228            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2229                    ps.readUserState(userId), userId);
2230        }
2231        return null;
2232    }
2233
2234    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2235            int userId) {
2236        if (!sUserManager.exists(userId)) return null;
2237        PackageSetting ps = mSettings.mPackages.get(packageName);
2238        if (ps != null) {
2239            PackageParser.Package pkg = ps.pkg;
2240            if (pkg == null) {
2241                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2242                    return null;
2243                }
2244                // TODO: teach about reading split name
2245                pkg = new PackageParser.Package(packageName, null);
2246                pkg.applicationInfo.packageName = packageName;
2247                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2248                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2249                pkg.applicationInfo.sourceDir = ps.codePathString;
2250                pkg.applicationInfo.dataDir =
2251                        getDataPathForPackage(packageName, 0).getPath();
2252                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2253                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2254            }
2255            return generatePackageInfo(pkg, flags, userId);
2256        }
2257        return null;
2258    }
2259
2260    @Override
2261    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2262        if (!sUserManager.exists(userId)) return null;
2263        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2264        // writer
2265        synchronized (mPackages) {
2266            PackageParser.Package p = mPackages.get(packageName);
2267            if (DEBUG_PACKAGE_INFO) Log.v(
2268                    TAG, "getApplicationInfo " + packageName
2269                    + ": " + p);
2270            if (p != null) {
2271                PackageSetting ps = mSettings.mPackages.get(packageName);
2272                if (ps == null) return null;
2273                // Note: isEnabledLP() does not apply here - always return info
2274                return PackageParser.generateApplicationInfo(
2275                        p, flags, ps.readUserState(userId), userId);
2276            }
2277            if ("android".equals(packageName)||"system".equals(packageName)) {
2278                return mAndroidApplication;
2279            }
2280            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2281                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2282            }
2283        }
2284        return null;
2285    }
2286
2287
2288    @Override
2289    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2290        mContext.enforceCallingOrSelfPermission(
2291                android.Manifest.permission.CLEAR_APP_CACHE, null);
2292        // Queue up an async operation since clearing cache may take a little while.
2293        mHandler.post(new Runnable() {
2294            public void run() {
2295                mHandler.removeCallbacks(this);
2296                int retCode = -1;
2297                synchronized (mInstallLock) {
2298                    retCode = mInstaller.freeCache(freeStorageSize);
2299                    if (retCode < 0) {
2300                        Slog.w(TAG, "Couldn't clear application caches");
2301                    }
2302                }
2303                if (observer != null) {
2304                    try {
2305                        observer.onRemoveCompleted(null, (retCode >= 0));
2306                    } catch (RemoteException e) {
2307                        Slog.w(TAG, "RemoveException when invoking call back");
2308                    }
2309                }
2310            }
2311        });
2312    }
2313
2314    @Override
2315    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2316        mContext.enforceCallingOrSelfPermission(
2317                android.Manifest.permission.CLEAR_APP_CACHE, null);
2318        // Queue up an async operation since clearing cache may take a little while.
2319        mHandler.post(new Runnable() {
2320            public void run() {
2321                mHandler.removeCallbacks(this);
2322                int retCode = -1;
2323                synchronized (mInstallLock) {
2324                    retCode = mInstaller.freeCache(freeStorageSize);
2325                    if (retCode < 0) {
2326                        Slog.w(TAG, "Couldn't clear application caches");
2327                    }
2328                }
2329                if(pi != null) {
2330                    try {
2331                        // Callback via pending intent
2332                        int code = (retCode >= 0) ? 1 : 0;
2333                        pi.sendIntent(null, code, null,
2334                                null, null);
2335                    } catch (SendIntentException e1) {
2336                        Slog.i(TAG, "Failed to send pending intent");
2337                    }
2338                }
2339            }
2340        });
2341    }
2342
2343    void freeStorage(long freeStorageSize) throws IOException {
2344        synchronized (mInstallLock) {
2345            if (mInstaller.freeCache(freeStorageSize) < 0) {
2346                throw new IOException("Failed to free enough space");
2347            }
2348        }
2349    }
2350
2351    @Override
2352    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2353        if (!sUserManager.exists(userId)) return null;
2354        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2355        synchronized (mPackages) {
2356            PackageParser.Activity a = mActivities.mActivities.get(component);
2357
2358            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2359            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2360                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2361                if (ps == null) return null;
2362                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2363                        userId);
2364            }
2365            if (mResolveComponentName.equals(component)) {
2366                return mResolveActivity;
2367            }
2368        }
2369        return null;
2370    }
2371
2372    @Override
2373    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2374            String resolvedType) {
2375        synchronized (mPackages) {
2376            PackageParser.Activity a = mActivities.mActivities.get(component);
2377            if (a == null) {
2378                return false;
2379            }
2380            for (int i=0; i<a.intents.size(); i++) {
2381                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2382                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2383                    return true;
2384                }
2385            }
2386            return false;
2387        }
2388    }
2389
2390    @Override
2391    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2392        if (!sUserManager.exists(userId)) return null;
2393        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2394        synchronized (mPackages) {
2395            PackageParser.Activity a = mReceivers.mActivities.get(component);
2396            if (DEBUG_PACKAGE_INFO) Log.v(
2397                TAG, "getReceiverInfo " + component + ": " + a);
2398            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2399                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2400                if (ps == null) return null;
2401                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2402                        userId);
2403            }
2404        }
2405        return null;
2406    }
2407
2408    @Override
2409    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2410        if (!sUserManager.exists(userId)) return null;
2411        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2412        synchronized (mPackages) {
2413            PackageParser.Service s = mServices.mServices.get(component);
2414            if (DEBUG_PACKAGE_INFO) Log.v(
2415                TAG, "getServiceInfo " + component + ": " + s);
2416            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2417                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2418                if (ps == null) return null;
2419                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2420                        userId);
2421            }
2422        }
2423        return null;
2424    }
2425
2426    @Override
2427    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2428        if (!sUserManager.exists(userId)) return null;
2429        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2430        synchronized (mPackages) {
2431            PackageParser.Provider p = mProviders.mProviders.get(component);
2432            if (DEBUG_PACKAGE_INFO) Log.v(
2433                TAG, "getProviderInfo " + component + ": " + p);
2434            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2435                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2436                if (ps == null) return null;
2437                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2438                        userId);
2439            }
2440        }
2441        return null;
2442    }
2443
2444    @Override
2445    public String[] getSystemSharedLibraryNames() {
2446        Set<String> libSet;
2447        synchronized (mPackages) {
2448            libSet = mSharedLibraries.keySet();
2449            int size = libSet.size();
2450            if (size > 0) {
2451                String[] libs = new String[size];
2452                libSet.toArray(libs);
2453                return libs;
2454            }
2455        }
2456        return null;
2457    }
2458
2459    @Override
2460    public FeatureInfo[] getSystemAvailableFeatures() {
2461        Collection<FeatureInfo> featSet;
2462        synchronized (mPackages) {
2463            featSet = mAvailableFeatures.values();
2464            int size = featSet.size();
2465            if (size > 0) {
2466                FeatureInfo[] features = new FeatureInfo[size+1];
2467                featSet.toArray(features);
2468                FeatureInfo fi = new FeatureInfo();
2469                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2470                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2471                features[size] = fi;
2472                return features;
2473            }
2474        }
2475        return null;
2476    }
2477
2478    @Override
2479    public boolean hasSystemFeature(String name) {
2480        synchronized (mPackages) {
2481            return mAvailableFeatures.containsKey(name);
2482        }
2483    }
2484
2485    private void checkValidCaller(int uid, int userId) {
2486        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2487            return;
2488
2489        throw new SecurityException("Caller uid=" + uid
2490                + " is not privileged to communicate with user=" + userId);
2491    }
2492
2493    @Override
2494    public int checkPermission(String permName, String pkgName) {
2495        synchronized (mPackages) {
2496            PackageParser.Package p = mPackages.get(pkgName);
2497            if (p != null && p.mExtras != null) {
2498                PackageSetting ps = (PackageSetting)p.mExtras;
2499                if (ps.sharedUser != null) {
2500                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2501                        return PackageManager.PERMISSION_GRANTED;
2502                    }
2503                } else if (ps.grantedPermissions.contains(permName)) {
2504                    return PackageManager.PERMISSION_GRANTED;
2505                }
2506            }
2507        }
2508        return PackageManager.PERMISSION_DENIED;
2509    }
2510
2511    @Override
2512    public int checkUidPermission(String permName, int uid) {
2513        synchronized (mPackages) {
2514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2515            if (obj != null) {
2516                GrantedPermissions gp = (GrantedPermissions)obj;
2517                if (gp.grantedPermissions.contains(permName)) {
2518                    return PackageManager.PERMISSION_GRANTED;
2519                }
2520            } else {
2521                HashSet<String> perms = mSystemPermissions.get(uid);
2522                if (perms != null && perms.contains(permName)) {
2523                    return PackageManager.PERMISSION_GRANTED;
2524                }
2525            }
2526        }
2527        return PackageManager.PERMISSION_DENIED;
2528    }
2529
2530    /**
2531     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2532     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2533     * @param message the message to log on security exception
2534     */
2535    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2536            String message) {
2537        if (userId < 0) {
2538            throw new IllegalArgumentException("Invalid userId " + userId);
2539        }
2540        if (userId == UserHandle.getUserId(callingUid)) return;
2541        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2542            if (requireFullPermission) {
2543                mContext.enforceCallingOrSelfPermission(
2544                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2545            } else {
2546                try {
2547                    mContext.enforceCallingOrSelfPermission(
2548                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2549                } catch (SecurityException se) {
2550                    mContext.enforceCallingOrSelfPermission(
2551                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2552                }
2553            }
2554        }
2555    }
2556
2557    private BasePermission findPermissionTreeLP(String permName) {
2558        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2559            if (permName.startsWith(bp.name) &&
2560                    permName.length() > bp.name.length() &&
2561                    permName.charAt(bp.name.length()) == '.') {
2562                return bp;
2563            }
2564        }
2565        return null;
2566    }
2567
2568    private BasePermission checkPermissionTreeLP(String permName) {
2569        if (permName != null) {
2570            BasePermission bp = findPermissionTreeLP(permName);
2571            if (bp != null) {
2572                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2573                    return bp;
2574                }
2575                throw new SecurityException("Calling uid "
2576                        + Binder.getCallingUid()
2577                        + " is not allowed to add to permission tree "
2578                        + bp.name + " owned by uid " + bp.uid);
2579            }
2580        }
2581        throw new SecurityException("No permission tree found for " + permName);
2582    }
2583
2584    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2585        if (s1 == null) {
2586            return s2 == null;
2587        }
2588        if (s2 == null) {
2589            return false;
2590        }
2591        if (s1.getClass() != s2.getClass()) {
2592            return false;
2593        }
2594        return s1.equals(s2);
2595    }
2596
2597    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2598        if (pi1.icon != pi2.icon) return false;
2599        if (pi1.logo != pi2.logo) return false;
2600        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2601        if (!compareStrings(pi1.name, pi2.name)) return false;
2602        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2603        // We'll take care of setting this one.
2604        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2605        // These are not currently stored in settings.
2606        //if (!compareStrings(pi1.group, pi2.group)) return false;
2607        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2608        //if (pi1.labelRes != pi2.labelRes) return false;
2609        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2610        return true;
2611    }
2612
2613    int permissionInfoFootprint(PermissionInfo info) {
2614        int size = info.name.length();
2615        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2616        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2617        return size;
2618    }
2619
2620    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2621        int size = 0;
2622        for (BasePermission perm : mSettings.mPermissions.values()) {
2623            if (perm.uid == tree.uid) {
2624                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2625            }
2626        }
2627        return size;
2628    }
2629
2630    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2631        // We calculate the max size of permissions defined by this uid and throw
2632        // if that plus the size of 'info' would exceed our stated maximum.
2633        if (tree.uid != Process.SYSTEM_UID) {
2634            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2635            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2636                throw new SecurityException("Permission tree size cap exceeded");
2637            }
2638        }
2639    }
2640
2641    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2642        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2643            throw new SecurityException("Label must be specified in permission");
2644        }
2645        BasePermission tree = checkPermissionTreeLP(info.name);
2646        BasePermission bp = mSettings.mPermissions.get(info.name);
2647        boolean added = bp == null;
2648        boolean changed = true;
2649        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2650        if (added) {
2651            enforcePermissionCapLocked(info, tree);
2652            bp = new BasePermission(info.name, tree.sourcePackage,
2653                    BasePermission.TYPE_DYNAMIC);
2654        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2655            throw new SecurityException(
2656                    "Not allowed to modify non-dynamic permission "
2657                    + info.name);
2658        } else {
2659            if (bp.protectionLevel == fixedLevel
2660                    && bp.perm.owner.equals(tree.perm.owner)
2661                    && bp.uid == tree.uid
2662                    && comparePermissionInfos(bp.perm.info, info)) {
2663                changed = false;
2664            }
2665        }
2666        bp.protectionLevel = fixedLevel;
2667        info = new PermissionInfo(info);
2668        info.protectionLevel = fixedLevel;
2669        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2670        bp.perm.info.packageName = tree.perm.info.packageName;
2671        bp.uid = tree.uid;
2672        if (added) {
2673            mSettings.mPermissions.put(info.name, bp);
2674        }
2675        if (changed) {
2676            if (!async) {
2677                mSettings.writeLPr();
2678            } else {
2679                scheduleWriteSettingsLocked();
2680            }
2681        }
2682        return added;
2683    }
2684
2685    @Override
2686    public boolean addPermission(PermissionInfo info) {
2687        synchronized (mPackages) {
2688            return addPermissionLocked(info, false);
2689        }
2690    }
2691
2692    @Override
2693    public boolean addPermissionAsync(PermissionInfo info) {
2694        synchronized (mPackages) {
2695            return addPermissionLocked(info, true);
2696        }
2697    }
2698
2699    @Override
2700    public void removePermission(String name) {
2701        synchronized (mPackages) {
2702            checkPermissionTreeLP(name);
2703            BasePermission bp = mSettings.mPermissions.get(name);
2704            if (bp != null) {
2705                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2706                    throw new SecurityException(
2707                            "Not allowed to modify non-dynamic permission "
2708                            + name);
2709                }
2710                mSettings.mPermissions.remove(name);
2711                mSettings.writeLPr();
2712            }
2713        }
2714    }
2715
2716    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2717        int index = pkg.requestedPermissions.indexOf(bp.name);
2718        if (index == -1) {
2719            throw new SecurityException("Package " + pkg.packageName
2720                    + " has not requested permission " + bp.name);
2721        }
2722        boolean isNormal =
2723                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2724                        == PermissionInfo.PROTECTION_NORMAL);
2725        boolean isDangerous =
2726                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2727                        == PermissionInfo.PROTECTION_DANGEROUS);
2728        boolean isDevelopment =
2729                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2730
2731        if (!isNormal && !isDangerous && !isDevelopment) {
2732            throw new SecurityException("Permission " + bp.name
2733                    + " is not a changeable permission type");
2734        }
2735
2736        if (isNormal || isDangerous) {
2737            if (pkg.requestedPermissionsRequired.get(index)) {
2738                throw new SecurityException("Can't change " + bp.name
2739                        + ". It is required by the application");
2740            }
2741        }
2742    }
2743
2744    @Override
2745    public void grantPermission(String packageName, String permissionName) {
2746        mContext.enforceCallingOrSelfPermission(
2747                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2748        synchronized (mPackages) {
2749            final PackageParser.Package pkg = mPackages.get(packageName);
2750            if (pkg == null) {
2751                throw new IllegalArgumentException("Unknown package: " + packageName);
2752            }
2753            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2754            if (bp == null) {
2755                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2756            }
2757
2758            checkGrantRevokePermissions(pkg, bp);
2759
2760            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2761            if (ps == null) {
2762                return;
2763            }
2764            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2765            if (gp.grantedPermissions.add(permissionName)) {
2766                if (ps.haveGids) {
2767                    gp.gids = appendInts(gp.gids, bp.gids);
2768                }
2769                mSettings.writeLPr();
2770            }
2771        }
2772    }
2773
2774    @Override
2775    public void revokePermission(String packageName, String permissionName) {
2776        int changedAppId = -1;
2777
2778        synchronized (mPackages) {
2779            final PackageParser.Package pkg = mPackages.get(packageName);
2780            if (pkg == null) {
2781                throw new IllegalArgumentException("Unknown package: " + packageName);
2782            }
2783            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2784                mContext.enforceCallingOrSelfPermission(
2785                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2786            }
2787            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2788            if (bp == null) {
2789                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2790            }
2791
2792            checkGrantRevokePermissions(pkg, bp);
2793
2794            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2795            if (ps == null) {
2796                return;
2797            }
2798            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2799            if (gp.grantedPermissions.remove(permissionName)) {
2800                gp.grantedPermissions.remove(permissionName);
2801                if (ps.haveGids) {
2802                    gp.gids = removeInts(gp.gids, bp.gids);
2803                }
2804                mSettings.writeLPr();
2805                changedAppId = ps.appId;
2806            }
2807        }
2808
2809        if (changedAppId >= 0) {
2810            // We changed the perm on someone, kill its processes.
2811            IActivityManager am = ActivityManagerNative.getDefault();
2812            if (am != null) {
2813                final int callingUserId = UserHandle.getCallingUserId();
2814                final long ident = Binder.clearCallingIdentity();
2815                try {
2816                    //XXX we should only revoke for the calling user's app permissions,
2817                    // but for now we impact all users.
2818                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2819                    //        "revoke " + permissionName);
2820                    int[] users = sUserManager.getUserIds();
2821                    for (int user : users) {
2822                        am.killUid(UserHandle.getUid(user, changedAppId),
2823                                "revoke " + permissionName);
2824                    }
2825                } catch (RemoteException e) {
2826                } finally {
2827                    Binder.restoreCallingIdentity(ident);
2828                }
2829            }
2830        }
2831    }
2832
2833    @Override
2834    public boolean isProtectedBroadcast(String actionName) {
2835        synchronized (mPackages) {
2836            return mProtectedBroadcasts.contains(actionName);
2837        }
2838    }
2839
2840    @Override
2841    public int checkSignatures(String pkg1, String pkg2) {
2842        synchronized (mPackages) {
2843            final PackageParser.Package p1 = mPackages.get(pkg1);
2844            final PackageParser.Package p2 = mPackages.get(pkg2);
2845            if (p1 == null || p1.mExtras == null
2846                    || p2 == null || p2.mExtras == null) {
2847                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2848            }
2849            return compareSignatures(p1.mSignatures, p2.mSignatures);
2850        }
2851    }
2852
2853    @Override
2854    public int checkUidSignatures(int uid1, int uid2) {
2855        // Map to base uids.
2856        uid1 = UserHandle.getAppId(uid1);
2857        uid2 = UserHandle.getAppId(uid2);
2858        // reader
2859        synchronized (mPackages) {
2860            Signature[] s1;
2861            Signature[] s2;
2862            Object obj = mSettings.getUserIdLPr(uid1);
2863            if (obj != null) {
2864                if (obj instanceof SharedUserSetting) {
2865                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2866                } else if (obj instanceof PackageSetting) {
2867                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2868                } else {
2869                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2870                }
2871            } else {
2872                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2873            }
2874            obj = mSettings.getUserIdLPr(uid2);
2875            if (obj != null) {
2876                if (obj instanceof SharedUserSetting) {
2877                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2878                } else if (obj instanceof PackageSetting) {
2879                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2880                } else {
2881                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2882                }
2883            } else {
2884                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2885            }
2886            return compareSignatures(s1, s2);
2887        }
2888    }
2889
2890    /**
2891     * Compares two sets of signatures. Returns:
2892     * <br />
2893     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2894     * <br />
2895     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2896     * <br />
2897     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2898     * <br />
2899     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2900     * <br />
2901     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2902     */
2903    static int compareSignatures(Signature[] s1, Signature[] s2) {
2904        if (s1 == null) {
2905            return s2 == null
2906                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2907                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2908        }
2909
2910        if (s2 == null) {
2911            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2912        }
2913
2914        if (s1.length != s2.length) {
2915            return PackageManager.SIGNATURE_NO_MATCH;
2916        }
2917
2918        // Since both signature sets are of size 1, we can compare without HashSets.
2919        if (s1.length == 1) {
2920            return s1[0].equals(s2[0]) ?
2921                    PackageManager.SIGNATURE_MATCH :
2922                    PackageManager.SIGNATURE_NO_MATCH;
2923        }
2924
2925        HashSet<Signature> set1 = new HashSet<Signature>();
2926        for (Signature sig : s1) {
2927            set1.add(sig);
2928        }
2929        HashSet<Signature> set2 = new HashSet<Signature>();
2930        for (Signature sig : s2) {
2931            set2.add(sig);
2932        }
2933        // Make sure s2 contains all signatures in s1.
2934        if (set1.equals(set2)) {
2935            return PackageManager.SIGNATURE_MATCH;
2936        }
2937        return PackageManager.SIGNATURE_NO_MATCH;
2938    }
2939
2940    /**
2941     * If the database version for this type of package (internal storage or
2942     * external storage) is less than the version where package signatures
2943     * were updated, return true.
2944     */
2945    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2946        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2947                DatabaseVersion.SIGNATURE_END_ENTITY))
2948                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2949                        DatabaseVersion.SIGNATURE_END_ENTITY));
2950    }
2951
2952    /**
2953     * Used for backward compatibility to make sure any packages with
2954     * certificate chains get upgraded to the new style. {@code existingSigs}
2955     * will be in the old format (since they were stored on disk from before the
2956     * system upgrade) and {@code scannedSigs} will be in the newer format.
2957     */
2958    private int compareSignaturesCompat(PackageSignatures existingSigs,
2959            PackageParser.Package scannedPkg) {
2960        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2961            return PackageManager.SIGNATURE_NO_MATCH;
2962        }
2963
2964        HashSet<Signature> existingSet = new HashSet<Signature>();
2965        for (Signature sig : existingSigs.mSignatures) {
2966            existingSet.add(sig);
2967        }
2968        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2969        for (Signature sig : scannedPkg.mSignatures) {
2970            try {
2971                Signature[] chainSignatures = sig.getChainSignatures();
2972                for (Signature chainSig : chainSignatures) {
2973                    scannedCompatSet.add(chainSig);
2974                }
2975            } catch (CertificateEncodingException e) {
2976                scannedCompatSet.add(sig);
2977            }
2978        }
2979        /*
2980         * Make sure the expanded scanned set contains all signatures in the
2981         * existing one.
2982         */
2983        if (scannedCompatSet.equals(existingSet)) {
2984            // Migrate the old signatures to the new scheme.
2985            existingSigs.assignSignatures(scannedPkg.mSignatures);
2986            // The new KeySets will be re-added later in the scanning process.
2987            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2988            return PackageManager.SIGNATURE_MATCH;
2989        }
2990        return PackageManager.SIGNATURE_NO_MATCH;
2991    }
2992
2993    @Override
2994    public String[] getPackagesForUid(int uid) {
2995        uid = UserHandle.getAppId(uid);
2996        // reader
2997        synchronized (mPackages) {
2998            Object obj = mSettings.getUserIdLPr(uid);
2999            if (obj instanceof SharedUserSetting) {
3000                final SharedUserSetting sus = (SharedUserSetting) obj;
3001                final int N = sus.packages.size();
3002                final String[] res = new String[N];
3003                final Iterator<PackageSetting> it = sus.packages.iterator();
3004                int i = 0;
3005                while (it.hasNext()) {
3006                    res[i++] = it.next().name;
3007                }
3008                return res;
3009            } else if (obj instanceof PackageSetting) {
3010                final PackageSetting ps = (PackageSetting) obj;
3011                return new String[] { ps.name };
3012            }
3013        }
3014        return null;
3015    }
3016
3017    @Override
3018    public String getNameForUid(int uid) {
3019        // reader
3020        synchronized (mPackages) {
3021            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3022            if (obj instanceof SharedUserSetting) {
3023                final SharedUserSetting sus = (SharedUserSetting) obj;
3024                return sus.name + ":" + sus.userId;
3025            } else if (obj instanceof PackageSetting) {
3026                final PackageSetting ps = (PackageSetting) obj;
3027                return ps.name;
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public int getUidForSharedUser(String sharedUserName) {
3035        if(sharedUserName == null) {
3036            return -1;
3037        }
3038        // reader
3039        synchronized (mPackages) {
3040            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3041            if (suid == null) {
3042                return -1;
3043            }
3044            return suid.userId;
3045        }
3046    }
3047
3048    @Override
3049    public int getFlagsForUid(int uid) {
3050        synchronized (mPackages) {
3051            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3052            if (obj instanceof SharedUserSetting) {
3053                final SharedUserSetting sus = (SharedUserSetting) obj;
3054                return sus.pkgFlags;
3055            } else if (obj instanceof PackageSetting) {
3056                final PackageSetting ps = (PackageSetting) obj;
3057                return ps.pkgFlags;
3058            }
3059        }
3060        return 0;
3061    }
3062
3063    @Override
3064    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3065            int flags, int userId) {
3066        if (!sUserManager.exists(userId)) return null;
3067        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3068        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3069        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3070    }
3071
3072    @Override
3073    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3074            IntentFilter filter, int match, ComponentName activity) {
3075        final int userId = UserHandle.getCallingUserId();
3076        if (DEBUG_PREFERRED) {
3077            Log.v(TAG, "setLastChosenActivity intent=" + intent
3078                + " resolvedType=" + resolvedType
3079                + " flags=" + flags
3080                + " filter=" + filter
3081                + " match=" + match
3082                + " activity=" + activity);
3083            filter.dump(new PrintStreamPrinter(System.out), "    ");
3084        }
3085        intent.setComponent(null);
3086        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3087        // Find any earlier preferred or last chosen entries and nuke them
3088        findPreferredActivity(intent, resolvedType,
3089                flags, query, 0, false, true, false, userId);
3090        // Add the new activity as the last chosen for this filter
3091        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3092    }
3093
3094    @Override
3095    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3096        final int userId = UserHandle.getCallingUserId();
3097        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3098        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3099        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3100                false, false, false, userId);
3101    }
3102
3103    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3104            int flags, List<ResolveInfo> query, int userId) {
3105        if (query != null) {
3106            final int N = query.size();
3107            if (N == 1) {
3108                return query.get(0);
3109            } else if (N > 1) {
3110                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3111                // If there is more than one activity with the same priority,
3112                // then let the user decide between them.
3113                ResolveInfo r0 = query.get(0);
3114                ResolveInfo r1 = query.get(1);
3115                if (DEBUG_INTENT_MATCHING || debug) {
3116                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3117                            + r1.activityInfo.name + "=" + r1.priority);
3118                }
3119                // If the first activity has a higher priority, or a different
3120                // default, then it is always desireable to pick it.
3121                if (r0.priority != r1.priority
3122                        || r0.preferredOrder != r1.preferredOrder
3123                        || r0.isDefault != r1.isDefault) {
3124                    return query.get(0);
3125                }
3126                // If we have saved a preference for a preferred activity for
3127                // this Intent, use that.
3128                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3129                        flags, query, r0.priority, true, false, debug, userId);
3130                if (ri != null) {
3131                    return ri;
3132                }
3133                if (userId != 0) {
3134                    ri = new ResolveInfo(mResolveInfo);
3135                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3136                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3137                            ri.activityInfo.applicationInfo);
3138                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3139                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3140                    return ri;
3141                }
3142                return mResolveInfo;
3143            }
3144        }
3145        return null;
3146    }
3147
3148    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3149            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3150        final int N = query.size();
3151        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3152                .get(userId);
3153        // Get the list of persistent preferred activities that handle the intent
3154        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3155        List<PersistentPreferredActivity> pprefs = ppir != null
3156                ? ppir.queryIntent(intent, resolvedType,
3157                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3158                : null;
3159        if (pprefs != null && pprefs.size() > 0) {
3160            final int M = pprefs.size();
3161            for (int i=0; i<M; i++) {
3162                final PersistentPreferredActivity ppa = pprefs.get(i);
3163                if (DEBUG_PREFERRED || debug) {
3164                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3165                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3166                            + "\n  component=" + ppa.mComponent);
3167                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3168                }
3169                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3170                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3171                if (DEBUG_PREFERRED || debug) {
3172                    Slog.v(TAG, "Found persistent preferred activity:");
3173                    if (ai != null) {
3174                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3175                    } else {
3176                        Slog.v(TAG, "  null");
3177                    }
3178                }
3179                if (ai == null) {
3180                    // This previously registered persistent preferred activity
3181                    // component is no longer known. Ignore it and do NOT remove it.
3182                    continue;
3183                }
3184                for (int j=0; j<N; j++) {
3185                    final ResolveInfo ri = query.get(j);
3186                    if (!ri.activityInfo.applicationInfo.packageName
3187                            .equals(ai.applicationInfo.packageName)) {
3188                        continue;
3189                    }
3190                    if (!ri.activityInfo.name.equals(ai.name)) {
3191                        continue;
3192                    }
3193                    //  Found a persistent preference that can handle the intent.
3194                    if (DEBUG_PREFERRED || debug) {
3195                        Slog.v(TAG, "Returning persistent preferred activity: " +
3196                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3197                    }
3198                    return ri;
3199                }
3200            }
3201        }
3202        return null;
3203    }
3204
3205    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3206            List<ResolveInfo> query, int priority, boolean always,
3207            boolean removeMatches, boolean debug, int userId) {
3208        if (!sUserManager.exists(userId)) return null;
3209        // writer
3210        synchronized (mPackages) {
3211            if (intent.getSelector() != null) {
3212                intent = intent.getSelector();
3213            }
3214            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3215
3216            // Try to find a matching persistent preferred activity.
3217            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3218                    debug, userId);
3219
3220            // If a persistent preferred activity matched, use it.
3221            if (pri != null) {
3222                return pri;
3223            }
3224
3225            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3226            // Get the list of preferred activities that handle the intent
3227            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3228            List<PreferredActivity> prefs = pir != null
3229                    ? pir.queryIntent(intent, resolvedType,
3230                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3231                    : null;
3232            if (prefs != null && prefs.size() > 0) {
3233                // First figure out how good the original match set is.
3234                // We will only allow preferred activities that came
3235                // from the same match quality.
3236                int match = 0;
3237
3238                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3239
3240                final int N = query.size();
3241                for (int j=0; j<N; j++) {
3242                    final ResolveInfo ri = query.get(j);
3243                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3244                            + ": 0x" + Integer.toHexString(match));
3245                    if (ri.match > match) {
3246                        match = ri.match;
3247                    }
3248                }
3249
3250                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3251                        + Integer.toHexString(match));
3252
3253                match &= IntentFilter.MATCH_CATEGORY_MASK;
3254                final int M = prefs.size();
3255                for (int i=0; i<M; i++) {
3256                    final PreferredActivity pa = prefs.get(i);
3257                    if (DEBUG_PREFERRED || debug) {
3258                        Slog.v(TAG, "Checking PreferredActivity ds="
3259                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3260                                + "\n  component=" + pa.mPref.mComponent);
3261                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3262                    }
3263                    if (pa.mPref.mMatch != match) {
3264                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3265                                + Integer.toHexString(pa.mPref.mMatch));
3266                        continue;
3267                    }
3268                    // If it's not an "always" type preferred activity and that's what we're
3269                    // looking for, skip it.
3270                    if (always && !pa.mPref.mAlways) {
3271                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3272                        continue;
3273                    }
3274                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3275                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3276                    if (DEBUG_PREFERRED || debug) {
3277                        Slog.v(TAG, "Found preferred activity:");
3278                        if (ai != null) {
3279                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3280                        } else {
3281                            Slog.v(TAG, "  null");
3282                        }
3283                    }
3284                    if (ai == null) {
3285                        // This previously registered preferred activity
3286                        // component is no longer known.  Most likely an update
3287                        // to the app was installed and in the new version this
3288                        // component no longer exists.  Clean it up by removing
3289                        // it from the preferred activities list, and skip it.
3290                        Slog.w(TAG, "Removing dangling preferred activity: "
3291                                + pa.mPref.mComponent);
3292                        pir.removeFilter(pa);
3293                        continue;
3294                    }
3295                    for (int j=0; j<N; j++) {
3296                        final ResolveInfo ri = query.get(j);
3297                        if (!ri.activityInfo.applicationInfo.packageName
3298                                .equals(ai.applicationInfo.packageName)) {
3299                            continue;
3300                        }
3301                        if (!ri.activityInfo.name.equals(ai.name)) {
3302                            continue;
3303                        }
3304
3305                        if (removeMatches) {
3306                            pir.removeFilter(pa);
3307                            if (DEBUG_PREFERRED) {
3308                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3309                            }
3310                            break;
3311                        }
3312
3313                        // Okay we found a previously set preferred or last chosen app.
3314                        // If the result set is different from when this
3315                        // was created, we need to clear it and re-ask the
3316                        // user their preference, if we're looking for an "always" type entry.
3317                        if (always && !pa.mPref.sameSet(query, priority)) {
3318                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3319                                    + intent + " type " + resolvedType);
3320                            if (DEBUG_PREFERRED) {
3321                                Slog.v(TAG, "Removing preferred activity since set changed "
3322                                        + pa.mPref.mComponent);
3323                            }
3324                            pir.removeFilter(pa);
3325                            // Re-add the filter as a "last chosen" entry (!always)
3326                            PreferredActivity lastChosen = new PreferredActivity(
3327                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3328                            pir.addFilter(lastChosen);
3329                            mSettings.writePackageRestrictionsLPr(userId);
3330                            return null;
3331                        }
3332
3333                        // Yay! Either the set matched or we're looking for the last chosen
3334                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3335                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3336                        mSettings.writePackageRestrictionsLPr(userId);
3337                        return ri;
3338                    }
3339                }
3340            }
3341            mSettings.writePackageRestrictionsLPr(userId);
3342        }
3343        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3344        return null;
3345    }
3346
3347    /*
3348     * Returns if intent can be forwarded from the userId from to dest
3349     */
3350    @Override
3351    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3352            int targetUserId) {
3353        mContext.enforceCallingOrSelfPermission(
3354                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3355        List<CrossProfileIntentFilter> matches =
3356                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3357        if (matches != null) {
3358            int size = matches.size();
3359            for (int i = 0; i < size; i++) {
3360                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3361            }
3362        }
3363        return false;
3364    }
3365
3366    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3367            String resolvedType, int userId) {
3368        CrossProfileIntentResolver cpir = mSettings.mCrossProfileIntentResolvers.get(userId);
3369        if (cpir != null) {
3370            return cpir.queryIntent(intent, resolvedType, false, userId);
3371        }
3372        return null;
3373    }
3374
3375    @Override
3376    public List<ResolveInfo> queryIntentActivities(Intent intent,
3377            String resolvedType, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return Collections.emptyList();
3379        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3380        ComponentName comp = intent.getComponent();
3381        if (comp == null) {
3382            if (intent.getSelector() != null) {
3383                intent = intent.getSelector();
3384                comp = intent.getComponent();
3385            }
3386        }
3387
3388        if (comp != null) {
3389            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3390            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3391            if (ai != null) {
3392                final ResolveInfo ri = new ResolveInfo();
3393                ri.activityInfo = ai;
3394                list.add(ri);
3395            }
3396            return list;
3397        }
3398
3399        // reader
3400        synchronized (mPackages) {
3401            final String pkgName = intent.getPackage();
3402            if (pkgName == null) {
3403                List<ResolveInfo> result =
3404                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3405                // Checking if we can forward the intent to another user
3406                List<CrossProfileIntentFilter> cpifs =
3407                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3408                if (cpifs != null) {
3409                    CrossProfileIntentFilter crossProfileIntentFilterWithResult = null;
3410                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3411                    for (CrossProfileIntentFilter cpif : cpifs) {
3412                        int targetUserId = cpif.getTargetUserId();
3413                        // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3414                        // match the same an intent. For performance reasons, it is better not to
3415                        // run queryIntent twice for the same userId
3416                        if (!alreadyTriedUserIds.contains(targetUserId)) {
3417                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3418                                    resolvedType, flags, targetUserId);
3419                            if (resultUser != null) {
3420                                crossProfileIntentFilterWithResult = cpif;
3421                                // As soon as there is a match in another user, we add the
3422                                // intentForwarderActivity to the list of ResolveInfo.
3423                                break;
3424                            }
3425                            alreadyTriedUserIds.add(targetUserId);
3426                        }
3427                    }
3428                    if (crossProfileIntentFilterWithResult != null) {
3429                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3430                                crossProfileIntentFilterWithResult, userId);
3431                        result.add(forwardingResolveInfo);
3432                    }
3433                }
3434                return result;
3435            }
3436            final PackageParser.Package pkg = mPackages.get(pkgName);
3437            if (pkg != null) {
3438                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3439                        pkg.activities, userId);
3440            }
3441            return new ArrayList<ResolveInfo>();
3442        }
3443    }
3444
3445    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter cpif,
3446            int sourceUserId) {
3447        String className;
3448        int targetUserId = cpif.getTargetUserId();
3449        if (targetUserId == UserHandle.USER_OWNER) {
3450            className = FORWARD_INTENT_TO_USER_OWNER;
3451        } else {
3452            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3453        }
3454        ComponentName forwardingActivityComponentName = new ComponentName(
3455                mAndroidApplication.packageName, className);
3456        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3457                sourceUserId);
3458        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3459        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3460        forwardingResolveInfo.priority = 0;
3461        forwardingResolveInfo.preferredOrder = 0;
3462        forwardingResolveInfo.match = 0;
3463        forwardingResolveInfo.isDefault = true;
3464        forwardingResolveInfo.filter = cpif;
3465        return forwardingResolveInfo;
3466    }
3467
3468    @Override
3469    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3470            Intent[] specifics, String[] specificTypes, Intent intent,
3471            String resolvedType, int flags, int userId) {
3472        if (!sUserManager.exists(userId)) return Collections.emptyList();
3473        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3474                "query intent activity options");
3475        final String resultsAction = intent.getAction();
3476
3477        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3478                | PackageManager.GET_RESOLVED_FILTER, userId);
3479
3480        if (DEBUG_INTENT_MATCHING) {
3481            Log.v(TAG, "Query " + intent + ": " + results);
3482        }
3483
3484        int specificsPos = 0;
3485        int N;
3486
3487        // todo: note that the algorithm used here is O(N^2).  This
3488        // isn't a problem in our current environment, but if we start running
3489        // into situations where we have more than 5 or 10 matches then this
3490        // should probably be changed to something smarter...
3491
3492        // First we go through and resolve each of the specific items
3493        // that were supplied, taking care of removing any corresponding
3494        // duplicate items in the generic resolve list.
3495        if (specifics != null) {
3496            for (int i=0; i<specifics.length; i++) {
3497                final Intent sintent = specifics[i];
3498                if (sintent == null) {
3499                    continue;
3500                }
3501
3502                if (DEBUG_INTENT_MATCHING) {
3503                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3504                }
3505
3506                String action = sintent.getAction();
3507                if (resultsAction != null && resultsAction.equals(action)) {
3508                    // If this action was explicitly requested, then don't
3509                    // remove things that have it.
3510                    action = null;
3511                }
3512
3513                ResolveInfo ri = null;
3514                ActivityInfo ai = null;
3515
3516                ComponentName comp = sintent.getComponent();
3517                if (comp == null) {
3518                    ri = resolveIntent(
3519                        sintent,
3520                        specificTypes != null ? specificTypes[i] : null,
3521                            flags, userId);
3522                    if (ri == null) {
3523                        continue;
3524                    }
3525                    if (ri == mResolveInfo) {
3526                        // ACK!  Must do something better with this.
3527                    }
3528                    ai = ri.activityInfo;
3529                    comp = new ComponentName(ai.applicationInfo.packageName,
3530                            ai.name);
3531                } else {
3532                    ai = getActivityInfo(comp, flags, userId);
3533                    if (ai == null) {
3534                        continue;
3535                    }
3536                }
3537
3538                // Look for any generic query activities that are duplicates
3539                // of this specific one, and remove them from the results.
3540                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3541                N = results.size();
3542                int j;
3543                for (j=specificsPos; j<N; j++) {
3544                    ResolveInfo sri = results.get(j);
3545                    if ((sri.activityInfo.name.equals(comp.getClassName())
3546                            && sri.activityInfo.applicationInfo.packageName.equals(
3547                                    comp.getPackageName()))
3548                        || (action != null && sri.filter.matchAction(action))) {
3549                        results.remove(j);
3550                        if (DEBUG_INTENT_MATCHING) Log.v(
3551                            TAG, "Removing duplicate item from " + j
3552                            + " due to specific " + specificsPos);
3553                        if (ri == null) {
3554                            ri = sri;
3555                        }
3556                        j--;
3557                        N--;
3558                    }
3559                }
3560
3561                // Add this specific item to its proper place.
3562                if (ri == null) {
3563                    ri = new ResolveInfo();
3564                    ri.activityInfo = ai;
3565                }
3566                results.add(specificsPos, ri);
3567                ri.specificIndex = i;
3568                specificsPos++;
3569            }
3570        }
3571
3572        // Now we go through the remaining generic results and remove any
3573        // duplicate actions that are found here.
3574        N = results.size();
3575        for (int i=specificsPos; i<N-1; i++) {
3576            final ResolveInfo rii = results.get(i);
3577            if (rii.filter == null) {
3578                continue;
3579            }
3580
3581            // Iterate over all of the actions of this result's intent
3582            // filter...  typically this should be just one.
3583            final Iterator<String> it = rii.filter.actionsIterator();
3584            if (it == null) {
3585                continue;
3586            }
3587            while (it.hasNext()) {
3588                final String action = it.next();
3589                if (resultsAction != null && resultsAction.equals(action)) {
3590                    // If this action was explicitly requested, then don't
3591                    // remove things that have it.
3592                    continue;
3593                }
3594                for (int j=i+1; j<N; j++) {
3595                    final ResolveInfo rij = results.get(j);
3596                    if (rij.filter != null && rij.filter.hasAction(action)) {
3597                        results.remove(j);
3598                        if (DEBUG_INTENT_MATCHING) Log.v(
3599                            TAG, "Removing duplicate item from " + j
3600                            + " due to action " + action + " at " + i);
3601                        j--;
3602                        N--;
3603                    }
3604                }
3605            }
3606
3607            // If the caller didn't request filter information, drop it now
3608            // so we don't have to marshall/unmarshall it.
3609            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3610                rii.filter = null;
3611            }
3612        }
3613
3614        // Filter out the caller activity if so requested.
3615        if (caller != null) {
3616            N = results.size();
3617            for (int i=0; i<N; i++) {
3618                ActivityInfo ainfo = results.get(i).activityInfo;
3619                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3620                        && caller.getClassName().equals(ainfo.name)) {
3621                    results.remove(i);
3622                    break;
3623                }
3624            }
3625        }
3626
3627        // If the caller didn't request filter information,
3628        // drop them now so we don't have to
3629        // marshall/unmarshall it.
3630        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3631            N = results.size();
3632            for (int i=0; i<N; i++) {
3633                results.get(i).filter = null;
3634            }
3635        }
3636
3637        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3638        return results;
3639    }
3640
3641    @Override
3642    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3643            int userId) {
3644        if (!sUserManager.exists(userId)) return Collections.emptyList();
3645        ComponentName comp = intent.getComponent();
3646        if (comp == null) {
3647            if (intent.getSelector() != null) {
3648                intent = intent.getSelector();
3649                comp = intent.getComponent();
3650            }
3651        }
3652        if (comp != null) {
3653            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3654            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3655            if (ai != null) {
3656                ResolveInfo ri = new ResolveInfo();
3657                ri.activityInfo = ai;
3658                list.add(ri);
3659            }
3660            return list;
3661        }
3662
3663        // reader
3664        synchronized (mPackages) {
3665            String pkgName = intent.getPackage();
3666            if (pkgName == null) {
3667                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3668            }
3669            final PackageParser.Package pkg = mPackages.get(pkgName);
3670            if (pkg != null) {
3671                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3672                        userId);
3673            }
3674            return null;
3675        }
3676    }
3677
3678    @Override
3679    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3680        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3681        if (!sUserManager.exists(userId)) return null;
3682        if (query != null) {
3683            if (query.size() >= 1) {
3684                // If there is more than one service with the same priority,
3685                // just arbitrarily pick the first one.
3686                return query.get(0);
3687            }
3688        }
3689        return null;
3690    }
3691
3692    @Override
3693    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3694            int userId) {
3695        if (!sUserManager.exists(userId)) return Collections.emptyList();
3696        ComponentName comp = intent.getComponent();
3697        if (comp == null) {
3698            if (intent.getSelector() != null) {
3699                intent = intent.getSelector();
3700                comp = intent.getComponent();
3701            }
3702        }
3703        if (comp != null) {
3704            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3705            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3706            if (si != null) {
3707                final ResolveInfo ri = new ResolveInfo();
3708                ri.serviceInfo = si;
3709                list.add(ri);
3710            }
3711            return list;
3712        }
3713
3714        // reader
3715        synchronized (mPackages) {
3716            String pkgName = intent.getPackage();
3717            if (pkgName == null) {
3718                return mServices.queryIntent(intent, resolvedType, flags, userId);
3719            }
3720            final PackageParser.Package pkg = mPackages.get(pkgName);
3721            if (pkg != null) {
3722                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3723                        userId);
3724            }
3725            return null;
3726        }
3727    }
3728
3729    @Override
3730    public List<ResolveInfo> queryIntentContentProviders(
3731            Intent intent, String resolvedType, int flags, int userId) {
3732        if (!sUserManager.exists(userId)) return Collections.emptyList();
3733        ComponentName comp = intent.getComponent();
3734        if (comp == null) {
3735            if (intent.getSelector() != null) {
3736                intent = intent.getSelector();
3737                comp = intent.getComponent();
3738            }
3739        }
3740        if (comp != null) {
3741            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3742            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3743            if (pi != null) {
3744                final ResolveInfo ri = new ResolveInfo();
3745                ri.providerInfo = pi;
3746                list.add(ri);
3747            }
3748            return list;
3749        }
3750
3751        // reader
3752        synchronized (mPackages) {
3753            String pkgName = intent.getPackage();
3754            if (pkgName == null) {
3755                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3756            }
3757            final PackageParser.Package pkg = mPackages.get(pkgName);
3758            if (pkg != null) {
3759                return mProviders.queryIntentForPackage(
3760                        intent, resolvedType, flags, pkg.providers, userId);
3761            }
3762            return null;
3763        }
3764    }
3765
3766    @Override
3767    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3768        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3769
3770        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3771
3772        // writer
3773        synchronized (mPackages) {
3774            ArrayList<PackageInfo> list;
3775            if (listUninstalled) {
3776                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3777                for (PackageSetting ps : mSettings.mPackages.values()) {
3778                    PackageInfo pi;
3779                    if (ps.pkg != null) {
3780                        pi = generatePackageInfo(ps.pkg, flags, userId);
3781                    } else {
3782                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3783                    }
3784                    if (pi != null) {
3785                        list.add(pi);
3786                    }
3787                }
3788            } else {
3789                list = new ArrayList<PackageInfo>(mPackages.size());
3790                for (PackageParser.Package p : mPackages.values()) {
3791                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3792                    if (pi != null) {
3793                        list.add(pi);
3794                    }
3795                }
3796            }
3797
3798            return new ParceledListSlice<PackageInfo>(list);
3799        }
3800    }
3801
3802    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3803            String[] permissions, boolean[] tmp, int flags, int userId) {
3804        int numMatch = 0;
3805        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3806        for (int i=0; i<permissions.length; i++) {
3807            if (gp.grantedPermissions.contains(permissions[i])) {
3808                tmp[i] = true;
3809                numMatch++;
3810            } else {
3811                tmp[i] = false;
3812            }
3813        }
3814        if (numMatch == 0) {
3815            return;
3816        }
3817        PackageInfo pi;
3818        if (ps.pkg != null) {
3819            pi = generatePackageInfo(ps.pkg, flags, userId);
3820        } else {
3821            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3822        }
3823        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3824            if (numMatch == permissions.length) {
3825                pi.requestedPermissions = permissions;
3826            } else {
3827                pi.requestedPermissions = new String[numMatch];
3828                numMatch = 0;
3829                for (int i=0; i<permissions.length; i++) {
3830                    if (tmp[i]) {
3831                        pi.requestedPermissions[numMatch] = permissions[i];
3832                        numMatch++;
3833                    }
3834                }
3835            }
3836        }
3837        list.add(pi);
3838    }
3839
3840    @Override
3841    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3842            String[] permissions, int flags, int userId) {
3843        if (!sUserManager.exists(userId)) return null;
3844        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3845
3846        // writer
3847        synchronized (mPackages) {
3848            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3849            boolean[] tmpBools = new boolean[permissions.length];
3850            if (listUninstalled) {
3851                for (PackageSetting ps : mSettings.mPackages.values()) {
3852                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3853                }
3854            } else {
3855                for (PackageParser.Package pkg : mPackages.values()) {
3856                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3857                    if (ps != null) {
3858                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3859                                userId);
3860                    }
3861                }
3862            }
3863
3864            return new ParceledListSlice<PackageInfo>(list);
3865        }
3866    }
3867
3868    @Override
3869    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3870        if (!sUserManager.exists(userId)) return null;
3871        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3872
3873        // writer
3874        synchronized (mPackages) {
3875            ArrayList<ApplicationInfo> list;
3876            if (listUninstalled) {
3877                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3878                for (PackageSetting ps : mSettings.mPackages.values()) {
3879                    ApplicationInfo ai;
3880                    if (ps.pkg != null) {
3881                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3882                                ps.readUserState(userId), userId);
3883                    } else {
3884                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3885                    }
3886                    if (ai != null) {
3887                        list.add(ai);
3888                    }
3889                }
3890            } else {
3891                list = new ArrayList<ApplicationInfo>(mPackages.size());
3892                for (PackageParser.Package p : mPackages.values()) {
3893                    if (p.mExtras != null) {
3894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3895                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3896                        if (ai != null) {
3897                            list.add(ai);
3898                        }
3899                    }
3900                }
3901            }
3902
3903            return new ParceledListSlice<ApplicationInfo>(list);
3904        }
3905    }
3906
3907    public List<ApplicationInfo> getPersistentApplications(int flags) {
3908        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3909
3910        // reader
3911        synchronized (mPackages) {
3912            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3913            final int userId = UserHandle.getCallingUserId();
3914            while (i.hasNext()) {
3915                final PackageParser.Package p = i.next();
3916                if (p.applicationInfo != null
3917                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3918                        && (!mSafeMode || isSystemApp(p))) {
3919                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3920                    if (ps != null) {
3921                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3922                                ps.readUserState(userId), userId);
3923                        if (ai != null) {
3924                            finalList.add(ai);
3925                        }
3926                    }
3927                }
3928            }
3929        }
3930
3931        return finalList;
3932    }
3933
3934    @Override
3935    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3936        if (!sUserManager.exists(userId)) return null;
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3940            PackageSetting ps = provider != null
3941                    ? mSettings.mPackages.get(provider.owner.packageName)
3942                    : null;
3943            return ps != null
3944                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3945                    && (!mSafeMode || (provider.info.applicationInfo.flags
3946                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3947                    ? PackageParser.generateProviderInfo(provider, flags,
3948                            ps.readUserState(userId), userId)
3949                    : null;
3950        }
3951    }
3952
3953    /**
3954     * @deprecated
3955     */
3956    @Deprecated
3957    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3958        // reader
3959        synchronized (mPackages) {
3960            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3961                    .entrySet().iterator();
3962            final int userId = UserHandle.getCallingUserId();
3963            while (i.hasNext()) {
3964                Map.Entry<String, PackageParser.Provider> entry = i.next();
3965                PackageParser.Provider p = entry.getValue();
3966                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3967
3968                if (ps != null && p.syncable
3969                        && (!mSafeMode || (p.info.applicationInfo.flags
3970                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3971                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3972                            ps.readUserState(userId), userId);
3973                    if (info != null) {
3974                        outNames.add(entry.getKey());
3975                        outInfo.add(info);
3976                    }
3977                }
3978            }
3979        }
3980    }
3981
3982    @Override
3983    public List<ProviderInfo> queryContentProviders(String processName,
3984            int uid, int flags) {
3985        ArrayList<ProviderInfo> finalList = null;
3986        // reader
3987        synchronized (mPackages) {
3988            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3989            final int userId = processName != null ?
3990                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3991            while (i.hasNext()) {
3992                final PackageParser.Provider p = i.next();
3993                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3994                if (ps != null && p.info.authority != null
3995                        && (processName == null
3996                                || (p.info.processName.equals(processName)
3997                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3998                        && mSettings.isEnabledLPr(p.info, flags, userId)
3999                        && (!mSafeMode
4000                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4001                    if (finalList == null) {
4002                        finalList = new ArrayList<ProviderInfo>(3);
4003                    }
4004                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4005                            ps.readUserState(userId), userId);
4006                    if (info != null) {
4007                        finalList.add(info);
4008                    }
4009                }
4010            }
4011        }
4012
4013        if (finalList != null) {
4014            Collections.sort(finalList, mProviderInitOrderSorter);
4015        }
4016
4017        return finalList;
4018    }
4019
4020    @Override
4021    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4022            int flags) {
4023        // reader
4024        synchronized (mPackages) {
4025            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4026            return PackageParser.generateInstrumentationInfo(i, flags);
4027        }
4028    }
4029
4030    @Override
4031    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4032            int flags) {
4033        ArrayList<InstrumentationInfo> finalList =
4034            new ArrayList<InstrumentationInfo>();
4035
4036        // reader
4037        synchronized (mPackages) {
4038            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4039            while (i.hasNext()) {
4040                final PackageParser.Instrumentation p = i.next();
4041                if (targetPackage == null
4042                        || targetPackage.equals(p.info.targetPackage)) {
4043                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4044                            flags);
4045                    if (ii != null) {
4046                        finalList.add(ii);
4047                    }
4048                }
4049            }
4050        }
4051
4052        return finalList;
4053    }
4054
4055    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4056        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4057        if (overlays == null) {
4058            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4059            return;
4060        }
4061        for (PackageParser.Package opkg : overlays.values()) {
4062            // Not much to do if idmap fails: we already logged the error
4063            // and we certainly don't want to abort installation of pkg simply
4064            // because an overlay didn't fit properly. For these reasons,
4065            // ignore the return value of createIdmapForPackagePairLI.
4066            createIdmapForPackagePairLI(pkg, opkg);
4067        }
4068    }
4069
4070    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4071            PackageParser.Package opkg) {
4072        if (!opkg.mTrustedOverlay) {
4073            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4074                    opkg.mScanPath + ": overlay not trusted");
4075            return false;
4076        }
4077        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4078        if (overlaySet == null) {
4079            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4080                    opkg.mScanPath + " but target package has no known overlays");
4081            return false;
4082        }
4083        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4084        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4085            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4086            return false;
4087        }
4088        PackageParser.Package[] overlayArray =
4089            overlaySet.values().toArray(new PackageParser.Package[0]);
4090        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4091            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4092                return p1.mOverlayPriority - p2.mOverlayPriority;
4093            }
4094        };
4095        Arrays.sort(overlayArray, cmp);
4096
4097        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4098        int i = 0;
4099        for (PackageParser.Package p : overlayArray) {
4100            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4101        }
4102        return true;
4103    }
4104
4105    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4106        String[] files = dir.list();
4107        if (files == null) {
4108            Log.d(TAG, "No files in app dir " + dir);
4109            return;
4110        }
4111
4112        if (DEBUG_PACKAGE_SCANNING) {
4113            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4114                    + " flags=0x" + Integer.toHexString(flags));
4115        }
4116
4117        int i;
4118        for (i=0; i<files.length; i++) {
4119            File file = new File(dir, files[i]);
4120            if (!isPackageFilename(files[i])) {
4121                // Ignore entries which are not apk's
4122                continue;
4123            }
4124            PackageParser.Package pkg = scanPackageLI(file,
4125                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4126            // Don't mess around with apps in system partition.
4127            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4128                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4129                // Delete the apk
4130                Slog.w(TAG, "Cleaning up failed install of " + file);
4131                file.delete();
4132            }
4133        }
4134    }
4135
4136    private static File getSettingsProblemFile() {
4137        File dataDir = Environment.getDataDirectory();
4138        File systemDir = new File(dataDir, "system");
4139        File fname = new File(systemDir, "uiderrors.txt");
4140        return fname;
4141    }
4142
4143    static void reportSettingsProblem(int priority, String msg) {
4144        try {
4145            File fname = getSettingsProblemFile();
4146            FileOutputStream out = new FileOutputStream(fname, true);
4147            PrintWriter pw = new FastPrintWriter(out);
4148            SimpleDateFormat formatter = new SimpleDateFormat();
4149            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4150            pw.println(dateString + ": " + msg);
4151            pw.close();
4152            FileUtils.setPermissions(
4153                    fname.toString(),
4154                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4155                    -1, -1);
4156        } catch (java.io.IOException e) {
4157        }
4158        Slog.println(priority, TAG, msg);
4159    }
4160
4161    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4162            PackageParser.Package pkg, File srcFile, int parseFlags) {
4163        if (ps != null
4164                && ps.codePath.equals(srcFile)
4165                && ps.timeStamp == srcFile.lastModified()
4166                && !isCompatSignatureUpdateNeeded(pkg)) {
4167            if (ps.signatures.mSignatures != null
4168                    && ps.signatures.mSignatures.length != 0) {
4169                // Optimization: reuse the existing cached certificates
4170                // if the package appears to be unchanged.
4171                pkg.mSignatures = ps.signatures.mSignatures;
4172                return true;
4173            }
4174
4175            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4176        } else {
4177            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4178        }
4179
4180        if (!pp.collectCertificates(pkg, parseFlags)) {
4181            mLastScanError = pp.getParseError();
4182            return false;
4183        }
4184        return true;
4185    }
4186
4187    /*
4188     *  Scan a package and return the newly parsed package.
4189     *  Returns null in case of errors and the error code is stored in mLastScanError
4190     */
4191    private PackageParser.Package scanPackageLI(File scanFile,
4192            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4193        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4194        String scanPath = scanFile.getPath();
4195        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4196        parseFlags |= mDefParseFlags;
4197        PackageParser pp = new PackageParser(scanPath);
4198        pp.setSeparateProcesses(mSeparateProcesses);
4199        pp.setOnlyCoreApps(mOnlyCore);
4200        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4201                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4202
4203        if (pkg == null) {
4204            mLastScanError = pp.getParseError();
4205            return null;
4206        }
4207
4208        PackageSetting ps = null;
4209        PackageSetting updatedPkg;
4210        // reader
4211        synchronized (mPackages) {
4212            // Look to see if we already know about this package.
4213            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4214            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4215                // This package has been renamed to its original name.  Let's
4216                // use that.
4217                ps = mSettings.peekPackageLPr(oldName);
4218            }
4219            // If there was no original package, see one for the real package name.
4220            if (ps == null) {
4221                ps = mSettings.peekPackageLPr(pkg.packageName);
4222            }
4223            // Check to see if this package could be hiding/updating a system
4224            // package.  Must look for it either under the original or real
4225            // package name depending on our state.
4226            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4227            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4228        }
4229        boolean updatedPkgBetter = false;
4230        // First check if this is a system package that may involve an update
4231        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4232            if (ps != null && !ps.codePath.equals(scanFile)) {
4233                // The path has changed from what was last scanned...  check the
4234                // version of the new path against what we have stored to determine
4235                // what to do.
4236                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4237                if (pkg.mVersionCode < ps.versionCode) {
4238                    // The system package has been updated and the code path does not match
4239                    // Ignore entry. Skip it.
4240                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4241                            + " ignored: updated version " + ps.versionCode
4242                            + " better than this " + pkg.mVersionCode);
4243                    if (!updatedPkg.codePath.equals(scanFile)) {
4244                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4245                                + ps.name + " changing from " + updatedPkg.codePathString
4246                                + " to " + scanFile);
4247                        updatedPkg.codePath = scanFile;
4248                        updatedPkg.codePathString = scanFile.toString();
4249                        // This is the point at which we know that the system-disk APK
4250                        // for this package has moved during a reboot (e.g. due to an OTA),
4251                        // so we need to reevaluate it for privilege policy.
4252                        if (locationIsPrivileged(scanFile)) {
4253                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4254                        }
4255                    }
4256                    updatedPkg.pkg = pkg;
4257                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4258                    return null;
4259                } else {
4260                    // The current app on the system partition is better than
4261                    // what we have updated to on the data partition; switch
4262                    // back to the system partition version.
4263                    // At this point, its safely assumed that package installation for
4264                    // apps in system partition will go through. If not there won't be a working
4265                    // version of the app
4266                    // writer
4267                    synchronized (mPackages) {
4268                        // Just remove the loaded entries from package lists.
4269                        mPackages.remove(ps.name);
4270                    }
4271                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4272                            + "reverting from " + ps.codePathString
4273                            + ": new version " + pkg.mVersionCode
4274                            + " better than installed " + ps.versionCode);
4275
4276                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4277                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4278                            getAppInstructionSetFromSettings(ps));
4279                    synchronized (mInstallLock) {
4280                        args.cleanUpResourcesLI();
4281                    }
4282                    synchronized (mPackages) {
4283                        mSettings.enableSystemPackageLPw(ps.name);
4284                    }
4285                    updatedPkgBetter = true;
4286                }
4287            }
4288        }
4289
4290        if (updatedPkg != null) {
4291            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4292            // initially
4293            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4294
4295            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4296            // flag set initially
4297            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4298                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4299            }
4300        }
4301        // Verify certificates against what was last scanned
4302        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4303            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4304            return null;
4305        }
4306
4307        /*
4308         * A new system app appeared, but we already had a non-system one of the
4309         * same name installed earlier.
4310         */
4311        boolean shouldHideSystemApp = false;
4312        if (updatedPkg == null && ps != null
4313                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4314            /*
4315             * Check to make sure the signatures match first. If they don't,
4316             * wipe the installed application and its data.
4317             */
4318            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4319                    != PackageManager.SIGNATURE_MATCH) {
4320                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4321                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4322                ps = null;
4323            } else {
4324                /*
4325                 * If the newly-added system app is an older version than the
4326                 * already installed version, hide it. It will be scanned later
4327                 * and re-added like an update.
4328                 */
4329                if (pkg.mVersionCode < ps.versionCode) {
4330                    shouldHideSystemApp = true;
4331                } else {
4332                    /*
4333                     * The newly found system app is a newer version that the
4334                     * one previously installed. Simply remove the
4335                     * already-installed application and replace it with our own
4336                     * while keeping the application data.
4337                     */
4338                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4339                            + ps.codePathString + ": new version " + pkg.mVersionCode
4340                            + " better than installed " + ps.versionCode);
4341                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4342                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4343                            getAppInstructionSetFromSettings(ps));
4344                    synchronized (mInstallLock) {
4345                        args.cleanUpResourcesLI();
4346                    }
4347                }
4348            }
4349        }
4350
4351        // The apk is forward locked (not public) if its code and resources
4352        // are kept in different files. (except for app in either system or
4353        // vendor path).
4354        // TODO grab this value from PackageSettings
4355        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4356            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4357                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4358            }
4359        }
4360
4361        String codePath = null;
4362        String resPath = null;
4363        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4364            if (ps != null && ps.resourcePathString != null) {
4365                resPath = ps.resourcePathString;
4366            } else {
4367                // Should not happen at all. Just log an error.
4368                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4369            }
4370        } else {
4371            resPath = pkg.mScanPath;
4372        }
4373
4374        codePath = pkg.mScanPath;
4375        // Set application objects path explicitly.
4376        setApplicationInfoPaths(pkg, codePath, resPath);
4377        // Note that we invoke the following method only if we are about to unpack an application
4378        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4379                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4380
4381        /*
4382         * If the system app should be overridden by a previously installed
4383         * data, hide the system app now and let the /data/app scan pick it up
4384         * again.
4385         */
4386        if (shouldHideSystemApp) {
4387            synchronized (mPackages) {
4388                /*
4389                 * We have to grant systems permissions before we hide, because
4390                 * grantPermissions will assume the package update is trying to
4391                 * expand its permissions.
4392                 */
4393                grantPermissionsLPw(pkg, true);
4394                mSettings.disableSystemPackageLPw(pkg.packageName);
4395            }
4396        }
4397
4398        return scannedPkg;
4399    }
4400
4401    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4402            String destResPath) {
4403        pkg.mPath = pkg.mScanPath = destCodePath;
4404        pkg.applicationInfo.sourceDir = destCodePath;
4405        pkg.applicationInfo.publicSourceDir = destResPath;
4406    }
4407
4408    private static String fixProcessName(String defProcessName,
4409            String processName, int uid) {
4410        if (processName == null) {
4411            return defProcessName;
4412        }
4413        return processName;
4414    }
4415
4416    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4417        if (pkgSetting.signatures.mSignatures != null) {
4418            // Already existing package. Make sure signatures match
4419            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4420                    == PackageManager.SIGNATURE_MATCH;
4421            if (!match) {
4422                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4423                        == PackageManager.SIGNATURE_MATCH;
4424            }
4425            if (!match) {
4426                Slog.e(TAG, "Package " + pkg.packageName
4427                        + " signatures do not match the previously installed version; ignoring!");
4428                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4429                return false;
4430            }
4431        }
4432        // Check for shared user signatures
4433        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4434            // Already existing package. Make sure signatures match
4435            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4436                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4437            if (!match) {
4438                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4439                        == PackageManager.SIGNATURE_MATCH;
4440            }
4441            if (!match) {
4442                Slog.e(TAG, "Package " + pkg.packageName
4443                        + " has no signatures that match those in shared user "
4444                        + pkgSetting.sharedUser.name + "; ignoring!");
4445                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4446                return false;
4447            }
4448        }
4449        return true;
4450    }
4451
4452    /**
4453     * Enforces that only the system UID or root's UID can call a method exposed
4454     * via Binder.
4455     *
4456     * @param message used as message if SecurityException is thrown
4457     * @throws SecurityException if the caller is not system or root
4458     */
4459    private static final void enforceSystemOrRoot(String message) {
4460        final int uid = Binder.getCallingUid();
4461        if (uid != Process.SYSTEM_UID && uid != 0) {
4462            throw new SecurityException(message);
4463        }
4464    }
4465
4466    @Override
4467    public void performBootDexOpt() {
4468        enforceSystemOrRoot("Only the system can request dexopt be performed");
4469
4470        final HashSet<PackageParser.Package> pkgs;
4471        synchronized (mPackages) {
4472            pkgs = mDeferredDexOpt;
4473            mDeferredDexOpt = null;
4474        }
4475
4476        if (pkgs != null) {
4477            // Filter out packages that aren't recently used.
4478            //
4479            // The exception is first boot of a non-eng device, which
4480            // should do a full dexopt.
4481            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4482            if (eng || !isFirstBoot()) {
4483                // TODO: add a property to control this?
4484                long dexOptLRUThresholdInMinutes;
4485                if (eng) {
4486                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4487                } else {
4488                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4489                }
4490                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4491
4492                int total = pkgs.size();
4493                int skipped = 0;
4494                long now = System.currentTimeMillis();
4495                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4496                    PackageParser.Package pkg = i.next();
4497                    long then = pkg.mLastPackageUsageTimeInMills;
4498                    if (then + dexOptLRUThresholdInMills < now) {
4499                        if (DEBUG_DEXOPT) {
4500                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4501                                  ((then == 0) ? "never" : new Date(then)));
4502                        }
4503                        i.remove();
4504                        skipped++;
4505                    }
4506                }
4507                if (DEBUG_DEXOPT) {
4508                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4509                }
4510            }
4511
4512            int i = 0;
4513            for (PackageParser.Package pkg : pkgs) {
4514                i++;
4515                if (DEBUG_DEXOPT) {
4516                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4517                          + ": " + pkg.packageName);
4518                }
4519                if (!isFirstBoot()) {
4520                    try {
4521                        ActivityManagerNative.getDefault().showBootMessage(
4522                                mContext.getResources().getString(
4523                                        R.string.android_upgrading_apk,
4524                                        i, pkgs.size()), true);
4525                    } catch (RemoteException e) {
4526                    }
4527                }
4528                PackageParser.Package p = pkg;
4529                synchronized (mInstallLock) {
4530                    if (p.mDexOptNeeded) {
4531                        performDexOptLI(p, false /* force dex */, false /* defer */,
4532                                true /* include dependencies */);
4533                    }
4534                }
4535            }
4536        }
4537    }
4538
4539    @Override
4540    public boolean performDexOpt(String packageName) {
4541        enforceSystemOrRoot("Only the system can request dexopt be performed");
4542        return performDexOpt(packageName, true);
4543    }
4544
4545    public boolean performDexOpt(String packageName, boolean updateUsage) {
4546
4547        PackageParser.Package p;
4548        synchronized (mPackages) {
4549            p = mPackages.get(packageName);
4550            if (p == null) {
4551                return false;
4552            }
4553            if (updateUsage) {
4554                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4555            }
4556            mPackageUsage.write(false);
4557            if (!p.mDexOptNeeded) {
4558                return false;
4559            }
4560        }
4561
4562        synchronized (mInstallLock) {
4563            return performDexOptLI(p, false /* force dex */, false /* defer */,
4564                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4565        }
4566    }
4567
4568    public HashSet<String> getPackagesThatNeedDexOpt() {
4569        HashSet<String> pkgs = null;
4570        synchronized (mPackages) {
4571            for (PackageParser.Package p : mPackages.values()) {
4572                if (DEBUG_DEXOPT) {
4573                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4574                }
4575                if (!p.mDexOptNeeded) {
4576                    continue;
4577                }
4578                if (pkgs == null) {
4579                    pkgs = new HashSet<String>();
4580                }
4581                pkgs.add(p.packageName);
4582            }
4583        }
4584        return pkgs;
4585    }
4586
4587    public void shutdown() {
4588        mPackageUsage.write(true);
4589    }
4590
4591    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4592             boolean forceDex, boolean defer, HashSet<String> done) {
4593        for (int i=0; i<libs.size(); i++) {
4594            PackageParser.Package libPkg;
4595            String libName;
4596            synchronized (mPackages) {
4597                libName = libs.get(i);
4598                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4599                if (lib != null && lib.apk != null) {
4600                    libPkg = mPackages.get(lib.apk);
4601                } else {
4602                    libPkg = null;
4603                }
4604            }
4605            if (libPkg != null && !done.contains(libName)) {
4606                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4607            }
4608        }
4609    }
4610
4611    static final int DEX_OPT_SKIPPED = 0;
4612    static final int DEX_OPT_PERFORMED = 1;
4613    static final int DEX_OPT_DEFERRED = 2;
4614    static final int DEX_OPT_FAILED = -1;
4615
4616    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4617            boolean forceDex, boolean defer, HashSet<String> done) {
4618        final String instructionSet = instructionSetOverride != null ?
4619                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4620
4621        if (done != null) {
4622            done.add(pkg.packageName);
4623            if (pkg.usesLibraries != null) {
4624                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4625            }
4626            if (pkg.usesOptionalLibraries != null) {
4627                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4628            }
4629        }
4630
4631        boolean performed = false;
4632        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4633            String path = pkg.mScanPath;
4634            try {
4635                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4636                                                                                pkg.packageName,
4637                                                                                instructionSet,
4638                                                                                defer);
4639                // There are three basic cases here:
4640                // 1.) we need to dexopt, either because we are forced or it is needed
4641                // 2.) we are defering a needed dexopt
4642                // 3.) we are skipping an unneeded dexopt
4643                if (forceDex || (!defer && isDexOptNeededInternal)) {
4644                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4645                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4646                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4647                                                pkg.packageName, instructionSet);
4648                    // Note that we ran dexopt, since rerunning will
4649                    // probably just result in an error again.
4650                    pkg.mDexOptNeeded = false;
4651                    if (ret < 0) {
4652                        return DEX_OPT_FAILED;
4653                    }
4654                    return DEX_OPT_PERFORMED;
4655                }
4656                if (defer && isDexOptNeededInternal) {
4657                    if (mDeferredDexOpt == null) {
4658                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4659                    }
4660                    mDeferredDexOpt.add(pkg);
4661                    return DEX_OPT_DEFERRED;
4662                }
4663                pkg.mDexOptNeeded = false;
4664                return DEX_OPT_SKIPPED;
4665            } catch (FileNotFoundException e) {
4666                Slog.w(TAG, "Apk not found for dexopt: " + path);
4667                return DEX_OPT_FAILED;
4668            } catch (IOException e) {
4669                Slog.w(TAG, "IOException reading apk: " + path, e);
4670                return DEX_OPT_FAILED;
4671            } catch (StaleDexCacheError e) {
4672                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4673                return DEX_OPT_FAILED;
4674            } catch (Exception e) {
4675                Slog.w(TAG, "Exception when doing dexopt : ", e);
4676                return DEX_OPT_FAILED;
4677            }
4678        }
4679        return DEX_OPT_SKIPPED;
4680    }
4681
4682    private String getAppInstructionSet(ApplicationInfo info) {
4683        String instructionSet = getPreferredInstructionSet();
4684
4685        if (info.cpuAbi != null) {
4686            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4687        }
4688
4689        return instructionSet;
4690    }
4691
4692    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4693        String instructionSet = getPreferredInstructionSet();
4694
4695        if (ps.cpuAbiString != null) {
4696            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4697        }
4698
4699        return instructionSet;
4700    }
4701
4702    private static String getPreferredInstructionSet() {
4703        if (sPreferredInstructionSet == null) {
4704            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4705        }
4706
4707        return sPreferredInstructionSet;
4708    }
4709
4710    private static List<String> getAllInstructionSets() {
4711        final String[] allAbis = Build.SUPPORTED_ABIS;
4712        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4713
4714        for (String abi : allAbis) {
4715            final String instructionSet = VMRuntime.getInstructionSet(abi);
4716            if (!allInstructionSets.contains(instructionSet)) {
4717                allInstructionSets.add(instructionSet);
4718            }
4719        }
4720
4721        return allInstructionSets;
4722    }
4723
4724    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4725            boolean inclDependencies) {
4726        HashSet<String> done;
4727        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4728            done = new HashSet<String>();
4729            done.add(pkg.packageName);
4730        } else {
4731            done = null;
4732        }
4733        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4734    }
4735
4736    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4737        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4738            Slog.w(TAG, "Unable to update from " + oldPkg.name
4739                    + " to " + newPkg.packageName
4740                    + ": old package not in system partition");
4741            return false;
4742        } else if (mPackages.get(oldPkg.name) != null) {
4743            Slog.w(TAG, "Unable to update from " + oldPkg.name
4744                    + " to " + newPkg.packageName
4745                    + ": old package still exists");
4746            return false;
4747        }
4748        return true;
4749    }
4750
4751    File getDataPathForUser(int userId) {
4752        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4753    }
4754
4755    private File getDataPathForPackage(String packageName, int userId) {
4756        /*
4757         * Until we fully support multiple users, return the directory we
4758         * previously would have. The PackageManagerTests will need to be
4759         * revised when this is changed back..
4760         */
4761        if (userId == 0) {
4762            return new File(mAppDataDir, packageName);
4763        } else {
4764            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4765                + File.separator + packageName);
4766        }
4767    }
4768
4769    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4770        int[] users = sUserManager.getUserIds();
4771        int res = mInstaller.install(packageName, uid, uid, seinfo);
4772        if (res < 0) {
4773            return res;
4774        }
4775        for (int user : users) {
4776            if (user != 0) {
4777                res = mInstaller.createUserData(packageName,
4778                        UserHandle.getUid(user, uid), user, seinfo);
4779                if (res < 0) {
4780                    return res;
4781                }
4782            }
4783        }
4784        return res;
4785    }
4786
4787    private int removeDataDirsLI(String packageName) {
4788        int[] users = sUserManager.getUserIds();
4789        int res = 0;
4790        for (int user : users) {
4791            int resInner = mInstaller.remove(packageName, user);
4792            if (resInner < 0) {
4793                res = resInner;
4794            }
4795        }
4796
4797        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4798        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4799        if (!nativeLibraryFile.delete()) {
4800            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4801        }
4802
4803        return res;
4804    }
4805
4806    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4807            PackageParser.Package changingLib) {
4808        if (file.path != null) {
4809            usesLibraryFiles.add(file.path);
4810            return;
4811        }
4812        PackageParser.Package p = mPackages.get(file.apk);
4813        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4814            // If we are doing this while in the middle of updating a library apk,
4815            // then we need to make sure to use that new apk for determining the
4816            // dependencies here.  (We haven't yet finished committing the new apk
4817            // to the package manager state.)
4818            if (p == null || p.packageName.equals(changingLib.packageName)) {
4819                p = changingLib;
4820            }
4821        }
4822        if (p != null) {
4823            usesLibraryFiles.add(p.mPath);
4824        }
4825    }
4826
4827    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4828            PackageParser.Package changingLib) {
4829        // We might be upgrading from a version of the platform that did not
4830        // provide per-package native library directories for system apps.
4831        // Fix that up here.
4832        if (isSystemApp(pkg)) {
4833            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4834            setInternalAppNativeLibraryPath(pkg, ps);
4835        }
4836
4837        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4838            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4839            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4840            for (int i=0; i<N; i++) {
4841                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4842                if (file == null) {
4843                    Slog.e(TAG, "Package " + pkg.packageName
4844                            + " requires unavailable shared library "
4845                            + pkg.usesLibraries.get(i) + "; failing!");
4846                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4847                    return false;
4848                }
4849                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4850            }
4851            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4852            for (int i=0; i<N; i++) {
4853                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4854                if (file == null) {
4855                    Slog.w(TAG, "Package " + pkg.packageName
4856                            + " desires unavailable shared library "
4857                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4858                } else {
4859                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4860                }
4861            }
4862            N = usesLibraryFiles.size();
4863            if (N > 0) {
4864                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4865            } else {
4866                pkg.usesLibraryFiles = null;
4867            }
4868        }
4869        return true;
4870    }
4871
4872    private static boolean hasString(List<String> list, List<String> which) {
4873        if (list == null) {
4874            return false;
4875        }
4876        for (int i=list.size()-1; i>=0; i--) {
4877            for (int j=which.size()-1; j>=0; j--) {
4878                if (which.get(j).equals(list.get(i))) {
4879                    return true;
4880                }
4881            }
4882        }
4883        return false;
4884    }
4885
4886    private void updateAllSharedLibrariesLPw() {
4887        for (PackageParser.Package pkg : mPackages.values()) {
4888            updateSharedLibrariesLPw(pkg, null);
4889        }
4890    }
4891
4892    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4893            PackageParser.Package changingPkg) {
4894        ArrayList<PackageParser.Package> res = null;
4895        for (PackageParser.Package pkg : mPackages.values()) {
4896            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4897                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4898                if (res == null) {
4899                    res = new ArrayList<PackageParser.Package>();
4900                }
4901                res.add(pkg);
4902                updateSharedLibrariesLPw(pkg, changingPkg);
4903            }
4904        }
4905        return res;
4906    }
4907
4908    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4909            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4910        File scanFile = new File(pkg.mScanPath);
4911        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4912                pkg.applicationInfo.publicSourceDir == null) {
4913            // Bail out. The resource and code paths haven't been set.
4914            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4915            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4916            return null;
4917        }
4918
4919        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4920            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4921        }
4922
4923        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4924            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4925        }
4926
4927        if (mCustomResolverComponentName != null &&
4928                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4929            setUpCustomResolverActivity(pkg);
4930        }
4931
4932        if (pkg.packageName.equals("android")) {
4933            synchronized (mPackages) {
4934                if (mAndroidApplication != null) {
4935                    Slog.w(TAG, "*************************************************");
4936                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4937                    Slog.w(TAG, " file=" + scanFile);
4938                    Slog.w(TAG, "*************************************************");
4939                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4940                    return null;
4941                }
4942
4943                // Set up information for our fall-back user intent resolution activity.
4944                mPlatformPackage = pkg;
4945                pkg.mVersionCode = mSdkVersion;
4946                mAndroidApplication = pkg.applicationInfo;
4947
4948                if (!mResolverReplaced) {
4949                    mResolveActivity.applicationInfo = mAndroidApplication;
4950                    mResolveActivity.name = ResolverActivity.class.getName();
4951                    mResolveActivity.packageName = mAndroidApplication.packageName;
4952                    mResolveActivity.processName = "system:ui";
4953                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4954                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4955                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4956                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4957                    mResolveActivity.exported = true;
4958                    mResolveActivity.enabled = true;
4959                    mResolveInfo.activityInfo = mResolveActivity;
4960                    mResolveInfo.priority = 0;
4961                    mResolveInfo.preferredOrder = 0;
4962                    mResolveInfo.match = 0;
4963                    mResolveComponentName = new ComponentName(
4964                            mAndroidApplication.packageName, mResolveActivity.name);
4965                }
4966            }
4967        }
4968
4969        if (DEBUG_PACKAGE_SCANNING) {
4970            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4971                Log.d(TAG, "Scanning package " + pkg.packageName);
4972        }
4973
4974        if (mPackages.containsKey(pkg.packageName)
4975                || mSharedLibraries.containsKey(pkg.packageName)) {
4976            Slog.w(TAG, "Application package " + pkg.packageName
4977                    + " already installed.  Skipping duplicate.");
4978            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4979            return null;
4980        }
4981
4982        // Initialize package source and resource directories
4983        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4984        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4985
4986        SharedUserSetting suid = null;
4987        PackageSetting pkgSetting = null;
4988
4989        if (!isSystemApp(pkg)) {
4990            // Only system apps can use these features.
4991            pkg.mOriginalPackages = null;
4992            pkg.mRealPackage = null;
4993            pkg.mAdoptPermissions = null;
4994        }
4995
4996        // writer
4997        synchronized (mPackages) {
4998            if (pkg.mSharedUserId != null) {
4999                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5000                if (suid == null) {
5001                    Slog.w(TAG, "Creating application package " + pkg.packageName
5002                            + " for shared user failed");
5003                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5004                    return null;
5005                }
5006                if (DEBUG_PACKAGE_SCANNING) {
5007                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5008                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5009                                + "): packages=" + suid.packages);
5010                }
5011            }
5012
5013            // Check if we are renaming from an original package name.
5014            PackageSetting origPackage = null;
5015            String realName = null;
5016            if (pkg.mOriginalPackages != null) {
5017                // This package may need to be renamed to a previously
5018                // installed name.  Let's check on that...
5019                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5020                if (pkg.mOriginalPackages.contains(renamed)) {
5021                    // This package had originally been installed as the
5022                    // original name, and we have already taken care of
5023                    // transitioning to the new one.  Just update the new
5024                    // one to continue using the old name.
5025                    realName = pkg.mRealPackage;
5026                    if (!pkg.packageName.equals(renamed)) {
5027                        // Callers into this function may have already taken
5028                        // care of renaming the package; only do it here if
5029                        // it is not already done.
5030                        pkg.setPackageName(renamed);
5031                    }
5032
5033                } else {
5034                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5035                        if ((origPackage = mSettings.peekPackageLPr(
5036                                pkg.mOriginalPackages.get(i))) != null) {
5037                            // We do have the package already installed under its
5038                            // original name...  should we use it?
5039                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5040                                // New package is not compatible with original.
5041                                origPackage = null;
5042                                continue;
5043                            } else if (origPackage.sharedUser != null) {
5044                                // Make sure uid is compatible between packages.
5045                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5046                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5047                                            + " to " + pkg.packageName + ": old uid "
5048                                            + origPackage.sharedUser.name
5049                                            + " differs from " + pkg.mSharedUserId);
5050                                    origPackage = null;
5051                                    continue;
5052                                }
5053                            } else {
5054                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5055                                        + pkg.packageName + " to old name " + origPackage.name);
5056                            }
5057                            break;
5058                        }
5059                    }
5060                }
5061            }
5062
5063            if (mTransferedPackages.contains(pkg.packageName)) {
5064                Slog.w(TAG, "Package " + pkg.packageName
5065                        + " was transferred to another, but its .apk remains");
5066            }
5067
5068            // Just create the setting, don't add it yet. For already existing packages
5069            // the PkgSetting exists already and doesn't have to be created.
5070            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5071                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5072                    pkg.applicationInfo.cpuAbi,
5073                    pkg.applicationInfo.flags, user, false);
5074            if (pkgSetting == null) {
5075                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5076                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5077                return null;
5078            }
5079
5080            if (pkgSetting.origPackage != null) {
5081                // If we are first transitioning from an original package,
5082                // fix up the new package's name now.  We need to do this after
5083                // looking up the package under its new name, so getPackageLP
5084                // can take care of fiddling things correctly.
5085                pkg.setPackageName(origPackage.name);
5086
5087                // File a report about this.
5088                String msg = "New package " + pkgSetting.realName
5089                        + " renamed to replace old package " + pkgSetting.name;
5090                reportSettingsProblem(Log.WARN, msg);
5091
5092                // Make a note of it.
5093                mTransferedPackages.add(origPackage.name);
5094
5095                // No longer need to retain this.
5096                pkgSetting.origPackage = null;
5097            }
5098
5099            if (realName != null) {
5100                // Make a note of it.
5101                mTransferedPackages.add(pkg.packageName);
5102            }
5103
5104            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5105                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5106            }
5107
5108            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5109                // Check all shared libraries and map to their actual file path.
5110                // We only do this here for apps not on a system dir, because those
5111                // are the only ones that can fail an install due to this.  We
5112                // will take care of the system apps by updating all of their
5113                // library paths after the scan is done.
5114                if (!updateSharedLibrariesLPw(pkg, null)) {
5115                    return null;
5116                }
5117            }
5118
5119            if (mFoundPolicyFile) {
5120                SELinuxMMAC.assignSeinfoValue(pkg);
5121            }
5122
5123            pkg.applicationInfo.uid = pkgSetting.appId;
5124            pkg.mExtras = pkgSetting;
5125
5126            if (!verifySignaturesLP(pkgSetting, pkg)) {
5127                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5128                    return null;
5129                }
5130                // The signature has changed, but this package is in the system
5131                // image...  let's recover!
5132                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5133                // However...  if this package is part of a shared user, but it
5134                // doesn't match the signature of the shared user, let's fail.
5135                // What this means is that you can't change the signatures
5136                // associated with an overall shared user, which doesn't seem all
5137                // that unreasonable.
5138                if (pkgSetting.sharedUser != null) {
5139                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5140                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5141                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5142                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5143                        return null;
5144                    }
5145                }
5146                // File a report about this.
5147                String msg = "System package " + pkg.packageName
5148                        + " signature changed; retaining data.";
5149                reportSettingsProblem(Log.WARN, msg);
5150            }
5151
5152            // Verify that this new package doesn't have any content providers
5153            // that conflict with existing packages.  Only do this if the
5154            // package isn't already installed, since we don't want to break
5155            // things that are installed.
5156            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5157                final int N = pkg.providers.size();
5158                int i;
5159                for (i=0; i<N; i++) {
5160                    PackageParser.Provider p = pkg.providers.get(i);
5161                    if (p.info.authority != null) {
5162                        String names[] = p.info.authority.split(";");
5163                        for (int j = 0; j < names.length; j++) {
5164                            if (mProvidersByAuthority.containsKey(names[j])) {
5165                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5166                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5167                                        " (in package " + pkg.applicationInfo.packageName +
5168                                        ") is already used by "
5169                                        + ((other != null && other.getComponentName() != null)
5170                                                ? other.getComponentName().getPackageName() : "?"));
5171                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5172                                return null;
5173                            }
5174                        }
5175                    }
5176                }
5177            }
5178
5179            if (pkg.mAdoptPermissions != null) {
5180                // This package wants to adopt ownership of permissions from
5181                // another package.
5182                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5183                    final String origName = pkg.mAdoptPermissions.get(i);
5184                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5185                    if (orig != null) {
5186                        if (verifyPackageUpdateLPr(orig, pkg)) {
5187                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5188                                    + pkg.packageName);
5189                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5190                        }
5191                    }
5192                }
5193            }
5194        }
5195
5196        final String pkgName = pkg.packageName;
5197
5198        final long scanFileTime = scanFile.lastModified();
5199        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5200        pkg.applicationInfo.processName = fixProcessName(
5201                pkg.applicationInfo.packageName,
5202                pkg.applicationInfo.processName,
5203                pkg.applicationInfo.uid);
5204
5205        File dataPath;
5206        if (mPlatformPackage == pkg) {
5207            // The system package is special.
5208            dataPath = new File (Environment.getDataDirectory(), "system");
5209            pkg.applicationInfo.dataDir = dataPath.getPath();
5210        } else {
5211            // This is a normal package, need to make its data directory.
5212            dataPath = getDataPathForPackage(pkg.packageName, 0);
5213
5214            boolean uidError = false;
5215
5216            if (dataPath.exists()) {
5217                int currentUid = 0;
5218                try {
5219                    StructStat stat = Os.stat(dataPath.getPath());
5220                    currentUid = stat.st_uid;
5221                } catch (ErrnoException e) {
5222                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5223                }
5224
5225                // If we have mismatched owners for the data path, we have a problem.
5226                if (currentUid != pkg.applicationInfo.uid) {
5227                    boolean recovered = false;
5228                    if (currentUid == 0) {
5229                        // The directory somehow became owned by root.  Wow.
5230                        // This is probably because the system was stopped while
5231                        // installd was in the middle of messing with its libs
5232                        // directory.  Ask installd to fix that.
5233                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5234                                pkg.applicationInfo.uid);
5235                        if (ret >= 0) {
5236                            recovered = true;
5237                            String msg = "Package " + pkg.packageName
5238                                    + " unexpectedly changed to uid 0; recovered to " +
5239                                    + pkg.applicationInfo.uid;
5240                            reportSettingsProblem(Log.WARN, msg);
5241                        }
5242                    }
5243                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5244                            || (scanMode&SCAN_BOOTING) != 0)) {
5245                        // If this is a system app, we can at least delete its
5246                        // current data so the application will still work.
5247                        int ret = removeDataDirsLI(pkgName);
5248                        if (ret >= 0) {
5249                            // TODO: Kill the processes first
5250                            // Old data gone!
5251                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5252                                    ? "System package " : "Third party package ";
5253                            String msg = prefix + pkg.packageName
5254                                    + " has changed from uid: "
5255                                    + currentUid + " to "
5256                                    + pkg.applicationInfo.uid + "; old data erased";
5257                            reportSettingsProblem(Log.WARN, msg);
5258                            recovered = true;
5259
5260                            // And now re-install the app.
5261                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5262                                                   pkg.applicationInfo.seinfo);
5263                            if (ret == -1) {
5264                                // Ack should not happen!
5265                                msg = prefix + pkg.packageName
5266                                        + " could not have data directory re-created after delete.";
5267                                reportSettingsProblem(Log.WARN, msg);
5268                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5269                                return null;
5270                            }
5271                        }
5272                        if (!recovered) {
5273                            mHasSystemUidErrors = true;
5274                        }
5275                    } else if (!recovered) {
5276                        // If we allow this install to proceed, we will be broken.
5277                        // Abort, abort!
5278                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5279                        return null;
5280                    }
5281                    if (!recovered) {
5282                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5283                            + pkg.applicationInfo.uid + "/fs_"
5284                            + currentUid;
5285                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5286                        String msg = "Package " + pkg.packageName
5287                                + " has mismatched uid: "
5288                                + currentUid + " on disk, "
5289                                + pkg.applicationInfo.uid + " in settings";
5290                        // writer
5291                        synchronized (mPackages) {
5292                            mSettings.mReadMessages.append(msg);
5293                            mSettings.mReadMessages.append('\n');
5294                            uidError = true;
5295                            if (!pkgSetting.uidError) {
5296                                reportSettingsProblem(Log.ERROR, msg);
5297                            }
5298                        }
5299                    }
5300                }
5301                pkg.applicationInfo.dataDir = dataPath.getPath();
5302                if (mShouldRestoreconData) {
5303                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5304                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5305                                pkg.applicationInfo.uid);
5306                }
5307            } else {
5308                if (DEBUG_PACKAGE_SCANNING) {
5309                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5310                        Log.v(TAG, "Want this data dir: " + dataPath);
5311                }
5312                //invoke installer to do the actual installation
5313                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5314                                           pkg.applicationInfo.seinfo);
5315                if (ret < 0) {
5316                    // Error from installer
5317                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5318                    return null;
5319                }
5320
5321                if (dataPath.exists()) {
5322                    pkg.applicationInfo.dataDir = dataPath.getPath();
5323                } else {
5324                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5325                    pkg.applicationInfo.dataDir = null;
5326                }
5327            }
5328
5329            /*
5330             * Set the data dir to the default "/data/data/<package name>/lib"
5331             * if we got here without anyone telling us different (e.g., apps
5332             * stored on SD card have their native libraries stored in the ASEC
5333             * container with the APK).
5334             *
5335             * This happens during an upgrade from a package settings file that
5336             * doesn't have a native library path attribute at all.
5337             */
5338            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5339                if (pkgSetting.nativeLibraryPathString == null) {
5340                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5341                } else {
5342                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5343                }
5344            }
5345            pkgSetting.uidError = uidError;
5346        }
5347
5348        String path = scanFile.getPath();
5349        /* Note: We don't want to unpack the native binaries for
5350         *        system applications, unless they have been updated
5351         *        (the binaries are already under /system/lib).
5352         *        Also, don't unpack libs for apps on the external card
5353         *        since they should have their libraries in the ASEC
5354         *        container already.
5355         *
5356         *        In other words, we're going to unpack the binaries
5357         *        only for non-system apps and system app upgrades.
5358         */
5359        if (pkg.applicationInfo.nativeLibraryDir != null) {
5360            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5361            try {
5362                // Enable gross and lame hacks for apps that are built with old
5363                // SDK tools. We must scan their APKs for renderscript bitcode and
5364                // not launch them if it's present. Don't bother checking on devices
5365                // that don't have 64 bit support.
5366                String[] abiList = Build.SUPPORTED_ABIS;
5367                boolean hasLegacyRenderscriptBitcode = false;
5368                if (abiOverride != null) {
5369                    abiList = new String[] { abiOverride };
5370                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5371                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5372                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5373                    hasLegacyRenderscriptBitcode = true;
5374                }
5375
5376                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5377                final String dataPathString = dataPath.getCanonicalPath();
5378
5379                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5380                    /*
5381                     * Upgrading from a previous version of the OS sometimes
5382                     * leaves native libraries in the /data/data/<app>/lib
5383                     * directory for system apps even when they shouldn't be.
5384                     * Recent changes in the JNI library search path
5385                     * necessitates we remove those to match previous behavior.
5386                     */
5387                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5388                        Log.i(TAG, "removed obsolete native libraries for system package "
5389                                + path);
5390                    }
5391                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5392                        pkg.applicationInfo.cpuAbi = abiList[0];
5393                        pkgSetting.cpuAbiString = abiList[0];
5394                    } else {
5395                        setInternalAppAbi(pkg, pkgSetting);
5396                    }
5397                } else {
5398                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5399                        /*
5400                        * Update native library dir if it starts with
5401                        * /data/data
5402                        */
5403                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5404                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5405                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5406                        }
5407
5408                        try {
5409                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5410                                    nativeLibraryDir, abiList);
5411                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5412                                Slog.e(TAG, "Unable to copy native libraries");
5413                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5414                                return null;
5415                            }
5416
5417                            // We've successfully copied native libraries across, so we make a
5418                            // note of what ABI we're using
5419                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5420                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5421                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5422                                pkg.applicationInfo.cpuAbi = abiList[0];
5423                            } else {
5424                                pkg.applicationInfo.cpuAbi = null;
5425                            }
5426                        } catch (IOException e) {
5427                            Slog.e(TAG, "Unable to copy native libraries", e);
5428                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5429                            return null;
5430                        }
5431                    } else {
5432                        // We don't have to copy the shared libraries if we're in the ASEC container
5433                        // but we still need to scan the file to figure out what ABI the app needs.
5434                        //
5435                        // TODO: This duplicates work done in the default container service. It's possible
5436                        // to clean this up but we'll need to change the interface between this service
5437                        // and IMediaContainerService (but doing so will spread this logic out, rather
5438                        // than centralizing it).
5439                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5440                        if (abi >= 0) {
5441                            pkg.applicationInfo.cpuAbi = abiList[abi];
5442                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5443                            // Note that (non upgraded) system apps will not have any native
5444                            // libraries bundled in their APK, but we're guaranteed not to be
5445                            // such an app at this point.
5446                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5447                                pkg.applicationInfo.cpuAbi = abiList[0];
5448                            } else {
5449                                pkg.applicationInfo.cpuAbi = null;
5450                            }
5451                        } else {
5452                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5453                            return null;
5454                        }
5455                    }
5456
5457                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5458                    final int[] userIds = sUserManager.getUserIds();
5459                    synchronized (mInstallLock) {
5460                        for (int userId : userIds) {
5461                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5462                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5463                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5464                                        + ")");
5465                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5466                                return null;
5467                            }
5468                        }
5469                    }
5470                }
5471
5472                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5473            } catch (IOException ioe) {
5474                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5475            } finally {
5476                handle.close();
5477            }
5478        }
5479        pkg.mScanPath = path;
5480
5481        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5482            // We don't do this here during boot because we can do it all
5483            // at once after scanning all existing packages.
5484            //
5485            // We also do this *before* we perform dexopt on this package, so that
5486            // we can avoid redundant dexopts, and also to make sure we've got the
5487            // code and package path correct.
5488            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5489                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5490                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5491                return null;
5492            }
5493        }
5494
5495        if ((scanMode&SCAN_NO_DEX) == 0) {
5496            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5497                    == DEX_OPT_FAILED) {
5498                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5499                    removeDataDirsLI(pkg.packageName);
5500                }
5501
5502                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5503                return null;
5504            }
5505        }
5506
5507        if (mFactoryTest && pkg.requestedPermissions.contains(
5508                android.Manifest.permission.FACTORY_TEST)) {
5509            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5510        }
5511
5512        ArrayList<PackageParser.Package> clientLibPkgs = null;
5513
5514        // writer
5515        synchronized (mPackages) {
5516            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5517                // Only system apps can add new shared libraries.
5518                if (pkg.libraryNames != null) {
5519                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5520                        String name = pkg.libraryNames.get(i);
5521                        boolean allowed = false;
5522                        if (isUpdatedSystemApp(pkg)) {
5523                            // New library entries can only be added through the
5524                            // system image.  This is important to get rid of a lot
5525                            // of nasty edge cases: for example if we allowed a non-
5526                            // system update of the app to add a library, then uninstalling
5527                            // the update would make the library go away, and assumptions
5528                            // we made such as through app install filtering would now
5529                            // have allowed apps on the device which aren't compatible
5530                            // with it.  Better to just have the restriction here, be
5531                            // conservative, and create many fewer cases that can negatively
5532                            // impact the user experience.
5533                            final PackageSetting sysPs = mSettings
5534                                    .getDisabledSystemPkgLPr(pkg.packageName);
5535                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5536                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5537                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5538                                        allowed = true;
5539                                        allowed = true;
5540                                        break;
5541                                    }
5542                                }
5543                            }
5544                        } else {
5545                            allowed = true;
5546                        }
5547                        if (allowed) {
5548                            if (!mSharedLibraries.containsKey(name)) {
5549                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5550                            } else if (!name.equals(pkg.packageName)) {
5551                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5552                                        + name + " already exists; skipping");
5553                            }
5554                        } else {
5555                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5556                                    + name + " that is not declared on system image; skipping");
5557                        }
5558                    }
5559                    if ((scanMode&SCAN_BOOTING) == 0) {
5560                        // If we are not booting, we need to update any applications
5561                        // that are clients of our shared library.  If we are booting,
5562                        // this will all be done once the scan is complete.
5563                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5564                    }
5565                }
5566            }
5567        }
5568
5569        // We also need to dexopt any apps that are dependent on this library.  Note that
5570        // if these fail, we should abort the install since installing the library will
5571        // result in some apps being broken.
5572        if (clientLibPkgs != null) {
5573            if ((scanMode&SCAN_NO_DEX) == 0) {
5574                for (int i=0; i<clientLibPkgs.size(); i++) {
5575                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5576                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5577                            == DEX_OPT_FAILED) {
5578                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5579                            removeDataDirsLI(pkg.packageName);
5580                        }
5581
5582                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5583                        return null;
5584                    }
5585                }
5586            }
5587        }
5588
5589        // Request the ActivityManager to kill the process(only for existing packages)
5590        // so that we do not end up in a confused state while the user is still using the older
5591        // version of the application while the new one gets installed.
5592        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5593            // If the package lives in an asec, tell everyone that the container is going
5594            // away so they can clean up any references to its resources (which would prevent
5595            // vold from being able to unmount the asec)
5596            if (isForwardLocked(pkg) || isExternal(pkg)) {
5597                if (DEBUG_INSTALL) {
5598                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5599                }
5600                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5601                final ArrayList<String> pkgList = new ArrayList<String>(1);
5602                pkgList.add(pkg.applicationInfo.packageName);
5603                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5604            }
5605
5606            // Post the request that it be killed now that the going-away broadcast is en route
5607            killApplication(pkg.applicationInfo.packageName,
5608                        pkg.applicationInfo.uid, "update pkg");
5609        }
5610
5611        // Also need to kill any apps that are dependent on the library.
5612        if (clientLibPkgs != null) {
5613            for (int i=0; i<clientLibPkgs.size(); i++) {
5614                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5615                killApplication(clientPkg.applicationInfo.packageName,
5616                        clientPkg.applicationInfo.uid, "update lib");
5617            }
5618        }
5619
5620        // writer
5621        synchronized (mPackages) {
5622            // We don't expect installation to fail beyond this point,
5623            if ((scanMode&SCAN_MONITOR) != 0) {
5624                mAppDirs.put(pkg.mPath, pkg);
5625            }
5626            // Add the new setting to mSettings
5627            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5628            // Add the new setting to mPackages
5629            mPackages.put(pkg.applicationInfo.packageName, pkg);
5630            // Make sure we don't accidentally delete its data.
5631            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5632            while (iter.hasNext()) {
5633                PackageCleanItem item = iter.next();
5634                if (pkgName.equals(item.packageName)) {
5635                    iter.remove();
5636                }
5637            }
5638
5639            // Take care of first install / last update times.
5640            if (currentTime != 0) {
5641                if (pkgSetting.firstInstallTime == 0) {
5642                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5643                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5644                    pkgSetting.lastUpdateTime = currentTime;
5645                }
5646            } else if (pkgSetting.firstInstallTime == 0) {
5647                // We need *something*.  Take time time stamp of the file.
5648                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5649            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5650                if (scanFileTime != pkgSetting.timeStamp) {
5651                    // A package on the system image has changed; consider this
5652                    // to be an update.
5653                    pkgSetting.lastUpdateTime = scanFileTime;
5654                }
5655            }
5656
5657            // Add the package's KeySets to the global KeySetManager
5658            KeySetManager ksm = mSettings.mKeySetManager;
5659            try {
5660                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5661                if (pkg.mKeySetMapping != null) {
5662                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5663                        if (entry.getValue() != null) {
5664                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5665                                entry.getValue(), entry.getKey());
5666                        }
5667                    }
5668                }
5669            } catch (NullPointerException e) {
5670                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5671            } catch (IllegalArgumentException e) {
5672                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5673            }
5674
5675            int N = pkg.providers.size();
5676            StringBuilder r = null;
5677            int i;
5678            for (i=0; i<N; i++) {
5679                PackageParser.Provider p = pkg.providers.get(i);
5680                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5681                        p.info.processName, pkg.applicationInfo.uid);
5682                mProviders.addProvider(p);
5683                p.syncable = p.info.isSyncable;
5684                if (p.info.authority != null) {
5685                    String names[] = p.info.authority.split(";");
5686                    p.info.authority = null;
5687                    for (int j = 0; j < names.length; j++) {
5688                        if (j == 1 && p.syncable) {
5689                            // We only want the first authority for a provider to possibly be
5690                            // syncable, so if we already added this provider using a different
5691                            // authority clear the syncable flag. We copy the provider before
5692                            // changing it because the mProviders object contains a reference
5693                            // to a provider that we don't want to change.
5694                            // Only do this for the second authority since the resulting provider
5695                            // object can be the same for all future authorities for this provider.
5696                            p = new PackageParser.Provider(p);
5697                            p.syncable = false;
5698                        }
5699                        if (!mProvidersByAuthority.containsKey(names[j])) {
5700                            mProvidersByAuthority.put(names[j], p);
5701                            if (p.info.authority == null) {
5702                                p.info.authority = names[j];
5703                            } else {
5704                                p.info.authority = p.info.authority + ";" + names[j];
5705                            }
5706                            if (DEBUG_PACKAGE_SCANNING) {
5707                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5708                                    Log.d(TAG, "Registered content provider: " + names[j]
5709                                            + ", className = " + p.info.name + ", isSyncable = "
5710                                            + p.info.isSyncable);
5711                            }
5712                        } else {
5713                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5714                            Slog.w(TAG, "Skipping provider name " + names[j] +
5715                                    " (in package " + pkg.applicationInfo.packageName +
5716                                    "): name already used by "
5717                                    + ((other != null && other.getComponentName() != null)
5718                                            ? other.getComponentName().getPackageName() : "?"));
5719                        }
5720                    }
5721                }
5722                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5723                    if (r == null) {
5724                        r = new StringBuilder(256);
5725                    } else {
5726                        r.append(' ');
5727                    }
5728                    r.append(p.info.name);
5729                }
5730            }
5731            if (r != null) {
5732                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5733            }
5734
5735            N = pkg.services.size();
5736            r = null;
5737            for (i=0; i<N; i++) {
5738                PackageParser.Service s = pkg.services.get(i);
5739                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5740                        s.info.processName, pkg.applicationInfo.uid);
5741                mServices.addService(s);
5742                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5743                    if (r == null) {
5744                        r = new StringBuilder(256);
5745                    } else {
5746                        r.append(' ');
5747                    }
5748                    r.append(s.info.name);
5749                }
5750            }
5751            if (r != null) {
5752                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5753            }
5754
5755            N = pkg.receivers.size();
5756            r = null;
5757            for (i=0; i<N; i++) {
5758                PackageParser.Activity a = pkg.receivers.get(i);
5759                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5760                        a.info.processName, pkg.applicationInfo.uid);
5761                mReceivers.addActivity(a, "receiver");
5762                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5763                    if (r == null) {
5764                        r = new StringBuilder(256);
5765                    } else {
5766                        r.append(' ');
5767                    }
5768                    r.append(a.info.name);
5769                }
5770            }
5771            if (r != null) {
5772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5773            }
5774
5775            N = pkg.activities.size();
5776            r = null;
5777            for (i=0; i<N; i++) {
5778                PackageParser.Activity a = pkg.activities.get(i);
5779                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5780                        a.info.processName, pkg.applicationInfo.uid);
5781                mActivities.addActivity(a, "activity");
5782                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5783                    if (r == null) {
5784                        r = new StringBuilder(256);
5785                    } else {
5786                        r.append(' ');
5787                    }
5788                    r.append(a.info.name);
5789                }
5790            }
5791            if (r != null) {
5792                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5793            }
5794
5795            N = pkg.permissionGroups.size();
5796            r = null;
5797            for (i=0; i<N; i++) {
5798                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5799                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5800                if (cur == null) {
5801                    mPermissionGroups.put(pg.info.name, pg);
5802                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5803                        if (r == null) {
5804                            r = new StringBuilder(256);
5805                        } else {
5806                            r.append(' ');
5807                        }
5808                        r.append(pg.info.name);
5809                    }
5810                } else {
5811                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5812                            + pg.info.packageName + " ignored: original from "
5813                            + cur.info.packageName);
5814                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5815                        if (r == null) {
5816                            r = new StringBuilder(256);
5817                        } else {
5818                            r.append(' ');
5819                        }
5820                        r.append("DUP:");
5821                        r.append(pg.info.name);
5822                    }
5823                }
5824            }
5825            if (r != null) {
5826                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5827            }
5828
5829            N = pkg.permissions.size();
5830            r = null;
5831            for (i=0; i<N; i++) {
5832                PackageParser.Permission p = pkg.permissions.get(i);
5833                HashMap<String, BasePermission> permissionMap =
5834                        p.tree ? mSettings.mPermissionTrees
5835                        : mSettings.mPermissions;
5836                p.group = mPermissionGroups.get(p.info.group);
5837                if (p.info.group == null || p.group != null) {
5838                    BasePermission bp = permissionMap.get(p.info.name);
5839                    if (bp == null) {
5840                        bp = new BasePermission(p.info.name, p.info.packageName,
5841                                BasePermission.TYPE_NORMAL);
5842                        permissionMap.put(p.info.name, bp);
5843                    }
5844                    if (bp.perm == null) {
5845                        if (bp.sourcePackage != null
5846                                && !bp.sourcePackage.equals(p.info.packageName)) {
5847                            // If this is a permission that was formerly defined by a non-system
5848                            // app, but is now defined by a system app (following an upgrade),
5849                            // discard the previous declaration and consider the system's to be
5850                            // canonical.
5851                            if (isSystemApp(p.owner)) {
5852                                String msg = "New decl " + p.owner + " of permission  "
5853                                        + p.info.name + " is system";
5854                                reportSettingsProblem(Log.WARN, msg);
5855                                bp.sourcePackage = null;
5856                            }
5857                        }
5858                        if (bp.sourcePackage == null
5859                                || bp.sourcePackage.equals(p.info.packageName)) {
5860                            BasePermission tree = findPermissionTreeLP(p.info.name);
5861                            if (tree == null
5862                                    || tree.sourcePackage.equals(p.info.packageName)) {
5863                                bp.packageSetting = pkgSetting;
5864                                bp.perm = p;
5865                                bp.uid = pkg.applicationInfo.uid;
5866                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5867                                    if (r == null) {
5868                                        r = new StringBuilder(256);
5869                                    } else {
5870                                        r.append(' ');
5871                                    }
5872                                    r.append(p.info.name);
5873                                }
5874                            } else {
5875                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5876                                        + p.info.packageName + " ignored: base tree "
5877                                        + tree.name + " is from package "
5878                                        + tree.sourcePackage);
5879                            }
5880                        } else {
5881                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5882                                    + p.info.packageName + " ignored: original from "
5883                                    + bp.sourcePackage);
5884                        }
5885                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5886                        if (r == null) {
5887                            r = new StringBuilder(256);
5888                        } else {
5889                            r.append(' ');
5890                        }
5891                        r.append("DUP:");
5892                        r.append(p.info.name);
5893                    }
5894                    if (bp.perm == p) {
5895                        bp.protectionLevel = p.info.protectionLevel;
5896                    }
5897                } else {
5898                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5899                            + p.info.packageName + " ignored: no group "
5900                            + p.group);
5901                }
5902            }
5903            if (r != null) {
5904                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5905            }
5906
5907            N = pkg.instrumentation.size();
5908            r = null;
5909            for (i=0; i<N; i++) {
5910                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5911                a.info.packageName = pkg.applicationInfo.packageName;
5912                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5913                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5914                a.info.dataDir = pkg.applicationInfo.dataDir;
5915                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5916                mInstrumentation.put(a.getComponentName(), a);
5917                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5918                    if (r == null) {
5919                        r = new StringBuilder(256);
5920                    } else {
5921                        r.append(' ');
5922                    }
5923                    r.append(a.info.name);
5924                }
5925            }
5926            if (r != null) {
5927                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5928            }
5929
5930            if (pkg.protectedBroadcasts != null) {
5931                N = pkg.protectedBroadcasts.size();
5932                for (i=0; i<N; i++) {
5933                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5934                }
5935            }
5936
5937            pkgSetting.setTimeStamp(scanFileTime);
5938
5939            // Create idmap files for pairs of (packages, overlay packages).
5940            // Note: "android", ie framework-res.apk, is handled by native layers.
5941            if (pkg.mOverlayTarget != null) {
5942                // This is an overlay package.
5943                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5944                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5945                        mOverlays.put(pkg.mOverlayTarget,
5946                                new HashMap<String, PackageParser.Package>());
5947                    }
5948                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5949                    map.put(pkg.packageName, pkg);
5950                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5951                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5952                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5953                        return null;
5954                    }
5955                }
5956            } else if (mOverlays.containsKey(pkg.packageName) &&
5957                    !pkg.packageName.equals("android")) {
5958                // This is a regular package, with one or more known overlay packages.
5959                createIdmapsForPackageLI(pkg);
5960            }
5961        }
5962
5963        return pkg;
5964    }
5965
5966    /**
5967     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5968     * i.e, so that all packages can be run inside a single process if required.
5969     *
5970     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5971     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5972     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5973     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5974     * updating a package that belongs to a shared user.
5975     */
5976    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5977            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5978        String requiredInstructionSet = null;
5979        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5980            requiredInstructionSet = VMRuntime.getInstructionSet(
5981                     scannedPackage.applicationInfo.cpuAbi);
5982        }
5983
5984        PackageSetting requirer = null;
5985        for (PackageSetting ps : packagesForUser) {
5986            // If packagesForUser contains scannedPackage, we skip it. This will happen
5987            // when scannedPackage is an update of an existing package. Without this check,
5988            // we will never be able to change the ABI of any package belonging to a shared
5989            // user, even if it's compatible with other packages.
5990            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
5991                if (ps.cpuAbiString == null) {
5992                    continue;
5993                }
5994
5995                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5996                if (requiredInstructionSet != null) {
5997                    if (!instructionSet.equals(requiredInstructionSet)) {
5998                        // We have a mismatch between instruction sets (say arm vs arm64).
5999                        // bail out.
6000                        String errorMessage = "Instruction set mismatch, "
6001                                + ((requirer == null) ? "[caller]" : requirer)
6002                                + " requires " + requiredInstructionSet + " whereas " + ps
6003                                + " requires " + instructionSet;
6004                        Slog.e(TAG, errorMessage);
6005
6006                        reportSettingsProblem(Log.WARN, errorMessage);
6007                        // Give up, don't bother making any other changes to the package settings.
6008                        return false;
6009                    }
6010                } else {
6011                    requiredInstructionSet = instructionSet;
6012                    requirer = ps;
6013                }
6014            }
6015        }
6016
6017        if (requiredInstructionSet != null) {
6018            String adjustedAbi;
6019            if (requirer != null) {
6020                // requirer != null implies that either scannedPackage was null or that scannedPackage
6021                // did not require an ABI, in which case we have to adjust scannedPackage to match
6022                // the ABI of the set (which is the same as requirer's ABI)
6023                adjustedAbi = requirer.cpuAbiString;
6024                if (scannedPackage != null) {
6025                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6026                }
6027            } else {
6028                // requirer == null implies that we're updating all ABIs in the set to
6029                // match scannedPackage.
6030                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6031            }
6032
6033            for (PackageSetting ps : packagesForUser) {
6034                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6035                    if (ps.cpuAbiString != null) {
6036                        continue;
6037                    }
6038
6039                    ps.cpuAbiString = adjustedAbi;
6040                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6041                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6042                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6043
6044                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6045                            ps.cpuAbiString = null;
6046                            ps.pkg.applicationInfo.cpuAbi = null;
6047                            return false;
6048                        } else {
6049                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6050                        }
6051                    }
6052                }
6053            }
6054        }
6055
6056        return true;
6057    }
6058
6059    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6060        synchronized (mPackages) {
6061            mResolverReplaced = true;
6062            // Set up information for custom user intent resolution activity.
6063            mResolveActivity.applicationInfo = pkg.applicationInfo;
6064            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6065            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6066            mResolveActivity.processName = null;
6067            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6068            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6069                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6070            mResolveActivity.theme = 0;
6071            mResolveActivity.exported = true;
6072            mResolveActivity.enabled = true;
6073            mResolveInfo.activityInfo = mResolveActivity;
6074            mResolveInfo.priority = 0;
6075            mResolveInfo.preferredOrder = 0;
6076            mResolveInfo.match = 0;
6077            mResolveComponentName = mCustomResolverComponentName;
6078            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6079                    mResolveComponentName);
6080        }
6081    }
6082
6083    private String calculateApkRoot(final String codePathString) {
6084        final File codePath = new File(codePathString);
6085        final File codeRoot;
6086        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6087            codeRoot = Environment.getRootDirectory();
6088        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6089            codeRoot = Environment.getOemDirectory();
6090        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6091            codeRoot = Environment.getVendorDirectory();
6092        } else {
6093            // Unrecognized code path; take its top real segment as the apk root:
6094            // e.g. /something/app/blah.apk => /something
6095            try {
6096                File f = codePath.getCanonicalFile();
6097                File parent = f.getParentFile();    // non-null because codePath is a file
6098                File tmp;
6099                while ((tmp = parent.getParentFile()) != null) {
6100                    f = parent;
6101                    parent = tmp;
6102                }
6103                codeRoot = f;
6104                Slog.w(TAG, "Unrecognized code path "
6105                        + codePath + " - using " + codeRoot);
6106            } catch (IOException e) {
6107                // Can't canonicalize the lib path -- shenanigans?
6108                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6109                return Environment.getRootDirectory().getPath();
6110            }
6111        }
6112        return codeRoot.getPath();
6113    }
6114
6115    // This is the initial scan-time determination of how to handle a given
6116    // package for purposes of native library location.
6117    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6118            PackageSetting pkgSetting) {
6119        // "bundled" here means system-installed with no overriding update
6120        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6121        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6122        final File libDir;
6123        if (bundledApk) {
6124            // If "/system/lib64/apkname" exists, assume that is the per-package
6125            // native library directory to use; otherwise use "/system/lib/apkname".
6126            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6127            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6128            File packLib64 = new File(lib64, apkName);
6129            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6130        } else {
6131            libDir = mAppLibInstallDir;
6132        }
6133        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6134        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6135        // pkgSetting might be null during rescan following uninstall of updates
6136        // to a bundled app, so accommodate that possibility.  The settings in
6137        // that case will be established later from the parsed package.
6138        if (pkgSetting != null) {
6139            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6140        }
6141    }
6142
6143    // Deduces the required ABI of an upgraded system app.
6144    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6145        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6146        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6147
6148        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6149        // or similar.
6150        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6151        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6152
6153        // Assume that the bundled native libraries always correspond to the
6154        // most preferred 32 or 64 bit ABI.
6155        if (lib64.exists()) {
6156            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6157            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6158        } else if (lib.exists()) {
6159            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6160            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6161        } else {
6162            // This is the case where the app has no native code.
6163            pkg.applicationInfo.cpuAbi = null;
6164            pkgSetting.cpuAbiString = null;
6165        }
6166    }
6167
6168    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6169            final File nativeLibraryDir, String[] abiList) throws IOException {
6170        if (!nativeLibraryDir.isDirectory()) {
6171            nativeLibraryDir.delete();
6172
6173            if (!nativeLibraryDir.mkdir()) {
6174                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6175            }
6176
6177            try {
6178                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6179            } catch (ErrnoException e) {
6180                throw new IOException("Cannot chmod native library directory "
6181                        + nativeLibraryDir.getPath(), e);
6182            }
6183        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6184            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6185        }
6186
6187        /*
6188         * If this is an internal application or our nativeLibraryPath points to
6189         * the app-lib directory, unpack the libraries if necessary.
6190         */
6191        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6192        if (abi >= 0) {
6193            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6194                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6195            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6196                return copyRet;
6197            }
6198        }
6199
6200        return abi;
6201    }
6202
6203    private void killApplication(String pkgName, int appId, String reason) {
6204        // Request the ActivityManager to kill the process(only for existing packages)
6205        // so that we do not end up in a confused state while the user is still using the older
6206        // version of the application while the new one gets installed.
6207        IActivityManager am = ActivityManagerNative.getDefault();
6208        if (am != null) {
6209            try {
6210                am.killApplicationWithAppId(pkgName, appId, reason);
6211            } catch (RemoteException e) {
6212            }
6213        }
6214    }
6215
6216    void removePackageLI(PackageSetting ps, boolean chatty) {
6217        if (DEBUG_INSTALL) {
6218            if (chatty)
6219                Log.d(TAG, "Removing package " + ps.name);
6220        }
6221
6222        // writer
6223        synchronized (mPackages) {
6224            mPackages.remove(ps.name);
6225            if (ps.codePathString != null) {
6226                mAppDirs.remove(ps.codePathString);
6227            }
6228
6229            final PackageParser.Package pkg = ps.pkg;
6230            if (pkg != null) {
6231                cleanPackageDataStructuresLILPw(pkg, chatty);
6232            }
6233        }
6234    }
6235
6236    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6237        if (DEBUG_INSTALL) {
6238            if (chatty)
6239                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6240        }
6241
6242        // writer
6243        synchronized (mPackages) {
6244            mPackages.remove(pkg.applicationInfo.packageName);
6245            if (pkg.mPath != null) {
6246                mAppDirs.remove(pkg.mPath);
6247            }
6248            cleanPackageDataStructuresLILPw(pkg, chatty);
6249        }
6250    }
6251
6252    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6253        int N = pkg.providers.size();
6254        StringBuilder r = null;
6255        int i;
6256        for (i=0; i<N; i++) {
6257            PackageParser.Provider p = pkg.providers.get(i);
6258            mProviders.removeProvider(p);
6259            if (p.info.authority == null) {
6260
6261                /* There was another ContentProvider with this authority when
6262                 * this app was installed so this authority is null,
6263                 * Ignore it as we don't have to unregister the provider.
6264                 */
6265                continue;
6266            }
6267            String names[] = p.info.authority.split(";");
6268            for (int j = 0; j < names.length; j++) {
6269                if (mProvidersByAuthority.get(names[j]) == p) {
6270                    mProvidersByAuthority.remove(names[j]);
6271                    if (DEBUG_REMOVE) {
6272                        if (chatty)
6273                            Log.d(TAG, "Unregistered content provider: " + names[j]
6274                                    + ", className = " + p.info.name + ", isSyncable = "
6275                                    + p.info.isSyncable);
6276                    }
6277                }
6278            }
6279            if (DEBUG_REMOVE && chatty) {
6280                if (r == null) {
6281                    r = new StringBuilder(256);
6282                } else {
6283                    r.append(' ');
6284                }
6285                r.append(p.info.name);
6286            }
6287        }
6288        if (r != null) {
6289            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6290        }
6291
6292        N = pkg.services.size();
6293        r = null;
6294        for (i=0; i<N; i++) {
6295            PackageParser.Service s = pkg.services.get(i);
6296            mServices.removeService(s);
6297            if (chatty) {
6298                if (r == null) {
6299                    r = new StringBuilder(256);
6300                } else {
6301                    r.append(' ');
6302                }
6303                r.append(s.info.name);
6304            }
6305        }
6306        if (r != null) {
6307            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6308        }
6309
6310        N = pkg.receivers.size();
6311        r = null;
6312        for (i=0; i<N; i++) {
6313            PackageParser.Activity a = pkg.receivers.get(i);
6314            mReceivers.removeActivity(a, "receiver");
6315            if (DEBUG_REMOVE && chatty) {
6316                if (r == null) {
6317                    r = new StringBuilder(256);
6318                } else {
6319                    r.append(' ');
6320                }
6321                r.append(a.info.name);
6322            }
6323        }
6324        if (r != null) {
6325            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6326        }
6327
6328        N = pkg.activities.size();
6329        r = null;
6330        for (i=0; i<N; i++) {
6331            PackageParser.Activity a = pkg.activities.get(i);
6332            mActivities.removeActivity(a, "activity");
6333            if (DEBUG_REMOVE && chatty) {
6334                if (r == null) {
6335                    r = new StringBuilder(256);
6336                } else {
6337                    r.append(' ');
6338                }
6339                r.append(a.info.name);
6340            }
6341        }
6342        if (r != null) {
6343            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6344        }
6345
6346        N = pkg.permissions.size();
6347        r = null;
6348        for (i=0; i<N; i++) {
6349            PackageParser.Permission p = pkg.permissions.get(i);
6350            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6351            if (bp == null) {
6352                bp = mSettings.mPermissionTrees.get(p.info.name);
6353            }
6354            if (bp != null && bp.perm == p) {
6355                bp.perm = null;
6356                if (DEBUG_REMOVE && chatty) {
6357                    if (r == null) {
6358                        r = new StringBuilder(256);
6359                    } else {
6360                        r.append(' ');
6361                    }
6362                    r.append(p.info.name);
6363                }
6364            }
6365        }
6366        if (r != null) {
6367            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6368        }
6369
6370        N = pkg.instrumentation.size();
6371        r = null;
6372        for (i=0; i<N; i++) {
6373            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6374            mInstrumentation.remove(a.getComponentName());
6375            if (DEBUG_REMOVE && chatty) {
6376                if (r == null) {
6377                    r = new StringBuilder(256);
6378                } else {
6379                    r.append(' ');
6380                }
6381                r.append(a.info.name);
6382            }
6383        }
6384        if (r != null) {
6385            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6386        }
6387
6388        r = null;
6389        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6390            // Only system apps can hold shared libraries.
6391            if (pkg.libraryNames != null) {
6392                for (i=0; i<pkg.libraryNames.size(); i++) {
6393                    String name = pkg.libraryNames.get(i);
6394                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6395                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6396                        mSharedLibraries.remove(name);
6397                        if (DEBUG_REMOVE && chatty) {
6398                            if (r == null) {
6399                                r = new StringBuilder(256);
6400                            } else {
6401                                r.append(' ');
6402                            }
6403                            r.append(name);
6404                        }
6405                    }
6406                }
6407            }
6408        }
6409        if (r != null) {
6410            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6411        }
6412    }
6413
6414    private static final boolean isPackageFilename(String name) {
6415        return name != null && name.endsWith(".apk");
6416    }
6417
6418    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6419        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6420            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6421                return true;
6422            }
6423        }
6424        return false;
6425    }
6426
6427    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6428    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6429    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6430
6431    private void updatePermissionsLPw(String changingPkg,
6432            PackageParser.Package pkgInfo, int flags) {
6433        // Make sure there are no dangling permission trees.
6434        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6435        while (it.hasNext()) {
6436            final BasePermission bp = it.next();
6437            if (bp.packageSetting == null) {
6438                // We may not yet have parsed the package, so just see if
6439                // we still know about its settings.
6440                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6441            }
6442            if (bp.packageSetting == null) {
6443                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6444                        + " from package " + bp.sourcePackage);
6445                it.remove();
6446            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6447                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6448                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6449                            + " from package " + bp.sourcePackage);
6450                    flags |= UPDATE_PERMISSIONS_ALL;
6451                    it.remove();
6452                }
6453            }
6454        }
6455
6456        // Make sure all dynamic permissions have been assigned to a package,
6457        // and make sure there are no dangling permissions.
6458        it = mSettings.mPermissions.values().iterator();
6459        while (it.hasNext()) {
6460            final BasePermission bp = it.next();
6461            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6462                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6463                        + bp.name + " pkg=" + bp.sourcePackage
6464                        + " info=" + bp.pendingInfo);
6465                if (bp.packageSetting == null && bp.pendingInfo != null) {
6466                    final BasePermission tree = findPermissionTreeLP(bp.name);
6467                    if (tree != null && tree.perm != null) {
6468                        bp.packageSetting = tree.packageSetting;
6469                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6470                                new PermissionInfo(bp.pendingInfo));
6471                        bp.perm.info.packageName = tree.perm.info.packageName;
6472                        bp.perm.info.name = bp.name;
6473                        bp.uid = tree.uid;
6474                    }
6475                }
6476            }
6477            if (bp.packageSetting == null) {
6478                // We may not yet have parsed the package, so just see if
6479                // we still know about its settings.
6480                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6481            }
6482            if (bp.packageSetting == null) {
6483                Slog.w(TAG, "Removing dangling permission: " + bp.name
6484                        + " from package " + bp.sourcePackage);
6485                it.remove();
6486            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6487                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6488                    Slog.i(TAG, "Removing old permission: " + bp.name
6489                            + " from package " + bp.sourcePackage);
6490                    flags |= UPDATE_PERMISSIONS_ALL;
6491                    it.remove();
6492                }
6493            }
6494        }
6495
6496        // Now update the permissions for all packages, in particular
6497        // replace the granted permissions of the system packages.
6498        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6499            for (PackageParser.Package pkg : mPackages.values()) {
6500                if (pkg != pkgInfo) {
6501                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6502                }
6503            }
6504        }
6505
6506        if (pkgInfo != null) {
6507            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6508        }
6509    }
6510
6511    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6512        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6513        if (ps == null) {
6514            return;
6515        }
6516        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6517        HashSet<String> origPermissions = gp.grantedPermissions;
6518        boolean changedPermission = false;
6519
6520        if (replace) {
6521            ps.permissionsFixed = false;
6522            if (gp == ps) {
6523                origPermissions = new HashSet<String>(gp.grantedPermissions);
6524                gp.grantedPermissions.clear();
6525                gp.gids = mGlobalGids;
6526            }
6527        }
6528
6529        if (gp.gids == null) {
6530            gp.gids = mGlobalGids;
6531        }
6532
6533        final int N = pkg.requestedPermissions.size();
6534        for (int i=0; i<N; i++) {
6535            final String name = pkg.requestedPermissions.get(i);
6536            final boolean required = pkg.requestedPermissionsRequired.get(i);
6537            final BasePermission bp = mSettings.mPermissions.get(name);
6538            if (DEBUG_INSTALL) {
6539                if (gp != ps) {
6540                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6541                }
6542            }
6543
6544            if (bp == null || bp.packageSetting == null) {
6545                Slog.w(TAG, "Unknown permission " + name
6546                        + " in package " + pkg.packageName);
6547                continue;
6548            }
6549
6550            final String perm = bp.name;
6551            boolean allowed;
6552            boolean allowedSig = false;
6553            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6554            if (level == PermissionInfo.PROTECTION_NORMAL
6555                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6556                // We grant a normal or dangerous permission if any of the following
6557                // are true:
6558                // 1) The permission is required
6559                // 2) The permission is optional, but was granted in the past
6560                // 3) The permission is optional, but was requested by an
6561                //    app in /system (not /data)
6562                //
6563                // Otherwise, reject the permission.
6564                allowed = (required || origPermissions.contains(perm)
6565                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6566            } else if (bp.packageSetting == null) {
6567                // This permission is invalid; skip it.
6568                allowed = false;
6569            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6570                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6571                if (allowed) {
6572                    allowedSig = true;
6573                }
6574            } else {
6575                allowed = false;
6576            }
6577            if (DEBUG_INSTALL) {
6578                if (gp != ps) {
6579                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6580                }
6581            }
6582            if (allowed) {
6583                if (!isSystemApp(ps) && ps.permissionsFixed) {
6584                    // If this is an existing, non-system package, then
6585                    // we can't add any new permissions to it.
6586                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6587                        // Except...  if this is a permission that was added
6588                        // to the platform (note: need to only do this when
6589                        // updating the platform).
6590                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6591                    }
6592                }
6593                if (allowed) {
6594                    if (!gp.grantedPermissions.contains(perm)) {
6595                        changedPermission = true;
6596                        gp.grantedPermissions.add(perm);
6597                        gp.gids = appendInts(gp.gids, bp.gids);
6598                    } else if (!ps.haveGids) {
6599                        gp.gids = appendInts(gp.gids, bp.gids);
6600                    }
6601                } else {
6602                    Slog.w(TAG, "Not granting permission " + perm
6603                            + " to package " + pkg.packageName
6604                            + " because it was previously installed without");
6605                }
6606            } else {
6607                if (gp.grantedPermissions.remove(perm)) {
6608                    changedPermission = true;
6609                    gp.gids = removeInts(gp.gids, bp.gids);
6610                    Slog.i(TAG, "Un-granting permission " + perm
6611                            + " from package " + pkg.packageName
6612                            + " (protectionLevel=" + bp.protectionLevel
6613                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6614                            + ")");
6615                } else {
6616                    Slog.w(TAG, "Not granting permission " + perm
6617                            + " to package " + pkg.packageName
6618                            + " (protectionLevel=" + bp.protectionLevel
6619                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6620                            + ")");
6621                }
6622            }
6623        }
6624
6625        if ((changedPermission || replace) && !ps.permissionsFixed &&
6626                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6627            // This is the first that we have heard about this package, so the
6628            // permissions we have now selected are fixed until explicitly
6629            // changed.
6630            ps.permissionsFixed = true;
6631        }
6632        ps.haveGids = true;
6633    }
6634
6635    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6636        boolean allowed = false;
6637        final int NP = PackageParser.NEW_PERMISSIONS.length;
6638        for (int ip=0; ip<NP; ip++) {
6639            final PackageParser.NewPermissionInfo npi
6640                    = PackageParser.NEW_PERMISSIONS[ip];
6641            if (npi.name.equals(perm)
6642                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6643                allowed = true;
6644                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6645                        + pkg.packageName);
6646                break;
6647            }
6648        }
6649        return allowed;
6650    }
6651
6652    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6653                                          BasePermission bp, HashSet<String> origPermissions) {
6654        boolean allowed;
6655        allowed = (compareSignatures(
6656                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6657                        == PackageManager.SIGNATURE_MATCH)
6658                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6659                        == PackageManager.SIGNATURE_MATCH);
6660        if (!allowed && (bp.protectionLevel
6661                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6662            if (isSystemApp(pkg)) {
6663                // For updated system applications, a system permission
6664                // is granted only if it had been defined by the original application.
6665                if (isUpdatedSystemApp(pkg)) {
6666                    final PackageSetting sysPs = mSettings
6667                            .getDisabledSystemPkgLPr(pkg.packageName);
6668                    final GrantedPermissions origGp = sysPs.sharedUser != null
6669                            ? sysPs.sharedUser : sysPs;
6670
6671                    if (origGp.grantedPermissions.contains(perm)) {
6672                        // If the original was granted this permission, we take
6673                        // that grant decision as read and propagate it to the
6674                        // update.
6675                        allowed = true;
6676                    } else {
6677                        // The system apk may have been updated with an older
6678                        // version of the one on the data partition, but which
6679                        // granted a new system permission that it didn't have
6680                        // before.  In this case we do want to allow the app to
6681                        // now get the new permission if the ancestral apk is
6682                        // privileged to get it.
6683                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6684                            for (int j=0;
6685                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6686                                if (perm.equals(
6687                                        sysPs.pkg.requestedPermissions.get(j))) {
6688                                    allowed = true;
6689                                    break;
6690                                }
6691                            }
6692                        }
6693                    }
6694                } else {
6695                    allowed = isPrivilegedApp(pkg);
6696                }
6697            }
6698        }
6699        if (!allowed && (bp.protectionLevel
6700                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6701            // For development permissions, a development permission
6702            // is granted only if it was already granted.
6703            allowed = origPermissions.contains(perm);
6704        }
6705        return allowed;
6706    }
6707
6708    final class ActivityIntentResolver
6709            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6711                boolean defaultOnly, int userId) {
6712            if (!sUserManager.exists(userId)) return null;
6713            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6714            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6715        }
6716
6717        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6718                int userId) {
6719            if (!sUserManager.exists(userId)) return null;
6720            mFlags = flags;
6721            return super.queryIntent(intent, resolvedType,
6722                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6723        }
6724
6725        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6726                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6727            if (!sUserManager.exists(userId)) return null;
6728            if (packageActivities == null) {
6729                return null;
6730            }
6731            mFlags = flags;
6732            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6733            final int N = packageActivities.size();
6734            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6735                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6736
6737            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6738            for (int i = 0; i < N; ++i) {
6739                intentFilters = packageActivities.get(i).intents;
6740                if (intentFilters != null && intentFilters.size() > 0) {
6741                    PackageParser.ActivityIntentInfo[] array =
6742                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6743                    intentFilters.toArray(array);
6744                    listCut.add(array);
6745                }
6746            }
6747            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6748        }
6749
6750        public final void addActivity(PackageParser.Activity a, String type) {
6751            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6752            mActivities.put(a.getComponentName(), a);
6753            if (DEBUG_SHOW_INFO)
6754                Log.v(
6755                TAG, "  " + type + " " +
6756                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6757            if (DEBUG_SHOW_INFO)
6758                Log.v(TAG, "    Class=" + a.info.name);
6759            final int NI = a.intents.size();
6760            for (int j=0; j<NI; j++) {
6761                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6762                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6763                    intent.setPriority(0);
6764                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6765                            + a.className + " with priority > 0, forcing to 0");
6766                }
6767                if (DEBUG_SHOW_INFO) {
6768                    Log.v(TAG, "    IntentFilter:");
6769                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6770                }
6771                if (!intent.debugCheck()) {
6772                    Log.w(TAG, "==> For Activity " + a.info.name);
6773                }
6774                addFilter(intent);
6775            }
6776        }
6777
6778        public final void removeActivity(PackageParser.Activity a, String type) {
6779            mActivities.remove(a.getComponentName());
6780            if (DEBUG_SHOW_INFO) {
6781                Log.v(TAG, "  " + type + " "
6782                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6783                                : a.info.name) + ":");
6784                Log.v(TAG, "    Class=" + a.info.name);
6785            }
6786            final int NI = a.intents.size();
6787            for (int j=0; j<NI; j++) {
6788                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6789                if (DEBUG_SHOW_INFO) {
6790                    Log.v(TAG, "    IntentFilter:");
6791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6792                }
6793                removeFilter(intent);
6794            }
6795        }
6796
6797        @Override
6798        protected boolean allowFilterResult(
6799                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6800            ActivityInfo filterAi = filter.activity.info;
6801            for (int i=dest.size()-1; i>=0; i--) {
6802                ActivityInfo destAi = dest.get(i).activityInfo;
6803                if (destAi.name == filterAi.name
6804                        && destAi.packageName == filterAi.packageName) {
6805                    return false;
6806                }
6807            }
6808            return true;
6809        }
6810
6811        @Override
6812        protected ActivityIntentInfo[] newArray(int size) {
6813            return new ActivityIntentInfo[size];
6814        }
6815
6816        @Override
6817        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6818            if (!sUserManager.exists(userId)) return true;
6819            PackageParser.Package p = filter.activity.owner;
6820            if (p != null) {
6821                PackageSetting ps = (PackageSetting)p.mExtras;
6822                if (ps != null) {
6823                    // System apps are never considered stopped for purposes of
6824                    // filtering, because there may be no way for the user to
6825                    // actually re-launch them.
6826                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6827                            && ps.getStopped(userId);
6828                }
6829            }
6830            return false;
6831        }
6832
6833        @Override
6834        protected boolean isPackageForFilter(String packageName,
6835                PackageParser.ActivityIntentInfo info) {
6836            return packageName.equals(info.activity.owner.packageName);
6837        }
6838
6839        @Override
6840        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6841                int match, int userId) {
6842            if (!sUserManager.exists(userId)) return null;
6843            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6844                return null;
6845            }
6846            final PackageParser.Activity activity = info.activity;
6847            if (mSafeMode && (activity.info.applicationInfo.flags
6848                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6849                return null;
6850            }
6851            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6852            if (ps == null) {
6853                return null;
6854            }
6855            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6856                    ps.readUserState(userId), userId);
6857            if (ai == null) {
6858                return null;
6859            }
6860            final ResolveInfo res = new ResolveInfo();
6861            res.activityInfo = ai;
6862            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6863                res.filter = info;
6864            }
6865            res.priority = info.getPriority();
6866            res.preferredOrder = activity.owner.mPreferredOrder;
6867            //System.out.println("Result: " + res.activityInfo.className +
6868            //                   " = " + res.priority);
6869            res.match = match;
6870            res.isDefault = info.hasDefault;
6871            res.labelRes = info.labelRes;
6872            res.nonLocalizedLabel = info.nonLocalizedLabel;
6873            res.icon = info.icon;
6874            res.system = isSystemApp(res.activityInfo.applicationInfo);
6875            return res;
6876        }
6877
6878        @Override
6879        protected void sortResults(List<ResolveInfo> results) {
6880            Collections.sort(results, mResolvePrioritySorter);
6881        }
6882
6883        @Override
6884        protected void dumpFilter(PrintWriter out, String prefix,
6885                PackageParser.ActivityIntentInfo filter) {
6886            out.print(prefix); out.print(
6887                    Integer.toHexString(System.identityHashCode(filter.activity)));
6888                    out.print(' ');
6889                    filter.activity.printComponentShortName(out);
6890                    out.print(" filter ");
6891                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6892        }
6893
6894//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6895//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6896//            final List<ResolveInfo> retList = Lists.newArrayList();
6897//            while (i.hasNext()) {
6898//                final ResolveInfo resolveInfo = i.next();
6899//                if (isEnabledLP(resolveInfo.activityInfo)) {
6900//                    retList.add(resolveInfo);
6901//                }
6902//            }
6903//            return retList;
6904//        }
6905
6906        // Keys are String (activity class name), values are Activity.
6907        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6908                = new HashMap<ComponentName, PackageParser.Activity>();
6909        private int mFlags;
6910    }
6911
6912    private final class ServiceIntentResolver
6913            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6914        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6915                boolean defaultOnly, int userId) {
6916            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6917            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6918        }
6919
6920        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6921                int userId) {
6922            if (!sUserManager.exists(userId)) return null;
6923            mFlags = flags;
6924            return super.queryIntent(intent, resolvedType,
6925                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6926        }
6927
6928        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6929                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6930            if (!sUserManager.exists(userId)) return null;
6931            if (packageServices == null) {
6932                return null;
6933            }
6934            mFlags = flags;
6935            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6936            final int N = packageServices.size();
6937            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6938                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6939
6940            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6941            for (int i = 0; i < N; ++i) {
6942                intentFilters = packageServices.get(i).intents;
6943                if (intentFilters != null && intentFilters.size() > 0) {
6944                    PackageParser.ServiceIntentInfo[] array =
6945                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6946                    intentFilters.toArray(array);
6947                    listCut.add(array);
6948                }
6949            }
6950            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6951        }
6952
6953        public final void addService(PackageParser.Service s) {
6954            mServices.put(s.getComponentName(), s);
6955            if (DEBUG_SHOW_INFO) {
6956                Log.v(TAG, "  "
6957                        + (s.info.nonLocalizedLabel != null
6958                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6959                Log.v(TAG, "    Class=" + s.info.name);
6960            }
6961            final int NI = s.intents.size();
6962            int j;
6963            for (j=0; j<NI; j++) {
6964                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6965                if (DEBUG_SHOW_INFO) {
6966                    Log.v(TAG, "    IntentFilter:");
6967                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6968                }
6969                if (!intent.debugCheck()) {
6970                    Log.w(TAG, "==> For Service " + s.info.name);
6971                }
6972                addFilter(intent);
6973            }
6974        }
6975
6976        public final void removeService(PackageParser.Service s) {
6977            mServices.remove(s.getComponentName());
6978            if (DEBUG_SHOW_INFO) {
6979                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6980                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6981                Log.v(TAG, "    Class=" + s.info.name);
6982            }
6983            final int NI = s.intents.size();
6984            int j;
6985            for (j=0; j<NI; j++) {
6986                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6987                if (DEBUG_SHOW_INFO) {
6988                    Log.v(TAG, "    IntentFilter:");
6989                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6990                }
6991                removeFilter(intent);
6992            }
6993        }
6994
6995        @Override
6996        protected boolean allowFilterResult(
6997                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6998            ServiceInfo filterSi = filter.service.info;
6999            for (int i=dest.size()-1; i>=0; i--) {
7000                ServiceInfo destAi = dest.get(i).serviceInfo;
7001                if (destAi.name == filterSi.name
7002                        && destAi.packageName == filterSi.packageName) {
7003                    return false;
7004                }
7005            }
7006            return true;
7007        }
7008
7009        @Override
7010        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7011            return new PackageParser.ServiceIntentInfo[size];
7012        }
7013
7014        @Override
7015        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7016            if (!sUserManager.exists(userId)) return true;
7017            PackageParser.Package p = filter.service.owner;
7018            if (p != null) {
7019                PackageSetting ps = (PackageSetting)p.mExtras;
7020                if (ps != null) {
7021                    // System apps are never considered stopped for purposes of
7022                    // filtering, because there may be no way for the user to
7023                    // actually re-launch them.
7024                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7025                            && ps.getStopped(userId);
7026                }
7027            }
7028            return false;
7029        }
7030
7031        @Override
7032        protected boolean isPackageForFilter(String packageName,
7033                PackageParser.ServiceIntentInfo info) {
7034            return packageName.equals(info.service.owner.packageName);
7035        }
7036
7037        @Override
7038        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7039                int match, int userId) {
7040            if (!sUserManager.exists(userId)) return null;
7041            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7042            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7043                return null;
7044            }
7045            final PackageParser.Service service = info.service;
7046            if (mSafeMode && (service.info.applicationInfo.flags
7047                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7048                return null;
7049            }
7050            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7051            if (ps == null) {
7052                return null;
7053            }
7054            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7055                    ps.readUserState(userId), userId);
7056            if (si == null) {
7057                return null;
7058            }
7059            final ResolveInfo res = new ResolveInfo();
7060            res.serviceInfo = si;
7061            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7062                res.filter = filter;
7063            }
7064            res.priority = info.getPriority();
7065            res.preferredOrder = service.owner.mPreferredOrder;
7066            //System.out.println("Result: " + res.activityInfo.className +
7067            //                   " = " + res.priority);
7068            res.match = match;
7069            res.isDefault = info.hasDefault;
7070            res.labelRes = info.labelRes;
7071            res.nonLocalizedLabel = info.nonLocalizedLabel;
7072            res.icon = info.icon;
7073            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7074            return res;
7075        }
7076
7077        @Override
7078        protected void sortResults(List<ResolveInfo> results) {
7079            Collections.sort(results, mResolvePrioritySorter);
7080        }
7081
7082        @Override
7083        protected void dumpFilter(PrintWriter out, String prefix,
7084                PackageParser.ServiceIntentInfo filter) {
7085            out.print(prefix); out.print(
7086                    Integer.toHexString(System.identityHashCode(filter.service)));
7087                    out.print(' ');
7088                    filter.service.printComponentShortName(out);
7089                    out.print(" filter ");
7090                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7091        }
7092
7093//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7094//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7095//            final List<ResolveInfo> retList = Lists.newArrayList();
7096//            while (i.hasNext()) {
7097//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7098//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7099//                    retList.add(resolveInfo);
7100//                }
7101//            }
7102//            return retList;
7103//        }
7104
7105        // Keys are String (activity class name), values are Activity.
7106        private final HashMap<ComponentName, PackageParser.Service> mServices
7107                = new HashMap<ComponentName, PackageParser.Service>();
7108        private int mFlags;
7109    };
7110
7111    private final class ProviderIntentResolver
7112            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7113        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7114                boolean defaultOnly, int userId) {
7115            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7116            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7117        }
7118
7119        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7120                int userId) {
7121            if (!sUserManager.exists(userId))
7122                return null;
7123            mFlags = flags;
7124            return super.queryIntent(intent, resolvedType,
7125                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7126        }
7127
7128        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7129                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7130            if (!sUserManager.exists(userId))
7131                return null;
7132            if (packageProviders == null) {
7133                return null;
7134            }
7135            mFlags = flags;
7136            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7137            final int N = packageProviders.size();
7138            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7139                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7140
7141            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7142            for (int i = 0; i < N; ++i) {
7143                intentFilters = packageProviders.get(i).intents;
7144                if (intentFilters != null && intentFilters.size() > 0) {
7145                    PackageParser.ProviderIntentInfo[] array =
7146                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7147                    intentFilters.toArray(array);
7148                    listCut.add(array);
7149                }
7150            }
7151            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7152        }
7153
7154        public final void addProvider(PackageParser.Provider p) {
7155            if (mProviders.containsKey(p.getComponentName())) {
7156                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7157                return;
7158            }
7159
7160            mProviders.put(p.getComponentName(), p);
7161            if (DEBUG_SHOW_INFO) {
7162                Log.v(TAG, "  "
7163                        + (p.info.nonLocalizedLabel != null
7164                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7165                Log.v(TAG, "    Class=" + p.info.name);
7166            }
7167            final int NI = p.intents.size();
7168            int j;
7169            for (j = 0; j < NI; j++) {
7170                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7171                if (DEBUG_SHOW_INFO) {
7172                    Log.v(TAG, "    IntentFilter:");
7173                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7174                }
7175                if (!intent.debugCheck()) {
7176                    Log.w(TAG, "==> For Provider " + p.info.name);
7177                }
7178                addFilter(intent);
7179            }
7180        }
7181
7182        public final void removeProvider(PackageParser.Provider p) {
7183            mProviders.remove(p.getComponentName());
7184            if (DEBUG_SHOW_INFO) {
7185                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7186                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7187                Log.v(TAG, "    Class=" + p.info.name);
7188            }
7189            final int NI = p.intents.size();
7190            int j;
7191            for (j = 0; j < NI; j++) {
7192                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7193                if (DEBUG_SHOW_INFO) {
7194                    Log.v(TAG, "    IntentFilter:");
7195                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7196                }
7197                removeFilter(intent);
7198            }
7199        }
7200
7201        @Override
7202        protected boolean allowFilterResult(
7203                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7204            ProviderInfo filterPi = filter.provider.info;
7205            for (int i = dest.size() - 1; i >= 0; i--) {
7206                ProviderInfo destPi = dest.get(i).providerInfo;
7207                if (destPi.name == filterPi.name
7208                        && destPi.packageName == filterPi.packageName) {
7209                    return false;
7210                }
7211            }
7212            return true;
7213        }
7214
7215        @Override
7216        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7217            return new PackageParser.ProviderIntentInfo[size];
7218        }
7219
7220        @Override
7221        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7222            if (!sUserManager.exists(userId))
7223                return true;
7224            PackageParser.Package p = filter.provider.owner;
7225            if (p != null) {
7226                PackageSetting ps = (PackageSetting) p.mExtras;
7227                if (ps != null) {
7228                    // System apps are never considered stopped for purposes of
7229                    // filtering, because there may be no way for the user to
7230                    // actually re-launch them.
7231                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7232                            && ps.getStopped(userId);
7233                }
7234            }
7235            return false;
7236        }
7237
7238        @Override
7239        protected boolean isPackageForFilter(String packageName,
7240                PackageParser.ProviderIntentInfo info) {
7241            return packageName.equals(info.provider.owner.packageName);
7242        }
7243
7244        @Override
7245        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7246                int match, int userId) {
7247            if (!sUserManager.exists(userId))
7248                return null;
7249            final PackageParser.ProviderIntentInfo info = filter;
7250            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7251                return null;
7252            }
7253            final PackageParser.Provider provider = info.provider;
7254            if (mSafeMode && (provider.info.applicationInfo.flags
7255                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7256                return null;
7257            }
7258            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7259            if (ps == null) {
7260                return null;
7261            }
7262            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7263                    ps.readUserState(userId), userId);
7264            if (pi == null) {
7265                return null;
7266            }
7267            final ResolveInfo res = new ResolveInfo();
7268            res.providerInfo = pi;
7269            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7270                res.filter = filter;
7271            }
7272            res.priority = info.getPriority();
7273            res.preferredOrder = provider.owner.mPreferredOrder;
7274            res.match = match;
7275            res.isDefault = info.hasDefault;
7276            res.labelRes = info.labelRes;
7277            res.nonLocalizedLabel = info.nonLocalizedLabel;
7278            res.icon = info.icon;
7279            res.system = isSystemApp(res.providerInfo.applicationInfo);
7280            return res;
7281        }
7282
7283        @Override
7284        protected void sortResults(List<ResolveInfo> results) {
7285            Collections.sort(results, mResolvePrioritySorter);
7286        }
7287
7288        @Override
7289        protected void dumpFilter(PrintWriter out, String prefix,
7290                PackageParser.ProviderIntentInfo filter) {
7291            out.print(prefix);
7292            out.print(
7293                    Integer.toHexString(System.identityHashCode(filter.provider)));
7294            out.print(' ');
7295            filter.provider.printComponentShortName(out);
7296            out.print(" filter ");
7297            out.println(Integer.toHexString(System.identityHashCode(filter)));
7298        }
7299
7300        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7301                = new HashMap<ComponentName, PackageParser.Provider>();
7302        private int mFlags;
7303    };
7304
7305    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7306            new Comparator<ResolveInfo>() {
7307        public int compare(ResolveInfo r1, ResolveInfo r2) {
7308            int v1 = r1.priority;
7309            int v2 = r2.priority;
7310            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7311            if (v1 != v2) {
7312                return (v1 > v2) ? -1 : 1;
7313            }
7314            v1 = r1.preferredOrder;
7315            v2 = r2.preferredOrder;
7316            if (v1 != v2) {
7317                return (v1 > v2) ? -1 : 1;
7318            }
7319            if (r1.isDefault != r2.isDefault) {
7320                return r1.isDefault ? -1 : 1;
7321            }
7322            v1 = r1.match;
7323            v2 = r2.match;
7324            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7325            if (v1 != v2) {
7326                return (v1 > v2) ? -1 : 1;
7327            }
7328            if (r1.system != r2.system) {
7329                return r1.system ? -1 : 1;
7330            }
7331            return 0;
7332        }
7333    };
7334
7335    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7336            new Comparator<ProviderInfo>() {
7337        public int compare(ProviderInfo p1, ProviderInfo p2) {
7338            final int v1 = p1.initOrder;
7339            final int v2 = p2.initOrder;
7340            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7341        }
7342    };
7343
7344    static final void sendPackageBroadcast(String action, String pkg,
7345            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7346            int[] userIds) {
7347        IActivityManager am = ActivityManagerNative.getDefault();
7348        if (am != null) {
7349            try {
7350                if (userIds == null) {
7351                    userIds = am.getRunningUserIds();
7352                }
7353                for (int id : userIds) {
7354                    final Intent intent = new Intent(action,
7355                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7356                    if (extras != null) {
7357                        intent.putExtras(extras);
7358                    }
7359                    if (targetPkg != null) {
7360                        intent.setPackage(targetPkg);
7361                    }
7362                    // Modify the UID when posting to other users
7363                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7364                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7365                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7366                        intent.putExtra(Intent.EXTRA_UID, uid);
7367                    }
7368                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7369                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7370                    if (DEBUG_BROADCASTS) {
7371                        RuntimeException here = new RuntimeException("here");
7372                        here.fillInStackTrace();
7373                        Slog.d(TAG, "Sending to user " + id + ": "
7374                                + intent.toShortString(false, true, false, false)
7375                                + " " + intent.getExtras(), here);
7376                    }
7377                    am.broadcastIntent(null, intent, null, finishedReceiver,
7378                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7379                            finishedReceiver != null, false, id);
7380                }
7381            } catch (RemoteException ex) {
7382            }
7383        }
7384    }
7385
7386    /**
7387     * Check if the external storage media is available. This is true if there
7388     * is a mounted external storage medium or if the external storage is
7389     * emulated.
7390     */
7391    private boolean isExternalMediaAvailable() {
7392        return mMediaMounted || Environment.isExternalStorageEmulated();
7393    }
7394
7395    @Override
7396    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7397        // writer
7398        synchronized (mPackages) {
7399            if (!isExternalMediaAvailable()) {
7400                // If the external storage is no longer mounted at this point,
7401                // the caller may not have been able to delete all of this
7402                // packages files and can not delete any more.  Bail.
7403                return null;
7404            }
7405            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7406            if (lastPackage != null) {
7407                pkgs.remove(lastPackage);
7408            }
7409            if (pkgs.size() > 0) {
7410                return pkgs.get(0);
7411            }
7412        }
7413        return null;
7414    }
7415
7416    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7417        if (false) {
7418            RuntimeException here = new RuntimeException("here");
7419            here.fillInStackTrace();
7420            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7421                    + " andCode=" + andCode, here);
7422        }
7423        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7424                userId, andCode ? 1 : 0, packageName));
7425    }
7426
7427    void startCleaningPackages() {
7428        // reader
7429        synchronized (mPackages) {
7430            if (!isExternalMediaAvailable()) {
7431                return;
7432            }
7433            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7434                return;
7435            }
7436        }
7437        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7438        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7439        IActivityManager am = ActivityManagerNative.getDefault();
7440        if (am != null) {
7441            try {
7442                am.startService(null, intent, null, UserHandle.USER_OWNER);
7443            } catch (RemoteException e) {
7444            }
7445        }
7446    }
7447
7448    private final class AppDirObserver extends FileObserver {
7449        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7450            super(path, mask);
7451            mRootDir = path;
7452            mIsRom = isrom;
7453            mIsPrivileged = isPrivileged;
7454        }
7455
7456        public void onEvent(int event, String path) {
7457            String removedPackage = null;
7458            int removedAppId = -1;
7459            int[] removedUsers = null;
7460            String addedPackage = null;
7461            int addedAppId = -1;
7462            int[] addedUsers = null;
7463
7464            // TODO post a message to the handler to obtain serial ordering
7465            synchronized (mInstallLock) {
7466                String fullPathStr = null;
7467                File fullPath = null;
7468                if (path != null) {
7469                    fullPath = new File(mRootDir, path);
7470                    fullPathStr = fullPath.getPath();
7471                }
7472
7473                if (DEBUG_APP_DIR_OBSERVER)
7474                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7475
7476                if (!isPackageFilename(path)) {
7477                    if (DEBUG_APP_DIR_OBSERVER)
7478                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7479                    return;
7480                }
7481
7482                // Ignore packages that are being installed or
7483                // have just been installed.
7484                if (ignoreCodePath(fullPathStr)) {
7485                    return;
7486                }
7487                PackageParser.Package p = null;
7488                PackageSetting ps = null;
7489                // reader
7490                synchronized (mPackages) {
7491                    p = mAppDirs.get(fullPathStr);
7492                    if (p != null) {
7493                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7494                        if (ps != null) {
7495                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7496                        } else {
7497                            removedUsers = sUserManager.getUserIds();
7498                        }
7499                    }
7500                    addedUsers = sUserManager.getUserIds();
7501                }
7502                if ((event&REMOVE_EVENTS) != 0) {
7503                    if (ps != null) {
7504                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7505                        removePackageLI(ps, true);
7506                        removedPackage = ps.name;
7507                        removedAppId = ps.appId;
7508                    }
7509                }
7510
7511                if ((event&ADD_EVENTS) != 0) {
7512                    if (p == null) {
7513                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7514                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7515                        if (mIsRom) {
7516                            flags |= PackageParser.PARSE_IS_SYSTEM
7517                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7518                            if (mIsPrivileged) {
7519                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7520                            }
7521                        }
7522                        p = scanPackageLI(fullPath, flags,
7523                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7524                                System.currentTimeMillis(), UserHandle.ALL, null);
7525                        if (p != null) {
7526                            /*
7527                             * TODO this seems dangerous as the package may have
7528                             * changed since we last acquired the mPackages
7529                             * lock.
7530                             */
7531                            // writer
7532                            synchronized (mPackages) {
7533                                updatePermissionsLPw(p.packageName, p,
7534                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7535                            }
7536                            addedPackage = p.applicationInfo.packageName;
7537                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7538                        }
7539                    }
7540                }
7541
7542                // reader
7543                synchronized (mPackages) {
7544                    mSettings.writeLPr();
7545                }
7546            }
7547
7548            if (removedPackage != null) {
7549                Bundle extras = new Bundle(1);
7550                extras.putInt(Intent.EXTRA_UID, removedAppId);
7551                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7552                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7553                        extras, null, null, removedUsers);
7554            }
7555            if (addedPackage != null) {
7556                Bundle extras = new Bundle(1);
7557                extras.putInt(Intent.EXTRA_UID, addedAppId);
7558                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7559                        extras, null, null, addedUsers);
7560            }
7561        }
7562
7563        private final String mRootDir;
7564        private final boolean mIsRom;
7565        private final boolean mIsPrivileged;
7566    }
7567
7568    /*
7569     * The old-style observer methods all just trampoline to the newer signature with
7570     * expanded install observer API.  The older API continues to work but does not
7571     * supply the additional details of the Observer2 API.
7572     */
7573
7574    /* Called when a downloaded package installation has been confirmed by the user */
7575    public void installPackage(
7576            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7577        installPackageEtc(packageURI, observer, null, flags, null);
7578    }
7579
7580    /* Called when a downloaded package installation has been confirmed by the user */
7581    @Override
7582    public void installPackage(
7583            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7584            final String installerPackageName) {
7585        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7586                installerPackageName, null, null, null);
7587    }
7588
7589    @Override
7590    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7591            int flags, String installerPackageName, Uri verificationURI,
7592            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7593        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7594                VerificationParams.NO_UID, manifestDigest);
7595        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7596                installerPackageName, verificationParams, encryptionParams);
7597    }
7598
7599    @Override
7600    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7601            IPackageInstallObserver observer, int flags, String installerPackageName,
7602            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7603        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7604                installerPackageName, verificationParams, encryptionParams);
7605    }
7606
7607    /*
7608     * And here are the "live" versions that take both observer arguments
7609     */
7610    public void installPackageEtc(
7611            final Uri packageURI, final IPackageInstallObserver observer,
7612            IPackageInstallObserver2 observer2, final int flags) {
7613        installPackageEtc(packageURI, observer, observer2, flags, null);
7614    }
7615
7616    public void installPackageEtc(
7617            final Uri packageURI, final IPackageInstallObserver observer,
7618            final IPackageInstallObserver2 observer2, final int flags,
7619            final String installerPackageName) {
7620        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7621                installerPackageName, null, null, null);
7622    }
7623
7624    @Override
7625    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7626            IPackageInstallObserver2 observer2,
7627            int flags, String installerPackageName, Uri verificationURI,
7628            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7629        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7630                VerificationParams.NO_UID, manifestDigest);
7631        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7632                installerPackageName, verificationParams, encryptionParams);
7633    }
7634
7635    /*
7636     * All of the installPackage...*() methods redirect to this one for the master implementation
7637     */
7638    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7639            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7640            int flags, String installerPackageName,
7641            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7642        if (observer == null && observer2 == null) {
7643            throw new IllegalArgumentException("No install observer supplied");
7644        }
7645        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7646                flags, installerPackageName, verificationParams, encryptionParams, null);
7647    }
7648
7649    @Override
7650    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7651            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7652            int flags, String installerPackageName,
7653            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7654            String packageAbiOverride) {
7655        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7656                null);
7657
7658        final int uid = Binder.getCallingUid();
7659        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7660            try {
7661                if (observer != null) {
7662                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7663                }
7664                if (observer2 != null) {
7665                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7666                }
7667            } catch (RemoteException re) {
7668            }
7669            return;
7670        }
7671
7672        UserHandle user;
7673        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7674            user = UserHandle.ALL;
7675        } else {
7676            user = new UserHandle(UserHandle.getUserId(uid));
7677        }
7678
7679        final int filteredFlags;
7680
7681        if (uid == Process.SHELL_UID || uid == 0) {
7682            if (DEBUG_INSTALL) {
7683                Slog.v(TAG, "Install from ADB");
7684            }
7685            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7686        } else {
7687            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7688        }
7689
7690        verificationParams.setInstallerUid(uid);
7691
7692        final Message msg = mHandler.obtainMessage(INIT_COPY);
7693        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7694                installerPackageName, verificationParams, encryptionParams, user,
7695                packageAbiOverride);
7696        mHandler.sendMessage(msg);
7697    }
7698
7699    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7700        Bundle extras = new Bundle(1);
7701        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7702
7703        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7704                packageName, extras, null, null, new int[] {userId});
7705        try {
7706            IActivityManager am = ActivityManagerNative.getDefault();
7707            final boolean isSystem =
7708                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7709            if (isSystem && am.isUserRunning(userId, false)) {
7710                // The just-installed/enabled app is bundled on the system, so presumed
7711                // to be able to run automatically without needing an explicit launch.
7712                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7713                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7714                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7715                        .setPackage(packageName);
7716                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7717                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7718            }
7719        } catch (RemoteException e) {
7720            // shouldn't happen
7721            Slog.w(TAG, "Unable to bootstrap installed package", e);
7722        }
7723    }
7724
7725    @Override
7726    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7727            int userId) {
7728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7729        PackageSetting pkgSetting;
7730        final int uid = Binder.getCallingUid();
7731        if (UserHandle.getUserId(uid) != userId) {
7732            mContext.enforceCallingOrSelfPermission(
7733                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7734                    "setApplicationBlockedSetting for user " + userId);
7735        }
7736
7737        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7738            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7739            return false;
7740        }
7741
7742        long callingId = Binder.clearCallingIdentity();
7743        try {
7744            boolean sendAdded = false;
7745            boolean sendRemoved = false;
7746            // writer
7747            synchronized (mPackages) {
7748                pkgSetting = mSettings.mPackages.get(packageName);
7749                if (pkgSetting == null) {
7750                    return false;
7751                }
7752                if (pkgSetting.getBlocked(userId) != blocked) {
7753                    pkgSetting.setBlocked(blocked, userId);
7754                    mSettings.writePackageRestrictionsLPr(userId);
7755                    if (blocked) {
7756                        sendRemoved = true;
7757                    } else {
7758                        sendAdded = true;
7759                    }
7760                }
7761            }
7762            if (sendAdded) {
7763                sendPackageAddedForUser(packageName, pkgSetting, userId);
7764                return true;
7765            }
7766            if (sendRemoved) {
7767                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7768                        "blocking pkg");
7769                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7770            }
7771        } finally {
7772            Binder.restoreCallingIdentity(callingId);
7773        }
7774        return false;
7775    }
7776
7777    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7778            int userId) {
7779        final PackageRemovedInfo info = new PackageRemovedInfo();
7780        info.removedPackage = packageName;
7781        info.removedUsers = new int[] {userId};
7782        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7783        info.sendBroadcast(false, false, false);
7784    }
7785
7786    /**
7787     * Returns true if application is not found or there was an error. Otherwise it returns
7788     * the blocked state of the package for the given user.
7789     */
7790    @Override
7791    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7792        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7793        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7794                "getApplicationBlocked for user " + userId);
7795        PackageSetting pkgSetting;
7796        long callingId = Binder.clearCallingIdentity();
7797        try {
7798            // writer
7799            synchronized (mPackages) {
7800                pkgSetting = mSettings.mPackages.get(packageName);
7801                if (pkgSetting == null) {
7802                    return true;
7803                }
7804                return pkgSetting.getBlocked(userId);
7805            }
7806        } finally {
7807            Binder.restoreCallingIdentity(callingId);
7808        }
7809    }
7810
7811    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7812            int flags) {
7813        // TODO: install stage!
7814        try {
7815            observer.packageInstalled(basePackageName, null,
7816                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7817        } catch (RemoteException ignored) {
7818        }
7819    }
7820
7821    /**
7822     * @hide
7823     */
7824    @Override
7825    public int installExistingPackageAsUser(String packageName, int userId) {
7826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7827                null);
7828        PackageSetting pkgSetting;
7829        final int uid = Binder.getCallingUid();
7830        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7831        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7832            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7833        }
7834
7835        long callingId = Binder.clearCallingIdentity();
7836        try {
7837            boolean sendAdded = false;
7838            Bundle extras = new Bundle(1);
7839
7840            // writer
7841            synchronized (mPackages) {
7842                pkgSetting = mSettings.mPackages.get(packageName);
7843                if (pkgSetting == null) {
7844                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7845                }
7846                if (!pkgSetting.getInstalled(userId)) {
7847                    pkgSetting.setInstalled(true, userId);
7848                    pkgSetting.setBlocked(false, userId);
7849                    mSettings.writePackageRestrictionsLPr(userId);
7850                    sendAdded = true;
7851                }
7852            }
7853
7854            if (sendAdded) {
7855                sendPackageAddedForUser(packageName, pkgSetting, userId);
7856            }
7857        } finally {
7858            Binder.restoreCallingIdentity(callingId);
7859        }
7860
7861        return PackageManager.INSTALL_SUCCEEDED;
7862    }
7863
7864    boolean isUserRestricted(int userId, String restrictionKey) {
7865        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7866        if (restrictions.getBoolean(restrictionKey, false)) {
7867            Log.w(TAG, "User is restricted: " + restrictionKey);
7868            return true;
7869        }
7870        return false;
7871    }
7872
7873    @Override
7874    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7875        mContext.enforceCallingOrSelfPermission(
7876                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7877                "Only package verification agents can verify applications");
7878
7879        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7880        final PackageVerificationResponse response = new PackageVerificationResponse(
7881                verificationCode, Binder.getCallingUid());
7882        msg.arg1 = id;
7883        msg.obj = response;
7884        mHandler.sendMessage(msg);
7885    }
7886
7887    @Override
7888    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7889            long millisecondsToDelay) {
7890        mContext.enforceCallingOrSelfPermission(
7891                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7892                "Only package verification agents can extend verification timeouts");
7893
7894        final PackageVerificationState state = mPendingVerification.get(id);
7895        final PackageVerificationResponse response = new PackageVerificationResponse(
7896                verificationCodeAtTimeout, Binder.getCallingUid());
7897
7898        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7899            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7900        }
7901        if (millisecondsToDelay < 0) {
7902            millisecondsToDelay = 0;
7903        }
7904        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7905                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7906            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7907        }
7908
7909        if ((state != null) && !state.timeoutExtended()) {
7910            state.extendTimeout();
7911
7912            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7913            msg.arg1 = id;
7914            msg.obj = response;
7915            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7916        }
7917    }
7918
7919    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7920            int verificationCode, UserHandle user) {
7921        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7922        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7923        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7924        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7925        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7926
7927        mContext.sendBroadcastAsUser(intent, user,
7928                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7929    }
7930
7931    private ComponentName matchComponentForVerifier(String packageName,
7932            List<ResolveInfo> receivers) {
7933        ActivityInfo targetReceiver = null;
7934
7935        final int NR = receivers.size();
7936        for (int i = 0; i < NR; i++) {
7937            final ResolveInfo info = receivers.get(i);
7938            if (info.activityInfo == null) {
7939                continue;
7940            }
7941
7942            if (packageName.equals(info.activityInfo.packageName)) {
7943                targetReceiver = info.activityInfo;
7944                break;
7945            }
7946        }
7947
7948        if (targetReceiver == null) {
7949            return null;
7950        }
7951
7952        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7953    }
7954
7955    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7956            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7957        if (pkgInfo.verifiers.length == 0) {
7958            return null;
7959        }
7960
7961        final int N = pkgInfo.verifiers.length;
7962        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7963        for (int i = 0; i < N; i++) {
7964            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7965
7966            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7967                    receivers);
7968            if (comp == null) {
7969                continue;
7970            }
7971
7972            final int verifierUid = getUidForVerifier(verifierInfo);
7973            if (verifierUid == -1) {
7974                continue;
7975            }
7976
7977            if (DEBUG_VERIFY) {
7978                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7979                        + " with the correct signature");
7980            }
7981            sufficientVerifiers.add(comp);
7982            verificationState.addSufficientVerifier(verifierUid);
7983        }
7984
7985        return sufficientVerifiers;
7986    }
7987
7988    private int getUidForVerifier(VerifierInfo verifierInfo) {
7989        synchronized (mPackages) {
7990            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7991            if (pkg == null) {
7992                return -1;
7993            } else if (pkg.mSignatures.length != 1) {
7994                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7995                        + " has more than one signature; ignoring");
7996                return -1;
7997            }
7998
7999            /*
8000             * If the public key of the package's signature does not match
8001             * our expected public key, then this is a different package and
8002             * we should skip.
8003             */
8004
8005            final byte[] expectedPublicKey;
8006            try {
8007                final Signature verifierSig = pkg.mSignatures[0];
8008                final PublicKey publicKey = verifierSig.getPublicKey();
8009                expectedPublicKey = publicKey.getEncoded();
8010            } catch (CertificateException e) {
8011                return -1;
8012            }
8013
8014            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8015
8016            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8017                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8018                        + " does not have the expected public key; ignoring");
8019                return -1;
8020            }
8021
8022            return pkg.applicationInfo.uid;
8023        }
8024    }
8025
8026    @Override
8027    public void finishPackageInstall(int token) {
8028        enforceSystemOrRoot("Only the system is allowed to finish installs");
8029
8030        if (DEBUG_INSTALL) {
8031            Slog.v(TAG, "BM finishing package install for " + token);
8032        }
8033
8034        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8035        mHandler.sendMessage(msg);
8036    }
8037
8038    /**
8039     * Get the verification agent timeout.
8040     *
8041     * @return verification timeout in milliseconds
8042     */
8043    private long getVerificationTimeout() {
8044        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8045                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8046                DEFAULT_VERIFICATION_TIMEOUT);
8047    }
8048
8049    /**
8050     * Get the default verification agent response code.
8051     *
8052     * @return default verification response code
8053     */
8054    private int getDefaultVerificationResponse() {
8055        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8056                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8057                DEFAULT_VERIFICATION_RESPONSE);
8058    }
8059
8060    /**
8061     * Check whether or not package verification has been enabled.
8062     *
8063     * @return true if verification should be performed
8064     */
8065    private boolean isVerificationEnabled(int flags) {
8066        if (!DEFAULT_VERIFY_ENABLE) {
8067            return false;
8068        }
8069
8070        // Check if installing from ADB
8071        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8072            // Do not run verification in a test harness environment
8073            if (ActivityManager.isRunningInTestHarness()) {
8074                return false;
8075            }
8076            // Check if the developer does not want package verification for ADB installs
8077            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8078                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8079                return false;
8080            }
8081        }
8082
8083        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8084                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8085    }
8086
8087    /**
8088     * Get the "allow unknown sources" setting.
8089     *
8090     * @return the current "allow unknown sources" setting
8091     */
8092    private int getUnknownSourcesSettings() {
8093        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8094                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8095                -1);
8096    }
8097
8098    @Override
8099    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8100        final int uid = Binder.getCallingUid();
8101        // writer
8102        synchronized (mPackages) {
8103            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8104            if (targetPackageSetting == null) {
8105                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8106            }
8107
8108            PackageSetting installerPackageSetting;
8109            if (installerPackageName != null) {
8110                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8111                if (installerPackageSetting == null) {
8112                    throw new IllegalArgumentException("Unknown installer package: "
8113                            + installerPackageName);
8114                }
8115            } else {
8116                installerPackageSetting = null;
8117            }
8118
8119            Signature[] callerSignature;
8120            Object obj = mSettings.getUserIdLPr(uid);
8121            if (obj != null) {
8122                if (obj instanceof SharedUserSetting) {
8123                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8124                } else if (obj instanceof PackageSetting) {
8125                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8126                } else {
8127                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8128                }
8129            } else {
8130                throw new SecurityException("Unknown calling uid " + uid);
8131            }
8132
8133            // Verify: can't set installerPackageName to a package that is
8134            // not signed with the same cert as the caller.
8135            if (installerPackageSetting != null) {
8136                if (compareSignatures(callerSignature,
8137                        installerPackageSetting.signatures.mSignatures)
8138                        != PackageManager.SIGNATURE_MATCH) {
8139                    throw new SecurityException(
8140                            "Caller does not have same cert as new installer package "
8141                            + installerPackageName);
8142                }
8143            }
8144
8145            // Verify: if target already has an installer package, it must
8146            // be signed with the same cert as the caller.
8147            if (targetPackageSetting.installerPackageName != null) {
8148                PackageSetting setting = mSettings.mPackages.get(
8149                        targetPackageSetting.installerPackageName);
8150                // If the currently set package isn't valid, then it's always
8151                // okay to change it.
8152                if (setting != null) {
8153                    if (compareSignatures(callerSignature,
8154                            setting.signatures.mSignatures)
8155                            != PackageManager.SIGNATURE_MATCH) {
8156                        throw new SecurityException(
8157                                "Caller does not have same cert as old installer package "
8158                                + targetPackageSetting.installerPackageName);
8159                    }
8160                }
8161            }
8162
8163            // Okay!
8164            targetPackageSetting.installerPackageName = installerPackageName;
8165            scheduleWriteSettingsLocked();
8166        }
8167    }
8168
8169    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8170        // Queue up an async operation since the package installation may take a little while.
8171        mHandler.post(new Runnable() {
8172            public void run() {
8173                mHandler.removeCallbacks(this);
8174                 // Result object to be returned
8175                PackageInstalledInfo res = new PackageInstalledInfo();
8176                res.returnCode = currentStatus;
8177                res.uid = -1;
8178                res.pkg = null;
8179                res.removedInfo = new PackageRemovedInfo();
8180                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8181                    args.doPreInstall(res.returnCode);
8182                    synchronized (mInstallLock) {
8183                        installPackageLI(args, true, res);
8184                    }
8185                    args.doPostInstall(res.returnCode, res.uid);
8186                }
8187
8188                // A restore should be performed at this point if (a) the install
8189                // succeeded, (b) the operation is not an update, and (c) the new
8190                // package has a backupAgent defined.
8191                final boolean update = res.removedInfo.removedPackage != null;
8192                boolean doRestore = (!update
8193                        && res.pkg != null
8194                        && res.pkg.applicationInfo.backupAgentName != null);
8195
8196                // Set up the post-install work request bookkeeping.  This will be used
8197                // and cleaned up by the post-install event handling regardless of whether
8198                // there's a restore pass performed.  Token values are >= 1.
8199                int token;
8200                if (mNextInstallToken < 0) mNextInstallToken = 1;
8201                token = mNextInstallToken++;
8202
8203                PostInstallData data = new PostInstallData(args, res);
8204                mRunningInstalls.put(token, data);
8205                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8206
8207                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8208                    // Pass responsibility to the Backup Manager.  It will perform a
8209                    // restore if appropriate, then pass responsibility back to the
8210                    // Package Manager to run the post-install observer callbacks
8211                    // and broadcasts.
8212                    IBackupManager bm = IBackupManager.Stub.asInterface(
8213                            ServiceManager.getService(Context.BACKUP_SERVICE));
8214                    if (bm != null) {
8215                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8216                                + " to BM for possible restore");
8217                        try {
8218                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8219                        } catch (RemoteException e) {
8220                            // can't happen; the backup manager is local
8221                        } catch (Exception e) {
8222                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8223                            doRestore = false;
8224                        }
8225                    } else {
8226                        Slog.e(TAG, "Backup Manager not found!");
8227                        doRestore = false;
8228                    }
8229                }
8230
8231                if (!doRestore) {
8232                    // No restore possible, or the Backup Manager was mysteriously not
8233                    // available -- just fire the post-install work request directly.
8234                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8235                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8236                    mHandler.sendMessage(msg);
8237                }
8238            }
8239        });
8240    }
8241
8242    private abstract class HandlerParams {
8243        private static final int MAX_RETRIES = 4;
8244
8245        /**
8246         * Number of times startCopy() has been attempted and had a non-fatal
8247         * error.
8248         */
8249        private int mRetries = 0;
8250
8251        /** User handle for the user requesting the information or installation. */
8252        private final UserHandle mUser;
8253
8254        HandlerParams(UserHandle user) {
8255            mUser = user;
8256        }
8257
8258        UserHandle getUser() {
8259            return mUser;
8260        }
8261
8262        final boolean startCopy() {
8263            boolean res;
8264            try {
8265                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8266
8267                if (++mRetries > MAX_RETRIES) {
8268                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8269                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8270                    handleServiceError();
8271                    return false;
8272                } else {
8273                    handleStartCopy();
8274                    res = true;
8275                }
8276            } catch (RemoteException e) {
8277                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8278                mHandler.sendEmptyMessage(MCS_RECONNECT);
8279                res = false;
8280            }
8281            handleReturnCode();
8282            return res;
8283        }
8284
8285        final void serviceError() {
8286            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8287            handleServiceError();
8288            handleReturnCode();
8289        }
8290
8291        abstract void handleStartCopy() throws RemoteException;
8292        abstract void handleServiceError();
8293        abstract void handleReturnCode();
8294    }
8295
8296    class MeasureParams extends HandlerParams {
8297        private final PackageStats mStats;
8298        private boolean mSuccess;
8299
8300        private final IPackageStatsObserver mObserver;
8301
8302        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8303            super(new UserHandle(stats.userHandle));
8304            mObserver = observer;
8305            mStats = stats;
8306        }
8307
8308        @Override
8309        public String toString() {
8310            return "MeasureParams{"
8311                + Integer.toHexString(System.identityHashCode(this))
8312                + " " + mStats.packageName + "}";
8313        }
8314
8315        @Override
8316        void handleStartCopy() throws RemoteException {
8317            synchronized (mInstallLock) {
8318                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8319            }
8320
8321            if (mSuccess) {
8322                final boolean mounted;
8323                if (Environment.isExternalStorageEmulated()) {
8324                    mounted = true;
8325                } else {
8326                    final String status = Environment.getExternalStorageState();
8327                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8328                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8329                }
8330
8331                if (mounted) {
8332                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8333
8334                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8335                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8336
8337                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8338                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8339
8340                    // Always subtract cache size, since it's a subdirectory
8341                    mStats.externalDataSize -= mStats.externalCacheSize;
8342
8343                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8344                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8345
8346                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8347                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8348                }
8349            }
8350        }
8351
8352        @Override
8353        void handleReturnCode() {
8354            if (mObserver != null) {
8355                try {
8356                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8357                } catch (RemoteException e) {
8358                    Slog.i(TAG, "Observer no longer exists.");
8359                }
8360            }
8361        }
8362
8363        @Override
8364        void handleServiceError() {
8365            Slog.e(TAG, "Could not measure application " + mStats.packageName
8366                            + " external storage");
8367        }
8368    }
8369
8370    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8371            throws RemoteException {
8372        long result = 0;
8373        for (File path : paths) {
8374            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8375        }
8376        return result;
8377    }
8378
8379    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8380        for (File path : paths) {
8381            try {
8382                mcs.clearDirectory(path.getAbsolutePath());
8383            } catch (RemoteException e) {
8384            }
8385        }
8386    }
8387
8388    class InstallParams extends HandlerParams {
8389        final IPackageInstallObserver observer;
8390        final IPackageInstallObserver2 observer2;
8391        int flags;
8392
8393        private final Uri mPackageURI;
8394        final String installerPackageName;
8395        final VerificationParams verificationParams;
8396        private InstallArgs mArgs;
8397        private int mRet;
8398        private File mTempPackage;
8399        final ContainerEncryptionParams encryptionParams;
8400        final String packageAbiOverride;
8401        final String packageInstructionSetOverride;
8402
8403        InstallParams(Uri packageURI,
8404                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8405                int flags, String installerPackageName, VerificationParams verificationParams,
8406                ContainerEncryptionParams encryptionParams, UserHandle user,
8407                String packageAbiOverride) {
8408            super(user);
8409            this.mPackageURI = packageURI;
8410            this.flags = flags;
8411            this.observer = observer;
8412            this.observer2 = observer2;
8413            this.installerPackageName = installerPackageName;
8414            this.verificationParams = verificationParams;
8415            this.encryptionParams = encryptionParams;
8416            this.packageAbiOverride = packageAbiOverride;
8417            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8418                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8419        }
8420
8421        @Override
8422        public String toString() {
8423            return "InstallParams{"
8424                + Integer.toHexString(System.identityHashCode(this))
8425                + " " + mPackageURI + "}";
8426        }
8427
8428        public ManifestDigest getManifestDigest() {
8429            if (verificationParams == null) {
8430                return null;
8431            }
8432            return verificationParams.getManifestDigest();
8433        }
8434
8435        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8436            String packageName = pkgLite.packageName;
8437            int installLocation = pkgLite.installLocation;
8438            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8439            // reader
8440            synchronized (mPackages) {
8441                PackageParser.Package pkg = mPackages.get(packageName);
8442                if (pkg != null) {
8443                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8444                        // Check for downgrading.
8445                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8446                            if (pkgLite.versionCode < pkg.mVersionCode) {
8447                                Slog.w(TAG, "Can't install update of " + packageName
8448                                        + " update version " + pkgLite.versionCode
8449                                        + " is older than installed version "
8450                                        + pkg.mVersionCode);
8451                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8452                            }
8453                        }
8454                        // Check for updated system application.
8455                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8456                            if (onSd) {
8457                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8458                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8459                            }
8460                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8461                        } else {
8462                            if (onSd) {
8463                                // Install flag overrides everything.
8464                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8465                            }
8466                            // If current upgrade specifies particular preference
8467                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8468                                // Application explicitly specified internal.
8469                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8470                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8471                                // App explictly prefers external. Let policy decide
8472                            } else {
8473                                // Prefer previous location
8474                                if (isExternal(pkg)) {
8475                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8476                                }
8477                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8478                            }
8479                        }
8480                    } else {
8481                        // Invalid install. Return error code
8482                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8483                    }
8484                }
8485            }
8486            // All the special cases have been taken care of.
8487            // Return result based on recommended install location.
8488            if (onSd) {
8489                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8490            }
8491            return pkgLite.recommendedInstallLocation;
8492        }
8493
8494        private long getMemoryLowThreshold() {
8495            final DeviceStorageMonitorInternal
8496                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8497            if (dsm == null) {
8498                return 0L;
8499            }
8500            return dsm.getMemoryLowThreshold();
8501        }
8502
8503        /*
8504         * Invoke remote method to get package information and install
8505         * location values. Override install location based on default
8506         * policy if needed and then create install arguments based
8507         * on the install location.
8508         */
8509        public void handleStartCopy() throws RemoteException {
8510            int ret = PackageManager.INSTALL_SUCCEEDED;
8511            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8512            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8513            PackageInfoLite pkgLite = null;
8514
8515            if (onInt && onSd) {
8516                // Check if both bits are set.
8517                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8518                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8519            } else {
8520                final long lowThreshold = getMemoryLowThreshold();
8521                if (lowThreshold == 0L) {
8522                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8523                }
8524
8525                try {
8526                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8527                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8528
8529                    final File packageFile;
8530                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8531                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8532                        if (mTempPackage != null) {
8533                            ParcelFileDescriptor out;
8534                            try {
8535                                out = ParcelFileDescriptor.open(mTempPackage,
8536                                        ParcelFileDescriptor.MODE_READ_WRITE);
8537                            } catch (FileNotFoundException e) {
8538                                out = null;
8539                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8540                            }
8541
8542                            // Make a temporary file for decryption.
8543                            ret = mContainerService
8544                                    .copyResource(mPackageURI, encryptionParams, out);
8545                            IoUtils.closeQuietly(out);
8546
8547                            packageFile = mTempPackage;
8548
8549                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8550                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8551                                            | FileUtils.S_IROTH,
8552                                    -1, -1);
8553                        } else {
8554                            packageFile = null;
8555                        }
8556                    } else {
8557                        packageFile = new File(mPackageURI.getPath());
8558                    }
8559
8560                    if (packageFile != null) {
8561                        // Remote call to find out default install location
8562                        final String packageFilePath = packageFile.getAbsolutePath();
8563                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8564                                lowThreshold, packageAbiOverride);
8565
8566                        /*
8567                         * If we have too little free space, try to free cache
8568                         * before giving up.
8569                         */
8570                        if (pkgLite.recommendedInstallLocation
8571                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8572                            final long size = mContainerService.calculateInstalledSize(
8573                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8574                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8575                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8576                                        flags, lowThreshold, packageAbiOverride);
8577                            }
8578                            /*
8579                             * The cache free must have deleted the file we
8580                             * downloaded to install.
8581                             *
8582                             * TODO: fix the "freeCache" call to not delete
8583                             *       the file we care about.
8584                             */
8585                            if (pkgLite.recommendedInstallLocation
8586                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8587                                pkgLite.recommendedInstallLocation
8588                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8589                            }
8590                        }
8591                    }
8592                } finally {
8593                    mContext.revokeUriPermission(mPackageURI,
8594                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8595                }
8596            }
8597
8598            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8599                int loc = pkgLite.recommendedInstallLocation;
8600                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8601                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8602                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8603                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8604                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8605                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8606                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8607                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8608                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8609                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8610                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8611                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8612                } else {
8613                    // Override with defaults if needed.
8614                    loc = installLocationPolicy(pkgLite, flags);
8615                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8616                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8617                    } else if (!onSd && !onInt) {
8618                        // Override install location with flags
8619                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8620                            // Set the flag to install on external media.
8621                            flags |= PackageManager.INSTALL_EXTERNAL;
8622                            flags &= ~PackageManager.INSTALL_INTERNAL;
8623                        } else {
8624                            // Make sure the flag for installing on external
8625                            // media is unset
8626                            flags |= PackageManager.INSTALL_INTERNAL;
8627                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8628                        }
8629                    }
8630                }
8631            }
8632
8633            final InstallArgs args = createInstallArgs(this);
8634            mArgs = args;
8635
8636            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8637                 /*
8638                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8639                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8640                 */
8641                int userIdentifier = getUser().getIdentifier();
8642                if (userIdentifier == UserHandle.USER_ALL
8643                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8644                    userIdentifier = UserHandle.USER_OWNER;
8645                }
8646
8647                /*
8648                 * Determine if we have any installed package verifiers. If we
8649                 * do, then we'll defer to them to verify the packages.
8650                 */
8651                final int requiredUid = mRequiredVerifierPackage == null ? -1
8652                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8653                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8654                    final Intent verification = new Intent(
8655                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8656                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8657                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8658
8659                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8660                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8661                            0 /* TODO: Which userId? */);
8662
8663                    if (DEBUG_VERIFY) {
8664                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8665                                + verification.toString() + " with " + pkgLite.verifiers.length
8666                                + " optional verifiers");
8667                    }
8668
8669                    final int verificationId = mPendingVerificationToken++;
8670
8671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8672
8673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8674                            installerPackageName);
8675
8676                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8677
8678                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8679                            pkgLite.packageName);
8680
8681                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8682                            pkgLite.versionCode);
8683
8684                    if (verificationParams != null) {
8685                        if (verificationParams.getVerificationURI() != null) {
8686                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8687                                 verificationParams.getVerificationURI());
8688                        }
8689                        if (verificationParams.getOriginatingURI() != null) {
8690                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8691                                  verificationParams.getOriginatingURI());
8692                        }
8693                        if (verificationParams.getReferrer() != null) {
8694                            verification.putExtra(Intent.EXTRA_REFERRER,
8695                                  verificationParams.getReferrer());
8696                        }
8697                        if (verificationParams.getOriginatingUid() >= 0) {
8698                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8699                                  verificationParams.getOriginatingUid());
8700                        }
8701                        if (verificationParams.getInstallerUid() >= 0) {
8702                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8703                                  verificationParams.getInstallerUid());
8704                        }
8705                    }
8706
8707                    final PackageVerificationState verificationState = new PackageVerificationState(
8708                            requiredUid, args);
8709
8710                    mPendingVerification.append(verificationId, verificationState);
8711
8712                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8713                            receivers, verificationState);
8714
8715                    /*
8716                     * If any sufficient verifiers were listed in the package
8717                     * manifest, attempt to ask them.
8718                     */
8719                    if (sufficientVerifiers != null) {
8720                        final int N = sufficientVerifiers.size();
8721                        if (N == 0) {
8722                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8723                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8724                        } else {
8725                            for (int i = 0; i < N; i++) {
8726                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8727
8728                                final Intent sufficientIntent = new Intent(verification);
8729                                sufficientIntent.setComponent(verifierComponent);
8730
8731                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8732                            }
8733                        }
8734                    }
8735
8736                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8737                            mRequiredVerifierPackage, receivers);
8738                    if (ret == PackageManager.INSTALL_SUCCEEDED
8739                            && mRequiredVerifierPackage != null) {
8740                        /*
8741                         * Send the intent to the required verification agent,
8742                         * but only start the verification timeout after the
8743                         * target BroadcastReceivers have run.
8744                         */
8745                        verification.setComponent(requiredVerifierComponent);
8746                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8747                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8748                                new BroadcastReceiver() {
8749                                    @Override
8750                                    public void onReceive(Context context, Intent intent) {
8751                                        final Message msg = mHandler
8752                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8753                                        msg.arg1 = verificationId;
8754                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8755                                    }
8756                                }, null, 0, null, null);
8757
8758                        /*
8759                         * We don't want the copy to proceed until verification
8760                         * succeeds, so null out this field.
8761                         */
8762                        mArgs = null;
8763                    }
8764                } else {
8765                    /*
8766                     * No package verification is enabled, so immediately start
8767                     * the remote call to initiate copy using temporary file.
8768                     */
8769                    ret = args.copyApk(mContainerService, true);
8770                }
8771            }
8772
8773            mRet = ret;
8774        }
8775
8776        @Override
8777        void handleReturnCode() {
8778            // If mArgs is null, then MCS couldn't be reached. When it
8779            // reconnects, it will try again to install. At that point, this
8780            // will succeed.
8781            if (mArgs != null) {
8782                processPendingInstall(mArgs, mRet);
8783
8784                if (mTempPackage != null) {
8785                    if (!mTempPackage.delete()) {
8786                        Slog.w(TAG, "Couldn't delete temporary file: " +
8787                                mTempPackage.getAbsolutePath());
8788                    }
8789                }
8790            }
8791        }
8792
8793        @Override
8794        void handleServiceError() {
8795            mArgs = createInstallArgs(this);
8796            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8797        }
8798
8799        public boolean isForwardLocked() {
8800            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8801        }
8802
8803        public Uri getPackageUri() {
8804            if (mTempPackage != null) {
8805                return Uri.fromFile(mTempPackage);
8806            } else {
8807                return mPackageURI;
8808            }
8809        }
8810    }
8811
8812    /*
8813     * Utility class used in movePackage api.
8814     * srcArgs and targetArgs are not set for invalid flags and make
8815     * sure to do null checks when invoking methods on them.
8816     * We probably want to return ErrorPrams for both failed installs
8817     * and moves.
8818     */
8819    class MoveParams extends HandlerParams {
8820        final IPackageMoveObserver observer;
8821        final int flags;
8822        final String packageName;
8823        final InstallArgs srcArgs;
8824        final InstallArgs targetArgs;
8825        int uid;
8826        int mRet;
8827
8828        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8829                String packageName, String dataDir, String instructionSet,
8830                int uid, UserHandle user) {
8831            super(user);
8832            this.srcArgs = srcArgs;
8833            this.observer = observer;
8834            this.flags = flags;
8835            this.packageName = packageName;
8836            this.uid = uid;
8837            if (srcArgs != null) {
8838                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8839                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8840            } else {
8841                targetArgs = null;
8842            }
8843        }
8844
8845        @Override
8846        public String toString() {
8847            return "MoveParams{"
8848                + Integer.toHexString(System.identityHashCode(this))
8849                + " " + packageName + "}";
8850        }
8851
8852        public void handleStartCopy() throws RemoteException {
8853            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8854            // Check for storage space on target medium
8855            if (!targetArgs.checkFreeStorage(mContainerService)) {
8856                Log.w(TAG, "Insufficient storage to install");
8857                return;
8858            }
8859
8860            mRet = srcArgs.doPreCopy();
8861            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8862                return;
8863            }
8864
8865            mRet = targetArgs.copyApk(mContainerService, false);
8866            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8867                srcArgs.doPostCopy(uid);
8868                return;
8869            }
8870
8871            mRet = srcArgs.doPostCopy(uid);
8872            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8873                return;
8874            }
8875
8876            mRet = targetArgs.doPreInstall(mRet);
8877            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8878                return;
8879            }
8880
8881            if (DEBUG_SD_INSTALL) {
8882                StringBuilder builder = new StringBuilder();
8883                if (srcArgs != null) {
8884                    builder.append("src: ");
8885                    builder.append(srcArgs.getCodePath());
8886                }
8887                if (targetArgs != null) {
8888                    builder.append(" target : ");
8889                    builder.append(targetArgs.getCodePath());
8890                }
8891                Log.i(TAG, builder.toString());
8892            }
8893        }
8894
8895        @Override
8896        void handleReturnCode() {
8897            targetArgs.doPostInstall(mRet, uid);
8898            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8899            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8900                currentStatus = PackageManager.MOVE_SUCCEEDED;
8901            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8902                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8903            }
8904            processPendingMove(this, currentStatus);
8905        }
8906
8907        @Override
8908        void handleServiceError() {
8909            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8910        }
8911    }
8912
8913    /**
8914     * Used during creation of InstallArgs
8915     *
8916     * @param flags package installation flags
8917     * @return true if should be installed on external storage
8918     */
8919    private static boolean installOnSd(int flags) {
8920        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8921            return false;
8922        }
8923        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8924            return true;
8925        }
8926        return false;
8927    }
8928
8929    /**
8930     * Used during creation of InstallArgs
8931     *
8932     * @param flags package installation flags
8933     * @return true if should be installed as forward locked
8934     */
8935    private static boolean installForwardLocked(int flags) {
8936        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8937    }
8938
8939    private InstallArgs createInstallArgs(InstallParams params) {
8940        if (installOnSd(params.flags) || params.isForwardLocked()) {
8941            return new AsecInstallArgs(params);
8942        } else {
8943            return new FileInstallArgs(params);
8944        }
8945    }
8946
8947    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8948            String nativeLibraryPath, String instructionSet) {
8949        final boolean isInAsec;
8950        if (installOnSd(flags)) {
8951            /* Apps on SD card are always in ASEC containers. */
8952            isInAsec = true;
8953        } else if (installForwardLocked(flags)
8954                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8955            /*
8956             * Forward-locked apps are only in ASEC containers if they're the
8957             * new style
8958             */
8959            isInAsec = true;
8960        } else {
8961            isInAsec = false;
8962        }
8963
8964        if (isInAsec) {
8965            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8966                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8967        } else {
8968            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8969                    instructionSet);
8970        }
8971    }
8972
8973    // Used by package mover
8974    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8975            String instructionSet) {
8976        if (installOnSd(flags) || installForwardLocked(flags)) {
8977            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8978                    + AsecInstallArgs.RES_FILE_NAME);
8979            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8980                    installForwardLocked(flags));
8981        } else {
8982            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8983        }
8984    }
8985
8986    static abstract class InstallArgs {
8987        final IPackageInstallObserver observer;
8988        final IPackageInstallObserver2 observer2;
8989        // Always refers to PackageManager flags only
8990        final int flags;
8991        final Uri packageURI;
8992        final String installerPackageName;
8993        final ManifestDigest manifestDigest;
8994        final UserHandle user;
8995        final String instructionSet;
8996        final String abiOverride;
8997
8998        InstallArgs(Uri packageURI,
8999                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
9000                int flags, String installerPackageName, ManifestDigest manifestDigest,
9001                UserHandle user, String instructionSet, String abiOverride) {
9002            this.packageURI = packageURI;
9003            this.flags = flags;
9004            this.observer = observer;
9005            this.observer2 = observer2;
9006            this.installerPackageName = installerPackageName;
9007            this.manifestDigest = manifestDigest;
9008            this.user = user;
9009            this.instructionSet = instructionSet;
9010            this.abiOverride = abiOverride;
9011        }
9012
9013        abstract void createCopyFile();
9014        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9015        abstract int doPreInstall(int status);
9016        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9017
9018        abstract int doPostInstall(int status, int uid);
9019        abstract String getCodePath();
9020        abstract String getResourcePath();
9021        abstract String getNativeLibraryPath();
9022        // Need installer lock especially for dex file removal.
9023        abstract void cleanUpResourcesLI();
9024        abstract boolean doPostDeleteLI(boolean delete);
9025        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9026
9027        /**
9028         * Called before the source arguments are copied. This is used mostly
9029         * for MoveParams when it needs to read the source file to put it in the
9030         * destination.
9031         */
9032        int doPreCopy() {
9033            return PackageManager.INSTALL_SUCCEEDED;
9034        }
9035
9036        /**
9037         * Called after the source arguments are copied. This is used mostly for
9038         * MoveParams when it needs to read the source file to put it in the
9039         * destination.
9040         *
9041         * @return
9042         */
9043        int doPostCopy(int uid) {
9044            return PackageManager.INSTALL_SUCCEEDED;
9045        }
9046
9047        protected boolean isFwdLocked() {
9048            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9049        }
9050
9051        UserHandle getUser() {
9052            return user;
9053        }
9054    }
9055
9056    class FileInstallArgs extends InstallArgs {
9057        File installDir;
9058        String codeFileName;
9059        String resourceFileName;
9060        String libraryPath;
9061        boolean created = false;
9062
9063        FileInstallArgs(InstallParams params) {
9064            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9065                    params.installerPackageName, params.getManifestDigest(),
9066                    params.getUser(), params.packageInstructionSetOverride,
9067                    params.packageAbiOverride);
9068        }
9069
9070        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9071                String instructionSet) {
9072            super(null, null, null, 0, null, null, null, instructionSet, null);
9073            File codeFile = new File(fullCodePath);
9074            installDir = codeFile.getParentFile();
9075            codeFileName = fullCodePath;
9076            resourceFileName = fullResourcePath;
9077            libraryPath = nativeLibraryPath;
9078        }
9079
9080        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9081            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9082            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9083            String apkName = getNextCodePath(null, pkgName, ".apk");
9084            codeFileName = new File(installDir, apkName + ".apk").getPath();
9085            resourceFileName = getResourcePathFromCodePath();
9086            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9087        }
9088
9089        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9090            final long lowThreshold;
9091
9092            final DeviceStorageMonitorInternal
9093                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9094            if (dsm == null) {
9095                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9096                lowThreshold = 0L;
9097            } else {
9098                if (dsm.isMemoryLow()) {
9099                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9100                    return false;
9101                }
9102
9103                lowThreshold = dsm.getMemoryLowThreshold();
9104            }
9105
9106            try {
9107                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9108                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9109                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9110            } finally {
9111                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9112            }
9113        }
9114
9115        String getCodePath() {
9116            return codeFileName;
9117        }
9118
9119        void createCopyFile() {
9120            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9121            codeFileName = createTempPackageFile(installDir).getPath();
9122            resourceFileName = getResourcePathFromCodePath();
9123            libraryPath = getLibraryPathFromCodePath();
9124            created = true;
9125        }
9126
9127        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9128            if (temp) {
9129                // Generate temp file name
9130                createCopyFile();
9131            }
9132            // Get a ParcelFileDescriptor to write to the output file
9133            File codeFile = new File(codeFileName);
9134            if (!created) {
9135                try {
9136                    codeFile.createNewFile();
9137                    // Set permissions
9138                    if (!setPermissions()) {
9139                        // Failed setting permissions.
9140                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9141                    }
9142                } catch (IOException e) {
9143                   Slog.w(TAG, "Failed to create file " + codeFile);
9144                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9145                }
9146            }
9147            ParcelFileDescriptor out = null;
9148            try {
9149                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9150            } catch (FileNotFoundException e) {
9151                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9152                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9153            }
9154            // Copy the resource now
9155            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9156            try {
9157                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9158                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9159                ret = imcs.copyResource(packageURI, null, out);
9160            } finally {
9161                IoUtils.closeQuietly(out);
9162                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9163            }
9164
9165            if (isFwdLocked()) {
9166                final File destResourceFile = new File(getResourcePath());
9167
9168                // Copy the public files
9169                try {
9170                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9171                } catch (IOException e) {
9172                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9173                            + " forward-locked app.");
9174                    destResourceFile.delete();
9175                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9176                }
9177            }
9178
9179            final File nativeLibraryFile = new File(getNativeLibraryPath());
9180            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9181            if (nativeLibraryFile.exists()) {
9182                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9183                nativeLibraryFile.delete();
9184            }
9185
9186            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9187            String[] abiList = (abiOverride != null) ?
9188                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9189            try {
9190                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9191                        abiOverride == null &&
9192                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9193                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9194                }
9195
9196                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9197                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9198                    return copyRet;
9199                }
9200            } catch (IOException e) {
9201                Slog.e(TAG, "Copying native libraries failed", e);
9202                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9203            } finally {
9204                handle.close();
9205            }
9206
9207            return ret;
9208        }
9209
9210        int doPreInstall(int status) {
9211            if (status != PackageManager.INSTALL_SUCCEEDED) {
9212                cleanUp();
9213            }
9214            return status;
9215        }
9216
9217        boolean doRename(int status, final String pkgName, String oldCodePath) {
9218            if (status != PackageManager.INSTALL_SUCCEEDED) {
9219                cleanUp();
9220                return false;
9221            } else {
9222                final File oldCodeFile = new File(getCodePath());
9223                final File oldResourceFile = new File(getResourcePath());
9224                final File oldLibraryFile = new File(getNativeLibraryPath());
9225
9226                // Rename APK file based on packageName
9227                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9228                final File newCodeFile = new File(installDir, apkName + ".apk");
9229                if (!oldCodeFile.renameTo(newCodeFile)) {
9230                    return false;
9231                }
9232                codeFileName = newCodeFile.getPath();
9233
9234                // Rename public resource file if it's forward-locked.
9235                final File newResFile = new File(getResourcePathFromCodePath());
9236                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9237                    return false;
9238                }
9239                resourceFileName = newResFile.getPath();
9240
9241                // Rename library path
9242                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9243                if (newLibraryFile.exists()) {
9244                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9245                    newLibraryFile.delete();
9246                }
9247                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9248                    Slog.e(TAG, "Cannot rename native library directory "
9249                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9250                    return false;
9251                }
9252                libraryPath = newLibraryFile.getPath();
9253
9254                // Attempt to set permissions
9255                if (!setPermissions()) {
9256                    return false;
9257                }
9258
9259                if (!SELinux.restorecon(newCodeFile)) {
9260                    return false;
9261                }
9262
9263                return true;
9264            }
9265        }
9266
9267        int doPostInstall(int status, int uid) {
9268            if (status != PackageManager.INSTALL_SUCCEEDED) {
9269                cleanUp();
9270            }
9271            return status;
9272        }
9273
9274        String getResourcePath() {
9275            return resourceFileName;
9276        }
9277
9278        private String getResourcePathFromCodePath() {
9279            final String codePath = getCodePath();
9280            if (isFwdLocked()) {
9281                final StringBuilder sb = new StringBuilder();
9282
9283                sb.append(mAppInstallDir.getPath());
9284                sb.append('/');
9285                sb.append(getApkName(codePath));
9286                sb.append(".zip");
9287
9288                /*
9289                 * If our APK is a temporary file, mark the resource as a
9290                 * temporary file as well so it can be cleaned up after
9291                 * catastrophic failure.
9292                 */
9293                if (codePath.endsWith(".tmp")) {
9294                    sb.append(".tmp");
9295                }
9296
9297                return sb.toString();
9298            } else {
9299                return codePath;
9300            }
9301        }
9302
9303        private String getLibraryPathFromCodePath() {
9304            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9305        }
9306
9307        @Override
9308        String getNativeLibraryPath() {
9309            if (libraryPath == null) {
9310                libraryPath = getLibraryPathFromCodePath();
9311            }
9312            return libraryPath;
9313        }
9314
9315        private boolean cleanUp() {
9316            boolean ret = true;
9317            String sourceDir = getCodePath();
9318            String publicSourceDir = getResourcePath();
9319            if (sourceDir != null) {
9320                File sourceFile = new File(sourceDir);
9321                if (!sourceFile.exists()) {
9322                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9323                    ret = false;
9324                }
9325                // Delete application's code and resources
9326                sourceFile.delete();
9327            }
9328            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9329                final File publicSourceFile = new File(publicSourceDir);
9330                if (!publicSourceFile.exists()) {
9331                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9332                }
9333                if (publicSourceFile.exists()) {
9334                    publicSourceFile.delete();
9335                }
9336            }
9337
9338            if (libraryPath != null) {
9339                File nativeLibraryFile = new File(libraryPath);
9340                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9341                if (!nativeLibraryFile.delete()) {
9342                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9343                }
9344            }
9345
9346            return ret;
9347        }
9348
9349        void cleanUpResourcesLI() {
9350            String sourceDir = getCodePath();
9351            if (cleanUp()) {
9352                if (instructionSet == null) {
9353                    throw new IllegalStateException("instructionSet == null");
9354                }
9355                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9356                if (retCode < 0) {
9357                    Slog.w(TAG, "Couldn't remove dex file for package: "
9358                            +  " at location "
9359                            + sourceDir + ", retcode=" + retCode);
9360                    // we don't consider this to be a failure of the core package deletion
9361                }
9362            }
9363        }
9364
9365        private boolean setPermissions() {
9366            // TODO Do this in a more elegant way later on. for now just a hack
9367            if (!isFwdLocked()) {
9368                final int filePermissions =
9369                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9370                    |FileUtils.S_IROTH;
9371                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9372                if (retCode != 0) {
9373                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9374                            getCodePath()
9375                            + ". The return code was: " + retCode);
9376                    // TODO Define new internal error
9377                    return false;
9378                }
9379                return true;
9380            }
9381            return true;
9382        }
9383
9384        boolean doPostDeleteLI(boolean delete) {
9385            // XXX err, shouldn't we respect the delete flag?
9386            cleanUpResourcesLI();
9387            return true;
9388        }
9389    }
9390
9391    private boolean isAsecExternal(String cid) {
9392        final String asecPath = PackageHelper.getSdFilesystem(cid);
9393        return !asecPath.startsWith(mAsecInternalPath);
9394    }
9395
9396    /**
9397     * Extract the MountService "container ID" from the full code path of an
9398     * .apk.
9399     */
9400    static String cidFromCodePath(String fullCodePath) {
9401        int eidx = fullCodePath.lastIndexOf("/");
9402        String subStr1 = fullCodePath.substring(0, eidx);
9403        int sidx = subStr1.lastIndexOf("/");
9404        return subStr1.substring(sidx+1, eidx);
9405    }
9406
9407    class AsecInstallArgs extends InstallArgs {
9408        static final String RES_FILE_NAME = "pkg.apk";
9409        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9410
9411        String cid;
9412        String packagePath;
9413        String resourcePath;
9414        String libraryPath;
9415
9416        AsecInstallArgs(InstallParams params) {
9417            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9418                    params.installerPackageName, params.getManifestDigest(),
9419                    params.getUser(), params.packageInstructionSetOverride,
9420                    params.packageAbiOverride);
9421        }
9422
9423        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9424                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9425            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9426                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9427                    null, null, null, instructionSet, null);
9428            // Extract cid from fullCodePath
9429            int eidx = fullCodePath.lastIndexOf("/");
9430            String subStr1 = fullCodePath.substring(0, eidx);
9431            int sidx = subStr1.lastIndexOf("/");
9432            cid = subStr1.substring(sidx+1, eidx);
9433            setCachePath(subStr1);
9434        }
9435
9436        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9437            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9438                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9439                    null, null, null, instructionSet, null);
9440            this.cid = cid;
9441            setCachePath(PackageHelper.getSdDir(cid));
9442        }
9443
9444        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9445                boolean isExternal, boolean isForwardLocked) {
9446            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9447                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9448                    null, null, null, instructionSet, null);
9449            this.cid = cid;
9450        }
9451
9452        void createCopyFile() {
9453            cid = getTempContainerId();
9454        }
9455
9456        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9457            try {
9458                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9459                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9460                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9461            } finally {
9462                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9463            }
9464        }
9465
9466        private final boolean isExternal() {
9467            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9468        }
9469
9470        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9471            if (temp) {
9472                createCopyFile();
9473            } else {
9474                /*
9475                 * Pre-emptively destroy the container since it's destroyed if
9476                 * copying fails due to it existing anyway.
9477                 */
9478                PackageHelper.destroySdDir(cid);
9479            }
9480
9481            final String newCachePath;
9482            try {
9483                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9484                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9485                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9486                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9487                        abiOverride);
9488            } finally {
9489                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9490            }
9491
9492            if (newCachePath != null) {
9493                setCachePath(newCachePath);
9494                return PackageManager.INSTALL_SUCCEEDED;
9495            } else {
9496                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9497            }
9498        }
9499
9500        @Override
9501        String getCodePath() {
9502            return packagePath;
9503        }
9504
9505        @Override
9506        String getResourcePath() {
9507            return resourcePath;
9508        }
9509
9510        @Override
9511        String getNativeLibraryPath() {
9512            return libraryPath;
9513        }
9514
9515        int doPreInstall(int status) {
9516            if (status != PackageManager.INSTALL_SUCCEEDED) {
9517                // Destroy container
9518                PackageHelper.destroySdDir(cid);
9519            } else {
9520                boolean mounted = PackageHelper.isContainerMounted(cid);
9521                if (!mounted) {
9522                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9523                            Process.SYSTEM_UID);
9524                    if (newCachePath != null) {
9525                        setCachePath(newCachePath);
9526                    } else {
9527                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9528                    }
9529                }
9530            }
9531            return status;
9532        }
9533
9534        boolean doRename(int status, final String pkgName,
9535                String oldCodePath) {
9536            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9537            String newCachePath = null;
9538            if (PackageHelper.isContainerMounted(cid)) {
9539                // Unmount the container
9540                if (!PackageHelper.unMountSdDir(cid)) {
9541                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9542                    return false;
9543                }
9544            }
9545            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9546                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9547                        " which might be stale. Will try to clean up.");
9548                // Clean up the stale container and proceed to recreate.
9549                if (!PackageHelper.destroySdDir(newCacheId)) {
9550                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9551                    return false;
9552                }
9553                // Successfully cleaned up stale container. Try to rename again.
9554                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9555                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9556                            + " inspite of cleaning it up.");
9557                    return false;
9558                }
9559            }
9560            if (!PackageHelper.isContainerMounted(newCacheId)) {
9561                Slog.w(TAG, "Mounting container " + newCacheId);
9562                newCachePath = PackageHelper.mountSdDir(newCacheId,
9563                        getEncryptKey(), Process.SYSTEM_UID);
9564            } else {
9565                newCachePath = PackageHelper.getSdDir(newCacheId);
9566            }
9567            if (newCachePath == null) {
9568                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9569                return false;
9570            }
9571            Log.i(TAG, "Succesfully renamed " + cid +
9572                    " to " + newCacheId +
9573                    " at new path: " + newCachePath);
9574            cid = newCacheId;
9575            setCachePath(newCachePath);
9576            return true;
9577        }
9578
9579        private void setCachePath(String newCachePath) {
9580            File cachePath = new File(newCachePath);
9581            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9582            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9583
9584            if (isFwdLocked()) {
9585                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9586            } else {
9587                resourcePath = packagePath;
9588            }
9589        }
9590
9591        int doPostInstall(int status, int uid) {
9592            if (status != PackageManager.INSTALL_SUCCEEDED) {
9593                cleanUp();
9594            } else {
9595                final int groupOwner;
9596                final String protectedFile;
9597                if (isFwdLocked()) {
9598                    groupOwner = UserHandle.getSharedAppGid(uid);
9599                    protectedFile = RES_FILE_NAME;
9600                } else {
9601                    groupOwner = -1;
9602                    protectedFile = null;
9603                }
9604
9605                if (uid < Process.FIRST_APPLICATION_UID
9606                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9607                    Slog.e(TAG, "Failed to finalize " + cid);
9608                    PackageHelper.destroySdDir(cid);
9609                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9610                }
9611
9612                boolean mounted = PackageHelper.isContainerMounted(cid);
9613                if (!mounted) {
9614                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9615                }
9616            }
9617            return status;
9618        }
9619
9620        private void cleanUp() {
9621            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9622
9623            // Destroy secure container
9624            PackageHelper.destroySdDir(cid);
9625        }
9626
9627        void cleanUpResourcesLI() {
9628            String sourceFile = getCodePath();
9629            // Remove dex file
9630            if (instructionSet == null) {
9631                throw new IllegalStateException("instructionSet == null");
9632            }
9633            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9634            if (retCode < 0) {
9635                Slog.w(TAG, "Couldn't remove dex file for package: "
9636                        + " at location "
9637                        + sourceFile.toString() + ", retcode=" + retCode);
9638                // we don't consider this to be a failure of the core package deletion
9639            }
9640            cleanUp();
9641        }
9642
9643        boolean matchContainer(String app) {
9644            if (cid.startsWith(app)) {
9645                return true;
9646            }
9647            return false;
9648        }
9649
9650        String getPackageName() {
9651            return getAsecPackageName(cid);
9652        }
9653
9654        boolean doPostDeleteLI(boolean delete) {
9655            boolean ret = false;
9656            boolean mounted = PackageHelper.isContainerMounted(cid);
9657            if (mounted) {
9658                // Unmount first
9659                ret = PackageHelper.unMountSdDir(cid);
9660            }
9661            if (ret && delete) {
9662                cleanUpResourcesLI();
9663            }
9664            return ret;
9665        }
9666
9667        @Override
9668        int doPreCopy() {
9669            if (isFwdLocked()) {
9670                if (!PackageHelper.fixSdPermissions(cid,
9671                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9672                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9673                }
9674            }
9675
9676            return PackageManager.INSTALL_SUCCEEDED;
9677        }
9678
9679        @Override
9680        int doPostCopy(int uid) {
9681            if (isFwdLocked()) {
9682                if (uid < Process.FIRST_APPLICATION_UID
9683                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9684                                RES_FILE_NAME)) {
9685                    Slog.e(TAG, "Failed to finalize " + cid);
9686                    PackageHelper.destroySdDir(cid);
9687                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9688                }
9689            }
9690
9691            return PackageManager.INSTALL_SUCCEEDED;
9692        }
9693    };
9694
9695    static String getAsecPackageName(String packageCid) {
9696        int idx = packageCid.lastIndexOf("-");
9697        if (idx == -1) {
9698            return packageCid;
9699        }
9700        return packageCid.substring(0, idx);
9701    }
9702
9703    // Utility method used to create code paths based on package name and available index.
9704    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9705        String idxStr = "";
9706        int idx = 1;
9707        // Fall back to default value of idx=1 if prefix is not
9708        // part of oldCodePath
9709        if (oldCodePath != null) {
9710            String subStr = oldCodePath;
9711            // Drop the suffix right away
9712            if (subStr.endsWith(suffix)) {
9713                subStr = subStr.substring(0, subStr.length() - suffix.length());
9714            }
9715            // If oldCodePath already contains prefix find out the
9716            // ending index to either increment or decrement.
9717            int sidx = subStr.lastIndexOf(prefix);
9718            if (sidx != -1) {
9719                subStr = subStr.substring(sidx + prefix.length());
9720                if (subStr != null) {
9721                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9722                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9723                    }
9724                    try {
9725                        idx = Integer.parseInt(subStr);
9726                        if (idx <= 1) {
9727                            idx++;
9728                        } else {
9729                            idx--;
9730                        }
9731                    } catch(NumberFormatException e) {
9732                    }
9733                }
9734            }
9735        }
9736        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9737        return prefix + idxStr;
9738    }
9739
9740    // Utility method used to ignore ADD/REMOVE events
9741    // by directory observer.
9742    private static boolean ignoreCodePath(String fullPathStr) {
9743        String apkName = getApkName(fullPathStr);
9744        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9745        if (idx != -1 && ((idx+1) < apkName.length())) {
9746            // Make sure the package ends with a numeral
9747            String version = apkName.substring(idx+1);
9748            try {
9749                Integer.parseInt(version);
9750                return true;
9751            } catch (NumberFormatException e) {}
9752        }
9753        return false;
9754    }
9755
9756    // Utility method that returns the relative package path with respect
9757    // to the installation directory. Like say for /data/data/com.test-1.apk
9758    // string com.test-1 is returned.
9759    static String getApkName(String codePath) {
9760        if (codePath == null) {
9761            return null;
9762        }
9763        int sidx = codePath.lastIndexOf("/");
9764        int eidx = codePath.lastIndexOf(".");
9765        if (eidx == -1) {
9766            eidx = codePath.length();
9767        } else if (eidx == 0) {
9768            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9769            return null;
9770        }
9771        return codePath.substring(sidx+1, eidx);
9772    }
9773
9774    class PackageInstalledInfo {
9775        String name;
9776        int uid;
9777        // The set of users that originally had this package installed.
9778        int[] origUsers;
9779        // The set of users that now have this package installed.
9780        int[] newUsers;
9781        PackageParser.Package pkg;
9782        int returnCode;
9783        PackageRemovedInfo removedInfo;
9784
9785        // In some error cases we want to convey more info back to the observer
9786        String origPackage;
9787        String origPermission;
9788    }
9789
9790    /*
9791     * Install a non-existing package.
9792     */
9793    private void installNewPackageLI(PackageParser.Package pkg,
9794            int parseFlags, int scanMode, UserHandle user,
9795            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9796        // Remember this for later, in case we need to rollback this install
9797        String pkgName = pkg.packageName;
9798
9799        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9800        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9801        synchronized(mPackages) {
9802            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9803                // A package with the same name is already installed, though
9804                // it has been renamed to an older name.  The package we
9805                // are trying to install should be installed as an update to
9806                // the existing one, but that has not been requested, so bail.
9807                Slog.w(TAG, "Attempt to re-install " + pkgName
9808                        + " without first uninstalling package running as "
9809                        + mSettings.mRenamedPackages.get(pkgName));
9810                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9811                return;
9812            }
9813            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9814                // Don't allow installation over an existing package with the same name.
9815                Slog.w(TAG, "Attempt to re-install " + pkgName
9816                        + " without first uninstalling.");
9817                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9818                return;
9819            }
9820        }
9821        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9822        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9823                System.currentTimeMillis(), user, abiOverride);
9824        if (newPackage == null) {
9825            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9826            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9827                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9828            }
9829        } else {
9830            updateSettingsLI(newPackage,
9831                    installerPackageName,
9832                    null, null,
9833                    res);
9834            // delete the partially installed application. the data directory will have to be
9835            // restored if it was already existing
9836            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9837                // remove package from internal structures.  Note that we want deletePackageX to
9838                // delete the package data and cache directories that it created in
9839                // scanPackageLocked, unless those directories existed before we even tried to
9840                // install.
9841                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9842                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9843                                res.removedInfo, true);
9844            }
9845        }
9846    }
9847
9848    private void replacePackageLI(PackageParser.Package pkg,
9849            int parseFlags, int scanMode, UserHandle user,
9850            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9851
9852        PackageParser.Package oldPackage;
9853        String pkgName = pkg.packageName;
9854        int[] allUsers;
9855        boolean[] perUserInstalled;
9856
9857        // First find the old package info and check signatures
9858        synchronized(mPackages) {
9859            oldPackage = mPackages.get(pkgName);
9860            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9861            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9862                    != PackageManager.SIGNATURE_MATCH) {
9863                Slog.w(TAG, "New package has a different signature: " + pkgName);
9864                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9865                return;
9866            }
9867
9868            // In case of rollback, remember per-user/profile install state
9869            PackageSetting ps = mSettings.mPackages.get(pkgName);
9870            allUsers = sUserManager.getUserIds();
9871            perUserInstalled = new boolean[allUsers.length];
9872            for (int i = 0; i < allUsers.length; i++) {
9873                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9874            }
9875        }
9876        boolean sysPkg = (isSystemApp(oldPackage));
9877        if (sysPkg) {
9878            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9879                    user, allUsers, perUserInstalled, installerPackageName, res,
9880                    abiOverride);
9881        } else {
9882            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9883                    user, allUsers, perUserInstalled, installerPackageName, res,
9884                    abiOverride);
9885        }
9886    }
9887
9888    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9889            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9890            int[] allUsers, boolean[] perUserInstalled,
9891            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9892        PackageParser.Package newPackage = null;
9893        String pkgName = deletedPackage.packageName;
9894        boolean deletedPkg = true;
9895        boolean updatedSettings = false;
9896
9897        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9898                + deletedPackage);
9899        long origUpdateTime;
9900        if (pkg.mExtras != null) {
9901            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9902        } else {
9903            origUpdateTime = 0;
9904        }
9905
9906        // First delete the existing package while retaining the data directory
9907        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9908                res.removedInfo, true)) {
9909            // If the existing package wasn't successfully deleted
9910            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9911            deletedPkg = false;
9912        } else {
9913            // Successfully deleted the old package. Now proceed with re-installation
9914            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9915            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9916                    System.currentTimeMillis(), user, abiOverride);
9917            if (newPackage == null) {
9918                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9919                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9920                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9921                }
9922            } else {
9923                updateSettingsLI(newPackage,
9924                        installerPackageName,
9925                        allUsers, perUserInstalled,
9926                        res);
9927                updatedSettings = true;
9928            }
9929        }
9930
9931        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9932            // remove package from internal structures.  Note that we want deletePackageX to
9933            // delete the package data and cache directories that it created in
9934            // scanPackageLocked, unless those directories existed before we even tried to
9935            // install.
9936            if(updatedSettings) {
9937                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9938                deletePackageLI(
9939                        pkgName, null, true, allUsers, perUserInstalled,
9940                        PackageManager.DELETE_KEEP_DATA,
9941                                res.removedInfo, true);
9942            }
9943            // Since we failed to install the new package we need to restore the old
9944            // package that we deleted.
9945            if (deletedPkg) {
9946                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9947                File restoreFile = new File(deletedPackage.mPath);
9948                // Parse old package
9949                boolean oldOnSd = isExternal(deletedPackage);
9950                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9951                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9952                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9953                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9954                        | SCAN_UPDATE_TIME;
9955                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9956                        origUpdateTime, null, null) == null) {
9957                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9958                    return;
9959                }
9960                // Restore of old package succeeded. Update permissions.
9961                // writer
9962                synchronized (mPackages) {
9963                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9964                            UPDATE_PERMISSIONS_ALL);
9965                    // can downgrade to reader
9966                    mSettings.writeLPr();
9967                }
9968                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9969            }
9970        }
9971    }
9972
9973    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9974            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9975            int[] allUsers, boolean[] perUserInstalled,
9976            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9977        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9978                + ", old=" + deletedPackage);
9979        PackageParser.Package newPackage = null;
9980        boolean updatedSettings = false;
9981        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9982                PackageParser.PARSE_IS_SYSTEM;
9983        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9984            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9985        }
9986        String packageName = deletedPackage.packageName;
9987        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9988        if (packageName == null) {
9989            Slog.w(TAG, "Attempt to delete null packageName.");
9990            return;
9991        }
9992        PackageParser.Package oldPkg;
9993        PackageSetting oldPkgSetting;
9994        // reader
9995        synchronized (mPackages) {
9996            oldPkg = mPackages.get(packageName);
9997            oldPkgSetting = mSettings.mPackages.get(packageName);
9998            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9999                    (oldPkgSetting == null)) {
10000                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10001                return;
10002            }
10003        }
10004
10005        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10006
10007        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10008        res.removedInfo.removedPackage = packageName;
10009        // Remove existing system package
10010        removePackageLI(oldPkgSetting, true);
10011        // writer
10012        synchronized (mPackages) {
10013            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10014                // We didn't need to disable the .apk as a current system package,
10015                // which means we are replacing another update that is already
10016                // installed.  We need to make sure to delete the older one's .apk.
10017                res.removedInfo.args = createInstallArgs(0,
10018                        deletedPackage.applicationInfo.sourceDir,
10019                        deletedPackage.applicationInfo.publicSourceDir,
10020                        deletedPackage.applicationInfo.nativeLibraryDir,
10021                        getAppInstructionSet(deletedPackage.applicationInfo));
10022            } else {
10023                res.removedInfo.args = null;
10024            }
10025        }
10026
10027        // Successfully disabled the old package. Now proceed with re-installation
10028        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10029        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10030        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10031        if (newPackage == null) {
10032            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
10033            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10034                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10035            }
10036        } else {
10037            if (newPackage.mExtras != null) {
10038                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10039                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10040                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10041
10042                // is the update attempting to change shared user? that isn't going to work...
10043                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10044                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10045                            + " to " + newPkgSetting.sharedUser);
10046                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10047                    updatedSettings = true;
10048                }
10049            }
10050
10051            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10052                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10053                updatedSettings = true;
10054            }
10055        }
10056
10057        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10058            // Re installation failed. Restore old information
10059            // Remove new pkg information
10060            if (newPackage != null) {
10061                removeInstalledPackageLI(newPackage, true);
10062            }
10063            // Add back the old system package
10064            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10065            // Restore the old system information in Settings
10066            synchronized(mPackages) {
10067                if (updatedSettings) {
10068                    mSettings.enableSystemPackageLPw(packageName);
10069                    mSettings.setInstallerPackageName(packageName,
10070                            oldPkgSetting.installerPackageName);
10071                }
10072                mSettings.writeLPr();
10073            }
10074        }
10075    }
10076
10077    // Utility method used to move dex files during install.
10078    private int moveDexFilesLI(PackageParser.Package newPackage) {
10079        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10080            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10081            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
10082                                             instructionSet);
10083            if (retCode != 0) {
10084                /*
10085                 * Programs may be lazily run through dexopt, so the
10086                 * source may not exist. However, something seems to
10087                 * have gone wrong, so note that dexopt needs to be
10088                 * run again and remove the source file. In addition,
10089                 * remove the target to make sure there isn't a stale
10090                 * file from a previous version of the package.
10091                 */
10092                newPackage.mDexOptNeeded = true;
10093                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
10094                mInstaller.rmdex(newPackage.mPath, instructionSet);
10095            }
10096        }
10097        return PackageManager.INSTALL_SUCCEEDED;
10098    }
10099
10100    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10101            int[] allUsers, boolean[] perUserInstalled,
10102            PackageInstalledInfo res) {
10103        String pkgName = newPackage.packageName;
10104        synchronized (mPackages) {
10105            //write settings. the installStatus will be incomplete at this stage.
10106            //note that the new package setting would have already been
10107            //added to mPackages. It hasn't been persisted yet.
10108            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10109            mSettings.writeLPr();
10110        }
10111
10112        if ((res.returnCode = moveDexFilesLI(newPackage))
10113                != PackageManager.INSTALL_SUCCEEDED) {
10114            // Discontinue if moving dex files failed.
10115            return;
10116        }
10117
10118        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
10119
10120        synchronized (mPackages) {
10121            updatePermissionsLPw(newPackage.packageName, newPackage,
10122                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10123                            ? UPDATE_PERMISSIONS_ALL : 0));
10124            // For system-bundled packages, we assume that installing an upgraded version
10125            // of the package implies that the user actually wants to run that new code,
10126            // so we enable the package.
10127            if (isSystemApp(newPackage)) {
10128                // NB: implicit assumption that system package upgrades apply to all users
10129                if (DEBUG_INSTALL) {
10130                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10131                }
10132                PackageSetting ps = mSettings.mPackages.get(pkgName);
10133                if (ps != null) {
10134                    if (res.origUsers != null) {
10135                        for (int userHandle : res.origUsers) {
10136                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10137                                    userHandle, installerPackageName);
10138                        }
10139                    }
10140                    // Also convey the prior install/uninstall state
10141                    if (allUsers != null && perUserInstalled != null) {
10142                        for (int i = 0; i < allUsers.length; i++) {
10143                            if (DEBUG_INSTALL) {
10144                                Slog.d(TAG, "    user " + allUsers[i]
10145                                        + " => " + perUserInstalled[i]);
10146                            }
10147                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10148                        }
10149                        // these install state changes will be persisted in the
10150                        // upcoming call to mSettings.writeLPr().
10151                    }
10152                }
10153            }
10154            res.name = pkgName;
10155            res.uid = newPackage.applicationInfo.uid;
10156            res.pkg = newPackage;
10157            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10158            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10159            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10160            //to update install status
10161            mSettings.writeLPr();
10162        }
10163    }
10164
10165    private void installPackageLI(InstallArgs args,
10166            boolean newInstall, PackageInstalledInfo res) {
10167        int pFlags = args.flags;
10168        String installerPackageName = args.installerPackageName;
10169        File tmpPackageFile = new File(args.getCodePath());
10170        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10171        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10172        boolean replace = false;
10173        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10174                | (newInstall ? SCAN_NEW_INSTALL : 0);
10175        // Result object to be returned
10176        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10177
10178        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10179        // Retrieve PackageSettings and parse package
10180        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10181                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10182                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10183        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10184        pp.setSeparateProcesses(mSeparateProcesses);
10185        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10186                null, mMetrics, parseFlags);
10187        if (pkg == null) {
10188            res.returnCode = pp.getParseError();
10189            return;
10190        }
10191        String pkgName = res.name = pkg.packageName;
10192        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10193            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10194                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10195                return;
10196            }
10197        }
10198        if (!pp.collectCertificates(pkg, parseFlags)) {
10199            res.returnCode = pp.getParseError();
10200            return;
10201        }
10202
10203        /* If the installer passed in a manifest digest, compare it now. */
10204        if (args.manifestDigest != null) {
10205            if (DEBUG_INSTALL) {
10206                final String parsedManifest = pkg.manifestDigest == null ? "null"
10207                        : pkg.manifestDigest.toString();
10208                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10209                        + parsedManifest);
10210            }
10211
10212            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10213                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10214                return;
10215            }
10216        } else if (DEBUG_INSTALL) {
10217            final String parsedManifest = pkg.manifestDigest == null
10218                    ? "null" : pkg.manifestDigest.toString();
10219            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10220        }
10221
10222        // Get rid of all references to package scan path via parser.
10223        pp = null;
10224        String oldCodePath = null;
10225        boolean systemApp = false;
10226        synchronized (mPackages) {
10227            // Check whether the newly-scanned package wants to define an already-defined perm
10228            int N = pkg.permissions.size();
10229            for (int i = N-1; i >= 0; i--) {
10230                PackageParser.Permission perm = pkg.permissions.get(i);
10231                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10232                if (bp != null) {
10233                    // If the defining package is signed with our cert, it's okay.  This
10234                    // also includes the "updating the same package" case, of course.
10235                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10236                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10237                        // If the owning package is the system itself, we log but allow
10238                        // install to proceed; we fail the install on all other permission
10239                        // redefinitions.
10240                        if (!bp.sourcePackage.equals("android")) {
10241                            Slog.w(TAG, "Package " + pkg.packageName
10242                                    + " attempting to redeclare permission " + perm.info.name
10243                                    + " already owned by " + bp.sourcePackage);
10244                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10245                            res.origPermission = perm.info.name;
10246                            res.origPackage = bp.sourcePackage;
10247                            return;
10248                        } else {
10249                            Slog.w(TAG, "Package " + pkg.packageName
10250                                    + " attempting to redeclare system permission "
10251                                    + perm.info.name + "; ignoring new declaration");
10252                            pkg.permissions.remove(i);
10253                        }
10254                    }
10255                }
10256            }
10257
10258            // Check if installing already existing package
10259            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10260                String oldName = mSettings.mRenamedPackages.get(pkgName);
10261                if (pkg.mOriginalPackages != null
10262                        && pkg.mOriginalPackages.contains(oldName)
10263                        && mPackages.containsKey(oldName)) {
10264                    // This package is derived from an original package,
10265                    // and this device has been updating from that original
10266                    // name.  We must continue using the original name, so
10267                    // rename the new package here.
10268                    pkg.setPackageName(oldName);
10269                    pkgName = pkg.packageName;
10270                    replace = true;
10271                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10272                            + oldName + " pkgName=" + pkgName);
10273                } else if (mPackages.containsKey(pkgName)) {
10274                    // This package, under its official name, already exists
10275                    // on the device; we should replace it.
10276                    replace = true;
10277                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10278                }
10279            }
10280            PackageSetting ps = mSettings.mPackages.get(pkgName);
10281            if (ps != null) {
10282                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10283                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10284                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10285                    systemApp = (ps.pkg.applicationInfo.flags &
10286                            ApplicationInfo.FLAG_SYSTEM) != 0;
10287                }
10288                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10289            }
10290        }
10291
10292        if (systemApp && onSd) {
10293            // Disable updates to system apps on sdcard
10294            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10295            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10296            return;
10297        }
10298
10299        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10300            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10301            return;
10302        }
10303        // Set application objects path explicitly after the rename
10304        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10305        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10306        if (replace) {
10307            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10308                    installerPackageName, res, args.abiOverride);
10309        } else {
10310            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10311                    installerPackageName, res, args.abiOverride);
10312        }
10313        synchronized (mPackages) {
10314            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10315            if (ps != null) {
10316                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10317            }
10318        }
10319    }
10320
10321    private static boolean isForwardLocked(PackageParser.Package pkg) {
10322        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10323    }
10324
10325
10326    private boolean isForwardLocked(PackageSetting ps) {
10327        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10328    }
10329
10330    private static boolean isExternal(PackageParser.Package pkg) {
10331        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10332    }
10333
10334    private static boolean isExternal(PackageSetting ps) {
10335        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10336    }
10337
10338    private static boolean isSystemApp(PackageParser.Package pkg) {
10339        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10340    }
10341
10342    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10343        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10344    }
10345
10346    private static boolean isSystemApp(ApplicationInfo info) {
10347        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10348    }
10349
10350    private static boolean isSystemApp(PackageSetting ps) {
10351        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10352    }
10353
10354    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10355        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10356    }
10357
10358    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10359        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10360    }
10361
10362    private int packageFlagsToInstallFlags(PackageSetting ps) {
10363        int installFlags = 0;
10364        if (isExternal(ps)) {
10365            installFlags |= PackageManager.INSTALL_EXTERNAL;
10366        }
10367        if (isForwardLocked(ps)) {
10368            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10369        }
10370        return installFlags;
10371    }
10372
10373    private void deleteTempPackageFiles() {
10374        final FilenameFilter filter = new FilenameFilter() {
10375            public boolean accept(File dir, String name) {
10376                return name.startsWith("vmdl") && name.endsWith(".tmp");
10377            }
10378        };
10379        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10380        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10381    }
10382
10383    private static final void deleteTempPackageFilesInDirectory(File directory,
10384            FilenameFilter filter) {
10385        final String[] tmpFilesList = directory.list(filter);
10386        if (tmpFilesList == null) {
10387            return;
10388        }
10389        for (int i = 0; i < tmpFilesList.length; i++) {
10390            final File tmpFile = new File(directory, tmpFilesList[i]);
10391            tmpFile.delete();
10392        }
10393    }
10394
10395    private File createTempPackageFile(File installDir) {
10396        File tmpPackageFile;
10397        try {
10398            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10399        } catch (IOException e) {
10400            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10401            return null;
10402        }
10403        try {
10404            FileUtils.setPermissions(
10405                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10406                    -1, -1);
10407            if (!SELinux.restorecon(tmpPackageFile)) {
10408                return null;
10409            }
10410        } catch (IOException e) {
10411            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10412            return null;
10413        }
10414        return tmpPackageFile;
10415    }
10416
10417    @Override
10418    public void deletePackageAsUser(final String packageName,
10419                                    final IPackageDeleteObserver observer,
10420                                    final int userId, final int flags) {
10421        mContext.enforceCallingOrSelfPermission(
10422                android.Manifest.permission.DELETE_PACKAGES, null);
10423        final int uid = Binder.getCallingUid();
10424        if (UserHandle.getUserId(uid) != userId) {
10425            mContext.enforceCallingPermission(
10426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10427                    "deletePackage for user " + userId);
10428        }
10429        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10430            try {
10431                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10432            } catch (RemoteException re) {
10433            }
10434            return;
10435        }
10436
10437        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10438        // Queue up an async operation since the package deletion may take a little while.
10439        mHandler.post(new Runnable() {
10440            public void run() {
10441                mHandler.removeCallbacks(this);
10442                final int returnCode = deletePackageX(packageName, userId, flags);
10443                if (observer != null) {
10444                    try {
10445                        observer.packageDeleted(packageName, returnCode);
10446                    } catch (RemoteException e) {
10447                        Log.i(TAG, "Observer no longer exists.");
10448                    } //end catch
10449                } //end if
10450            } //end run
10451        });
10452    }
10453
10454    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10455        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10456                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10457        try {
10458            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10459                    || dpm.isDeviceOwner(packageName))) {
10460                return true;
10461            }
10462        } catch (RemoteException e) {
10463        }
10464        return false;
10465    }
10466
10467    /**
10468     *  This method is an internal method that could be get invoked either
10469     *  to delete an installed package or to clean up a failed installation.
10470     *  After deleting an installed package, a broadcast is sent to notify any
10471     *  listeners that the package has been installed. For cleaning up a failed
10472     *  installation, the broadcast is not necessary since the package's
10473     *  installation wouldn't have sent the initial broadcast either
10474     *  The key steps in deleting a package are
10475     *  deleting the package information in internal structures like mPackages,
10476     *  deleting the packages base directories through installd
10477     *  updating mSettings to reflect current status
10478     *  persisting settings for later use
10479     *  sending a broadcast if necessary
10480     */
10481    private int deletePackageX(String packageName, int userId, int flags) {
10482        final PackageRemovedInfo info = new PackageRemovedInfo();
10483        final boolean res;
10484
10485        if (isPackageDeviceAdmin(packageName, userId)) {
10486            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10487            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10488        }
10489
10490        boolean removedForAllUsers = false;
10491        boolean systemUpdate = false;
10492
10493        // for the uninstall-updates case and restricted profiles, remember the per-
10494        // userhandle installed state
10495        int[] allUsers;
10496        boolean[] perUserInstalled;
10497        synchronized (mPackages) {
10498            PackageSetting ps = mSettings.mPackages.get(packageName);
10499            allUsers = sUserManager.getUserIds();
10500            perUserInstalled = new boolean[allUsers.length];
10501            for (int i = 0; i < allUsers.length; i++) {
10502                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10503            }
10504        }
10505
10506        synchronized (mInstallLock) {
10507            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10508            res = deletePackageLI(packageName,
10509                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10510                            ? UserHandle.ALL : new UserHandle(userId),
10511                    true, allUsers, perUserInstalled,
10512                    flags | REMOVE_CHATTY, info, true);
10513            systemUpdate = info.isRemovedPackageSystemUpdate;
10514            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10515                removedForAllUsers = true;
10516            }
10517            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10518                    + " removedForAllUsers=" + removedForAllUsers);
10519        }
10520
10521        if (res) {
10522            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10523
10524            // If the removed package was a system update, the old system package
10525            // was re-enabled; we need to broadcast this information
10526            if (systemUpdate) {
10527                Bundle extras = new Bundle(1);
10528                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10529                        ? info.removedAppId : info.uid);
10530                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10531
10532                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10533                        extras, null, null, null);
10534                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10535                        extras, null, null, null);
10536                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10537                        null, packageName, null, null);
10538            }
10539        }
10540        // Force a gc here.
10541        Runtime.getRuntime().gc();
10542        // Delete the resources here after sending the broadcast to let
10543        // other processes clean up before deleting resources.
10544        if (info.args != null) {
10545            synchronized (mInstallLock) {
10546                info.args.doPostDeleteLI(true);
10547            }
10548        }
10549
10550        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10551    }
10552
10553    static class PackageRemovedInfo {
10554        String removedPackage;
10555        int uid = -1;
10556        int removedAppId = -1;
10557        int[] removedUsers = null;
10558        boolean isRemovedPackageSystemUpdate = false;
10559        // Clean up resources deleted packages.
10560        InstallArgs args = null;
10561
10562        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10563            Bundle extras = new Bundle(1);
10564            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10565            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10566            if (replacing) {
10567                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10568            }
10569            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10570            if (removedPackage != null) {
10571                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10572                        extras, null, null, removedUsers);
10573                if (fullRemove && !replacing) {
10574                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10575                            extras, null, null, removedUsers);
10576                }
10577            }
10578            if (removedAppId >= 0) {
10579                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10580                        removedUsers);
10581            }
10582        }
10583    }
10584
10585    /*
10586     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10587     * flag is not set, the data directory is removed as well.
10588     * make sure this flag is set for partially installed apps. If not its meaningless to
10589     * delete a partially installed application.
10590     */
10591    private void removePackageDataLI(PackageSetting ps,
10592            int[] allUserHandles, boolean[] perUserInstalled,
10593            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10594        String packageName = ps.name;
10595        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10596        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10597        // Retrieve object to delete permissions for shared user later on
10598        final PackageSetting deletedPs;
10599        // reader
10600        synchronized (mPackages) {
10601            deletedPs = mSettings.mPackages.get(packageName);
10602            if (outInfo != null) {
10603                outInfo.removedPackage = packageName;
10604                outInfo.removedUsers = deletedPs != null
10605                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10606                        : null;
10607            }
10608        }
10609        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10610            removeDataDirsLI(packageName);
10611            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10612        }
10613        // writer
10614        synchronized (mPackages) {
10615            if (deletedPs != null) {
10616                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10617                    if (outInfo != null) {
10618                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10619                    }
10620                    if (deletedPs != null) {
10621                        updatePermissionsLPw(deletedPs.name, null, 0);
10622                        if (deletedPs.sharedUser != null) {
10623                            // remove permissions associated with package
10624                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10625                        }
10626                    }
10627                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10628                }
10629                // make sure to preserve per-user disabled state if this removal was just
10630                // a downgrade of a system app to the factory package
10631                if (allUserHandles != null && perUserInstalled != null) {
10632                    if (DEBUG_REMOVE) {
10633                        Slog.d(TAG, "Propagating install state across downgrade");
10634                    }
10635                    for (int i = 0; i < allUserHandles.length; i++) {
10636                        if (DEBUG_REMOVE) {
10637                            Slog.d(TAG, "    user " + allUserHandles[i]
10638                                    + " => " + perUserInstalled[i]);
10639                        }
10640                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10641                    }
10642                }
10643            }
10644            // can downgrade to reader
10645            if (writeSettings) {
10646                // Save settings now
10647                mSettings.writeLPr();
10648            }
10649        }
10650        if (outInfo != null) {
10651            // A user ID was deleted here. Go through all users and remove it
10652            // from KeyStore.
10653            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10654        }
10655    }
10656
10657    static boolean locationIsPrivileged(File path) {
10658        try {
10659            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10660                    .getCanonicalPath();
10661            return path.getCanonicalPath().startsWith(privilegedAppDir);
10662        } catch (IOException e) {
10663            Slog.e(TAG, "Unable to access code path " + path);
10664        }
10665        return false;
10666    }
10667
10668    /*
10669     * Tries to delete system package.
10670     */
10671    private boolean deleteSystemPackageLI(PackageSetting newPs,
10672            int[] allUserHandles, boolean[] perUserInstalled,
10673            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10674        final boolean applyUserRestrictions
10675                = (allUserHandles != null) && (perUserInstalled != null);
10676        PackageSetting disabledPs = null;
10677        // Confirm if the system package has been updated
10678        // An updated system app can be deleted. This will also have to restore
10679        // the system pkg from system partition
10680        // reader
10681        synchronized (mPackages) {
10682            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10683        }
10684        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10685                + " disabledPs=" + disabledPs);
10686        if (disabledPs == null) {
10687            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10688            return false;
10689        } else if (DEBUG_REMOVE) {
10690            Slog.d(TAG, "Deleting system pkg from data partition");
10691        }
10692        if (DEBUG_REMOVE) {
10693            if (applyUserRestrictions) {
10694                Slog.d(TAG, "Remembering install states:");
10695                for (int i = 0; i < allUserHandles.length; i++) {
10696                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10697                }
10698            }
10699        }
10700        // Delete the updated package
10701        outInfo.isRemovedPackageSystemUpdate = true;
10702        if (disabledPs.versionCode < newPs.versionCode) {
10703            // Delete data for downgrades
10704            flags &= ~PackageManager.DELETE_KEEP_DATA;
10705        } else {
10706            // Preserve data by setting flag
10707            flags |= PackageManager.DELETE_KEEP_DATA;
10708        }
10709        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10710                allUserHandles, perUserInstalled, outInfo, writeSettings);
10711        if (!ret) {
10712            return false;
10713        }
10714        // writer
10715        synchronized (mPackages) {
10716            // Reinstate the old system package
10717            mSettings.enableSystemPackageLPw(newPs.name);
10718            // Remove any native libraries from the upgraded package.
10719            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10720        }
10721        // Install the system package
10722        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10723        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10724        if (locationIsPrivileged(disabledPs.codePath)) {
10725            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10726        }
10727        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10728                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10729
10730        if (newPkg == null) {
10731            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10732                    + " with error:" + mLastScanError);
10733            return false;
10734        }
10735        // writer
10736        synchronized (mPackages) {
10737            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10738            setInternalAppNativeLibraryPath(newPkg, ps);
10739            updatePermissionsLPw(newPkg.packageName, newPkg,
10740                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10741            if (applyUserRestrictions) {
10742                if (DEBUG_REMOVE) {
10743                    Slog.d(TAG, "Propagating install state across reinstall");
10744                }
10745                for (int i = 0; i < allUserHandles.length; i++) {
10746                    if (DEBUG_REMOVE) {
10747                        Slog.d(TAG, "    user " + allUserHandles[i]
10748                                + " => " + perUserInstalled[i]);
10749                    }
10750                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10751                }
10752                // Regardless of writeSettings we need to ensure that this restriction
10753                // state propagation is persisted
10754                mSettings.writeAllUsersPackageRestrictionsLPr();
10755            }
10756            // can downgrade to reader here
10757            if (writeSettings) {
10758                mSettings.writeLPr();
10759            }
10760        }
10761        return true;
10762    }
10763
10764    private boolean deleteInstalledPackageLI(PackageSetting ps,
10765            boolean deleteCodeAndResources, int flags,
10766            int[] allUserHandles, boolean[] perUserInstalled,
10767            PackageRemovedInfo outInfo, boolean writeSettings) {
10768        if (outInfo != null) {
10769            outInfo.uid = ps.appId;
10770        }
10771
10772        // Delete package data from internal structures and also remove data if flag is set
10773        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10774
10775        // Delete application code and resources
10776        if (deleteCodeAndResources && (outInfo != null)) {
10777            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10778                    ps.resourcePathString, ps.nativeLibraryPathString,
10779                    getAppInstructionSetFromSettings(ps));
10780        }
10781        return true;
10782    }
10783
10784    /*
10785     * This method handles package deletion in general
10786     */
10787    private boolean deletePackageLI(String packageName, UserHandle user,
10788            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10789            int flags, PackageRemovedInfo outInfo,
10790            boolean writeSettings) {
10791        if (packageName == null) {
10792            Slog.w(TAG, "Attempt to delete null packageName.");
10793            return false;
10794        }
10795        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10796        PackageSetting ps;
10797        boolean dataOnly = false;
10798        int removeUser = -1;
10799        int appId = -1;
10800        synchronized (mPackages) {
10801            ps = mSettings.mPackages.get(packageName);
10802            if (ps == null) {
10803                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10804                return false;
10805            }
10806            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10807                    && user.getIdentifier() != UserHandle.USER_ALL) {
10808                // The caller is asking that the package only be deleted for a single
10809                // user.  To do this, we just mark its uninstalled state and delete
10810                // its data.  If this is a system app, we only allow this to happen if
10811                // they have set the special DELETE_SYSTEM_APP which requests different
10812                // semantics than normal for uninstalling system apps.
10813                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10814                ps.setUserState(user.getIdentifier(),
10815                        COMPONENT_ENABLED_STATE_DEFAULT,
10816                        false, //installed
10817                        true,  //stopped
10818                        true,  //notLaunched
10819                        false, //blocked
10820                        null, null, null);
10821                if (!isSystemApp(ps)) {
10822                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10823                        // Other user still have this package installed, so all
10824                        // we need to do is clear this user's data and save that
10825                        // it is uninstalled.
10826                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10827                        removeUser = user.getIdentifier();
10828                        appId = ps.appId;
10829                        mSettings.writePackageRestrictionsLPr(removeUser);
10830                    } else {
10831                        // We need to set it back to 'installed' so the uninstall
10832                        // broadcasts will be sent correctly.
10833                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10834                        ps.setInstalled(true, user.getIdentifier());
10835                    }
10836                } else {
10837                    // This is a system app, so we assume that the
10838                    // other users still have this package installed, so all
10839                    // we need to do is clear this user's data and save that
10840                    // it is uninstalled.
10841                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10842                    removeUser = user.getIdentifier();
10843                    appId = ps.appId;
10844                    mSettings.writePackageRestrictionsLPr(removeUser);
10845                }
10846            }
10847        }
10848
10849        if (removeUser >= 0) {
10850            // From above, we determined that we are deleting this only
10851            // for a single user.  Continue the work here.
10852            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10853            if (outInfo != null) {
10854                outInfo.removedPackage = packageName;
10855                outInfo.removedAppId = appId;
10856                outInfo.removedUsers = new int[] {removeUser};
10857            }
10858            mInstaller.clearUserData(packageName, removeUser);
10859            removeKeystoreDataIfNeeded(removeUser, appId);
10860            schedulePackageCleaning(packageName, removeUser, false);
10861            return true;
10862        }
10863
10864        if (dataOnly) {
10865            // Delete application data first
10866            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10867            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10868            return true;
10869        }
10870
10871        boolean ret = false;
10872        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10873        if (isSystemApp(ps)) {
10874            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10875            // When an updated system application is deleted we delete the existing resources as well and
10876            // fall back to existing code in system partition
10877            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10878                    flags, outInfo, writeSettings);
10879        } else {
10880            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10881            // Kill application pre-emptively especially for apps on sd.
10882            killApplication(packageName, ps.appId, "uninstall pkg");
10883            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10884                    allUserHandles, perUserInstalled,
10885                    outInfo, writeSettings);
10886        }
10887
10888        return ret;
10889    }
10890
10891    private final class ClearStorageConnection implements ServiceConnection {
10892        IMediaContainerService mContainerService;
10893
10894        @Override
10895        public void onServiceConnected(ComponentName name, IBinder service) {
10896            synchronized (this) {
10897                mContainerService = IMediaContainerService.Stub.asInterface(service);
10898                notifyAll();
10899            }
10900        }
10901
10902        @Override
10903        public void onServiceDisconnected(ComponentName name) {
10904        }
10905    }
10906
10907    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10908        final boolean mounted;
10909        if (Environment.isExternalStorageEmulated()) {
10910            mounted = true;
10911        } else {
10912            final String status = Environment.getExternalStorageState();
10913
10914            mounted = status.equals(Environment.MEDIA_MOUNTED)
10915                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10916        }
10917
10918        if (!mounted) {
10919            return;
10920        }
10921
10922        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10923        int[] users;
10924        if (userId == UserHandle.USER_ALL) {
10925            users = sUserManager.getUserIds();
10926        } else {
10927            users = new int[] { userId };
10928        }
10929        final ClearStorageConnection conn = new ClearStorageConnection();
10930        if (mContext.bindServiceAsUser(
10931                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10932            try {
10933                for (int curUser : users) {
10934                    long timeout = SystemClock.uptimeMillis() + 5000;
10935                    synchronized (conn) {
10936                        long now = SystemClock.uptimeMillis();
10937                        while (conn.mContainerService == null && now < timeout) {
10938                            try {
10939                                conn.wait(timeout - now);
10940                            } catch (InterruptedException e) {
10941                            }
10942                        }
10943                    }
10944                    if (conn.mContainerService == null) {
10945                        return;
10946                    }
10947
10948                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10949                    clearDirectory(conn.mContainerService,
10950                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10951                    if (allData) {
10952                        clearDirectory(conn.mContainerService,
10953                                userEnv.buildExternalStorageAppDataDirs(packageName));
10954                        clearDirectory(conn.mContainerService,
10955                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10956                    }
10957                }
10958            } finally {
10959                mContext.unbindService(conn);
10960            }
10961        }
10962    }
10963
10964    @Override
10965    public void clearApplicationUserData(final String packageName,
10966            final IPackageDataObserver observer, final int userId) {
10967        mContext.enforceCallingOrSelfPermission(
10968                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10969        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10970        // Queue up an async operation since the package deletion may take a little while.
10971        mHandler.post(new Runnable() {
10972            public void run() {
10973                mHandler.removeCallbacks(this);
10974                final boolean succeeded;
10975                synchronized (mInstallLock) {
10976                    succeeded = clearApplicationUserDataLI(packageName, userId);
10977                }
10978                clearExternalStorageDataSync(packageName, userId, true);
10979                if (succeeded) {
10980                    // invoke DeviceStorageMonitor's update method to clear any notifications
10981                    DeviceStorageMonitorInternal
10982                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10983                    if (dsm != null) {
10984                        dsm.checkMemory();
10985                    }
10986                }
10987                if(observer != null) {
10988                    try {
10989                        observer.onRemoveCompleted(packageName, succeeded);
10990                    } catch (RemoteException e) {
10991                        Log.i(TAG, "Observer no longer exists.");
10992                    }
10993                } //end if observer
10994            } //end run
10995        });
10996    }
10997
10998    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10999        if (packageName == null) {
11000            Slog.w(TAG, "Attempt to delete null packageName.");
11001            return false;
11002        }
11003        PackageParser.Package p;
11004        boolean dataOnly = false;
11005        final int appId;
11006        synchronized (mPackages) {
11007            p = mPackages.get(packageName);
11008            if (p == null) {
11009                dataOnly = true;
11010                PackageSetting ps = mSettings.mPackages.get(packageName);
11011                if ((ps == null) || (ps.pkg == null)) {
11012                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11013                    return false;
11014                }
11015                p = ps.pkg;
11016            }
11017            if (!dataOnly) {
11018                // need to check this only for fully installed applications
11019                if (p == null) {
11020                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11021                    return false;
11022                }
11023                final ApplicationInfo applicationInfo = p.applicationInfo;
11024                if (applicationInfo == null) {
11025                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11026                    return false;
11027                }
11028            }
11029            if (p != null && p.applicationInfo != null) {
11030                appId = p.applicationInfo.uid;
11031            } else {
11032                appId = -1;
11033            }
11034        }
11035        int retCode = mInstaller.clearUserData(packageName, userId);
11036        if (retCode < 0) {
11037            Slog.w(TAG, "Couldn't remove cache files for package: "
11038                    + packageName);
11039            return false;
11040        }
11041        removeKeystoreDataIfNeeded(userId, appId);
11042        return true;
11043    }
11044
11045    /**
11046     * Remove entries from the keystore daemon. Will only remove it if the
11047     * {@code appId} is valid.
11048     */
11049    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11050        if (appId < 0) {
11051            return;
11052        }
11053
11054        final KeyStore keyStore = KeyStore.getInstance();
11055        if (keyStore != null) {
11056            if (userId == UserHandle.USER_ALL) {
11057                for (final int individual : sUserManager.getUserIds()) {
11058                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11059                }
11060            } else {
11061                keyStore.clearUid(UserHandle.getUid(userId, appId));
11062            }
11063        } else {
11064            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11065        }
11066    }
11067
11068    @Override
11069    public void deleteApplicationCacheFiles(final String packageName,
11070            final IPackageDataObserver observer) {
11071        mContext.enforceCallingOrSelfPermission(
11072                android.Manifest.permission.DELETE_CACHE_FILES, null);
11073        // Queue up an async operation since the package deletion may take a little while.
11074        final int userId = UserHandle.getCallingUserId();
11075        mHandler.post(new Runnable() {
11076            public void run() {
11077                mHandler.removeCallbacks(this);
11078                final boolean succeded;
11079                synchronized (mInstallLock) {
11080                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11081                }
11082                clearExternalStorageDataSync(packageName, userId, false);
11083                if(observer != null) {
11084                    try {
11085                        observer.onRemoveCompleted(packageName, succeded);
11086                    } catch (RemoteException e) {
11087                        Log.i(TAG, "Observer no longer exists.");
11088                    }
11089                } //end if observer
11090            } //end run
11091        });
11092    }
11093
11094    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11095        if (packageName == null) {
11096            Slog.w(TAG, "Attempt to delete null packageName.");
11097            return false;
11098        }
11099        PackageParser.Package p;
11100        synchronized (mPackages) {
11101            p = mPackages.get(packageName);
11102        }
11103        if (p == null) {
11104            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11105            return false;
11106        }
11107        final ApplicationInfo applicationInfo = p.applicationInfo;
11108        if (applicationInfo == null) {
11109            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11110            return false;
11111        }
11112        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11113        if (retCode < 0) {
11114            Slog.w(TAG, "Couldn't remove cache files for package: "
11115                       + packageName + " u" + userId);
11116            return false;
11117        }
11118        return true;
11119    }
11120
11121    @Override
11122    public void getPackageSizeInfo(final String packageName, int userHandle,
11123            final IPackageStatsObserver observer) {
11124        mContext.enforceCallingOrSelfPermission(
11125                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11126        if (packageName == null) {
11127            throw new IllegalArgumentException("Attempt to get size of null packageName");
11128        }
11129
11130        PackageStats stats = new PackageStats(packageName, userHandle);
11131
11132        /*
11133         * Queue up an async operation since the package measurement may take a
11134         * little while.
11135         */
11136        Message msg = mHandler.obtainMessage(INIT_COPY);
11137        msg.obj = new MeasureParams(stats, observer);
11138        mHandler.sendMessage(msg);
11139    }
11140
11141    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11142            PackageStats pStats) {
11143        if (packageName == null) {
11144            Slog.w(TAG, "Attempt to get size of null packageName.");
11145            return false;
11146        }
11147        PackageParser.Package p;
11148        boolean dataOnly = false;
11149        String libDirPath = null;
11150        String asecPath = null;
11151        PackageSetting ps = null;
11152        synchronized (mPackages) {
11153            p = mPackages.get(packageName);
11154            ps = mSettings.mPackages.get(packageName);
11155            if(p == null) {
11156                dataOnly = true;
11157                if((ps == null) || (ps.pkg == null)) {
11158                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11159                    return false;
11160                }
11161                p = ps.pkg;
11162            }
11163            if (ps != null) {
11164                libDirPath = ps.nativeLibraryPathString;
11165            }
11166            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11167                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11168                if (secureContainerId != null) {
11169                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11170                }
11171            }
11172        }
11173        String publicSrcDir = null;
11174        if(!dataOnly) {
11175            final ApplicationInfo applicationInfo = p.applicationInfo;
11176            if (applicationInfo == null) {
11177                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11178                return false;
11179            }
11180            if (isForwardLocked(p)) {
11181                publicSrcDir = applicationInfo.publicSourceDir;
11182            }
11183        }
11184        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
11185                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11186                pStats);
11187        if (res < 0) {
11188            return false;
11189        }
11190
11191        // Fix-up for forward-locked applications in ASEC containers.
11192        if (!isExternal(p)) {
11193            pStats.codeSize += pStats.externalCodeSize;
11194            pStats.externalCodeSize = 0L;
11195        }
11196
11197        return true;
11198    }
11199
11200
11201    @Override
11202    public void addPackageToPreferred(String packageName) {
11203        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11204    }
11205
11206    @Override
11207    public void removePackageFromPreferred(String packageName) {
11208        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11209    }
11210
11211    @Override
11212    public List<PackageInfo> getPreferredPackages(int flags) {
11213        return new ArrayList<PackageInfo>();
11214    }
11215
11216    private int getUidTargetSdkVersionLockedLPr(int uid) {
11217        Object obj = mSettings.getUserIdLPr(uid);
11218        if (obj instanceof SharedUserSetting) {
11219            final SharedUserSetting sus = (SharedUserSetting) obj;
11220            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11221            final Iterator<PackageSetting> it = sus.packages.iterator();
11222            while (it.hasNext()) {
11223                final PackageSetting ps = it.next();
11224                if (ps.pkg != null) {
11225                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11226                    if (v < vers) vers = v;
11227                }
11228            }
11229            return vers;
11230        } else if (obj instanceof PackageSetting) {
11231            final PackageSetting ps = (PackageSetting) obj;
11232            if (ps.pkg != null) {
11233                return ps.pkg.applicationInfo.targetSdkVersion;
11234            }
11235        }
11236        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11237    }
11238
11239    @Override
11240    public void addPreferredActivity(IntentFilter filter, int match,
11241            ComponentName[] set, ComponentName activity, int userId) {
11242        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11243    }
11244
11245    private void addPreferredActivityInternal(IntentFilter filter, int match,
11246            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11247        // writer
11248        int callingUid = Binder.getCallingUid();
11249        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11250        if (filter.countActions() == 0) {
11251            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11252            return;
11253        }
11254        synchronized (mPackages) {
11255            if (mContext.checkCallingOrSelfPermission(
11256                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11257                    != PackageManager.PERMISSION_GRANTED) {
11258                if (getUidTargetSdkVersionLockedLPr(callingUid)
11259                        < Build.VERSION_CODES.FROYO) {
11260                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11261                            + callingUid);
11262                    return;
11263                }
11264                mContext.enforceCallingOrSelfPermission(
11265                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11266            }
11267
11268            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11269            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11270            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11271                    new PreferredActivity(filter, match, set, activity, always));
11272            mSettings.writePackageRestrictionsLPr(userId);
11273        }
11274    }
11275
11276    @Override
11277    public void replacePreferredActivity(IntentFilter filter, int match,
11278            ComponentName[] set, ComponentName activity) {
11279        if (filter.countActions() != 1) {
11280            throw new IllegalArgumentException(
11281                    "replacePreferredActivity expects filter to have only 1 action.");
11282        }
11283        if (filter.countDataAuthorities() != 0
11284                || filter.countDataPaths() != 0
11285                || filter.countDataSchemes() > 1
11286                || filter.countDataTypes() != 0) {
11287            throw new IllegalArgumentException(
11288                    "replacePreferredActivity expects filter to have no data authorities, " +
11289                    "paths, or types; and at most one scheme.");
11290        }
11291        synchronized (mPackages) {
11292            if (mContext.checkCallingOrSelfPermission(
11293                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11294                    != PackageManager.PERMISSION_GRANTED) {
11295                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11296                        < Build.VERSION_CODES.FROYO) {
11297                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11298                            + Binder.getCallingUid());
11299                    return;
11300                }
11301                mContext.enforceCallingOrSelfPermission(
11302                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11303            }
11304
11305            final int callingUserId = UserHandle.getCallingUserId();
11306            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11307            if (pir != null) {
11308                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11309                if (filter.countDataSchemes() == 1) {
11310                    Uri.Builder builder = new Uri.Builder();
11311                    builder.scheme(filter.getDataScheme(0));
11312                    intent.setData(builder.build());
11313                }
11314                List<PreferredActivity> matches = pir.queryIntent(
11315                        intent, null, true, callingUserId);
11316                if (DEBUG_PREFERRED) {
11317                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11318                }
11319                for (int i = 0; i < matches.size(); i++) {
11320                    PreferredActivity pa = matches.get(i);
11321                    if (DEBUG_PREFERRED) {
11322                        Slog.i(TAG, "Removing preferred activity "
11323                                + pa.mPref.mComponent + ":");
11324                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11325                    }
11326                    pir.removeFilter(pa);
11327                }
11328            }
11329            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11330        }
11331    }
11332
11333    @Override
11334    public void clearPackagePreferredActivities(String packageName) {
11335        final int uid = Binder.getCallingUid();
11336        // writer
11337        synchronized (mPackages) {
11338            PackageParser.Package pkg = mPackages.get(packageName);
11339            if (pkg == null || pkg.applicationInfo.uid != uid) {
11340                if (mContext.checkCallingOrSelfPermission(
11341                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11342                        != PackageManager.PERMISSION_GRANTED) {
11343                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11344                            < Build.VERSION_CODES.FROYO) {
11345                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11346                                + Binder.getCallingUid());
11347                        return;
11348                    }
11349                    mContext.enforceCallingOrSelfPermission(
11350                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11351                }
11352            }
11353
11354            int user = UserHandle.getCallingUserId();
11355            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11356                mSettings.writePackageRestrictionsLPr(user);
11357                scheduleWriteSettingsLocked();
11358            }
11359        }
11360    }
11361
11362    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11363    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11364        ArrayList<PreferredActivity> removed = null;
11365        boolean changed = false;
11366        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11367            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11368            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11369            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11370                continue;
11371            }
11372            Iterator<PreferredActivity> it = pir.filterIterator();
11373            while (it.hasNext()) {
11374                PreferredActivity pa = it.next();
11375                // Mark entry for removal only if it matches the package name
11376                // and the entry is of type "always".
11377                if (packageName == null ||
11378                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11379                                && pa.mPref.mAlways)) {
11380                    if (removed == null) {
11381                        removed = new ArrayList<PreferredActivity>();
11382                    }
11383                    removed.add(pa);
11384                }
11385            }
11386            if (removed != null) {
11387                for (int j=0; j<removed.size(); j++) {
11388                    PreferredActivity pa = removed.get(j);
11389                    pir.removeFilter(pa);
11390                }
11391                changed = true;
11392            }
11393        }
11394        return changed;
11395    }
11396
11397    @Override
11398    public void resetPreferredActivities(int userId) {
11399        mContext.enforceCallingOrSelfPermission(
11400                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11401        // writer
11402        synchronized (mPackages) {
11403            int user = UserHandle.getCallingUserId();
11404            clearPackagePreferredActivitiesLPw(null, user);
11405            mSettings.readDefaultPreferredAppsLPw(this, user);
11406            mSettings.writePackageRestrictionsLPr(user);
11407            scheduleWriteSettingsLocked();
11408        }
11409    }
11410
11411    @Override
11412    public int getPreferredActivities(List<IntentFilter> outFilters,
11413            List<ComponentName> outActivities, String packageName) {
11414
11415        int num = 0;
11416        final int userId = UserHandle.getCallingUserId();
11417        // reader
11418        synchronized (mPackages) {
11419            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11420            if (pir != null) {
11421                final Iterator<PreferredActivity> it = pir.filterIterator();
11422                while (it.hasNext()) {
11423                    final PreferredActivity pa = it.next();
11424                    if (packageName == null
11425                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11426                                    && pa.mPref.mAlways)) {
11427                        if (outFilters != null) {
11428                            outFilters.add(new IntentFilter(pa));
11429                        }
11430                        if (outActivities != null) {
11431                            outActivities.add(pa.mPref.mComponent);
11432                        }
11433                    }
11434                }
11435            }
11436        }
11437
11438        return num;
11439    }
11440
11441    @Override
11442    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11443            int userId) {
11444        int callingUid = Binder.getCallingUid();
11445        if (callingUid != Process.SYSTEM_UID) {
11446            throw new SecurityException(
11447                    "addPersistentPreferredActivity can only be run by the system");
11448        }
11449        if (filter.countActions() == 0) {
11450            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11451            return;
11452        }
11453        synchronized (mPackages) {
11454            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11455                    " :");
11456            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11457            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11458                    new PersistentPreferredActivity(filter, activity));
11459            mSettings.writePackageRestrictionsLPr(userId);
11460        }
11461    }
11462
11463    @Override
11464    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11465        int callingUid = Binder.getCallingUid();
11466        if (callingUid != Process.SYSTEM_UID) {
11467            throw new SecurityException(
11468                    "clearPackagePersistentPreferredActivities can only be run by the system");
11469        }
11470        ArrayList<PersistentPreferredActivity> removed = null;
11471        boolean changed = false;
11472        synchronized (mPackages) {
11473            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11474                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11475                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11476                        .valueAt(i);
11477                if (userId != thisUserId) {
11478                    continue;
11479                }
11480                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11481                while (it.hasNext()) {
11482                    PersistentPreferredActivity ppa = it.next();
11483                    // Mark entry for removal only if it matches the package name.
11484                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11485                        if (removed == null) {
11486                            removed = new ArrayList<PersistentPreferredActivity>();
11487                        }
11488                        removed.add(ppa);
11489                    }
11490                }
11491                if (removed != null) {
11492                    for (int j=0; j<removed.size(); j++) {
11493                        PersistentPreferredActivity ppa = removed.get(j);
11494                        ppir.removeFilter(ppa);
11495                    }
11496                    changed = true;
11497                }
11498            }
11499
11500            if (changed) {
11501                mSettings.writePackageRestrictionsLPr(userId);
11502            }
11503        }
11504    }
11505
11506    @Override
11507    public void addCrossProfileIntentFilter(IntentFilter filter, boolean removable,
11508            int sourceUserId, int targetUserId) {
11509        mContext.enforceCallingOrSelfPermission(
11510                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11511        if (filter.countActions() == 0) {
11512            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11513            return;
11514        }
11515        synchronized (mPackages) {
11516            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(
11517                    new CrossProfileIntentFilter(filter, removable, targetUserId));
11518            mSettings.writePackageRestrictionsLPr(sourceUserId);
11519        }
11520    }
11521
11522    @Override
11523    public void clearCrossProfileIntentFilters(int sourceUserId) {
11524        mContext.enforceCallingOrSelfPermission(
11525                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11526        synchronized (mPackages) {
11527            CrossProfileIntentResolver cpir =
11528                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11529            HashSet<CrossProfileIntentFilter> set =
11530                    new HashSet<CrossProfileIntentFilter>(cpir.filterSet());
11531            for (CrossProfileIntentFilter cpif : set) {
11532                if (cpif.isRemovable()) cpir.removeFilter(cpif);
11533            }
11534            mSettings.writePackageRestrictionsLPr(sourceUserId);
11535        }
11536    }
11537
11538    @Override
11539    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11540        Intent intent = new Intent(Intent.ACTION_MAIN);
11541        intent.addCategory(Intent.CATEGORY_HOME);
11542
11543        final int callingUserId = UserHandle.getCallingUserId();
11544        List<ResolveInfo> list = queryIntentActivities(intent, null,
11545                PackageManager.GET_META_DATA, callingUserId);
11546        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11547                true, false, false, callingUserId);
11548
11549        allHomeCandidates.clear();
11550        if (list != null) {
11551            for (ResolveInfo ri : list) {
11552                allHomeCandidates.add(ri);
11553            }
11554        }
11555        return (preferred == null || preferred.activityInfo == null)
11556                ? null
11557                : new ComponentName(preferred.activityInfo.packageName,
11558                        preferred.activityInfo.name);
11559    }
11560
11561    @Override
11562    public void setApplicationEnabledSetting(String appPackageName,
11563            int newState, int flags, int userId, String callingPackage) {
11564        if (!sUserManager.exists(userId)) return;
11565        if (callingPackage == null) {
11566            callingPackage = Integer.toString(Binder.getCallingUid());
11567        }
11568        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11569    }
11570
11571    @Override
11572    public void setComponentEnabledSetting(ComponentName componentName,
11573            int newState, int flags, int userId) {
11574        if (!sUserManager.exists(userId)) return;
11575        setEnabledSetting(componentName.getPackageName(),
11576                componentName.getClassName(), newState, flags, userId, null);
11577    }
11578
11579    private void setEnabledSetting(final String packageName, String className, int newState,
11580            final int flags, int userId, String callingPackage) {
11581        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11582              || newState == COMPONENT_ENABLED_STATE_ENABLED
11583              || newState == COMPONENT_ENABLED_STATE_DISABLED
11584              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11585              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11586            throw new IllegalArgumentException("Invalid new component state: "
11587                    + newState);
11588        }
11589        PackageSetting pkgSetting;
11590        final int uid = Binder.getCallingUid();
11591        final int permission = mContext.checkCallingOrSelfPermission(
11592                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11593        enforceCrossUserPermission(uid, userId, false, "set enabled");
11594        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11595        boolean sendNow = false;
11596        boolean isApp = (className == null);
11597        String componentName = isApp ? packageName : className;
11598        int packageUid = -1;
11599        ArrayList<String> components;
11600
11601        // writer
11602        synchronized (mPackages) {
11603            pkgSetting = mSettings.mPackages.get(packageName);
11604            if (pkgSetting == null) {
11605                if (className == null) {
11606                    throw new IllegalArgumentException(
11607                            "Unknown package: " + packageName);
11608                }
11609                throw new IllegalArgumentException(
11610                        "Unknown component: " + packageName
11611                        + "/" + className);
11612            }
11613            // Allow root and verify that userId is not being specified by a different user
11614            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11615                throw new SecurityException(
11616                        "Permission Denial: attempt to change component state from pid="
11617                        + Binder.getCallingPid()
11618                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11619            }
11620            if (className == null) {
11621                // We're dealing with an application/package level state change
11622                if (pkgSetting.getEnabled(userId) == newState) {
11623                    // Nothing to do
11624                    return;
11625                }
11626                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11627                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11628                    // Don't care about who enables an app.
11629                    callingPackage = null;
11630                }
11631                pkgSetting.setEnabled(newState, userId, callingPackage);
11632                // pkgSetting.pkg.mSetEnabled = newState;
11633            } else {
11634                // We're dealing with a component level state change
11635                // First, verify that this is a valid class name.
11636                PackageParser.Package pkg = pkgSetting.pkg;
11637                if (pkg == null || !pkg.hasComponentClassName(className)) {
11638                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11639                        throw new IllegalArgumentException("Component class " + className
11640                                + " does not exist in " + packageName);
11641                    } else {
11642                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11643                                + className + " does not exist in " + packageName);
11644                    }
11645                }
11646                switch (newState) {
11647                case COMPONENT_ENABLED_STATE_ENABLED:
11648                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11649                        return;
11650                    }
11651                    break;
11652                case COMPONENT_ENABLED_STATE_DISABLED:
11653                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11654                        return;
11655                    }
11656                    break;
11657                case COMPONENT_ENABLED_STATE_DEFAULT:
11658                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11659                        return;
11660                    }
11661                    break;
11662                default:
11663                    Slog.e(TAG, "Invalid new component state: " + newState);
11664                    return;
11665                }
11666            }
11667            mSettings.writePackageRestrictionsLPr(userId);
11668            components = mPendingBroadcasts.get(userId, packageName);
11669            final boolean newPackage = components == null;
11670            if (newPackage) {
11671                components = new ArrayList<String>();
11672            }
11673            if (!components.contains(componentName)) {
11674                components.add(componentName);
11675            }
11676            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11677                sendNow = true;
11678                // Purge entry from pending broadcast list if another one exists already
11679                // since we are sending one right away.
11680                mPendingBroadcasts.remove(userId, packageName);
11681            } else {
11682                if (newPackage) {
11683                    mPendingBroadcasts.put(userId, packageName, components);
11684                }
11685                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11686                    // Schedule a message
11687                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11688                }
11689            }
11690        }
11691
11692        long callingId = Binder.clearCallingIdentity();
11693        try {
11694            if (sendNow) {
11695                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11696                sendPackageChangedBroadcast(packageName,
11697                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11698            }
11699        } finally {
11700            Binder.restoreCallingIdentity(callingId);
11701        }
11702    }
11703
11704    private void sendPackageChangedBroadcast(String packageName,
11705            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11706        if (DEBUG_INSTALL)
11707            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11708                    + componentNames);
11709        Bundle extras = new Bundle(4);
11710        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11711        String nameList[] = new String[componentNames.size()];
11712        componentNames.toArray(nameList);
11713        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11714        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11715        extras.putInt(Intent.EXTRA_UID, packageUid);
11716        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11717                new int[] {UserHandle.getUserId(packageUid)});
11718    }
11719
11720    @Override
11721    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11722        if (!sUserManager.exists(userId)) return;
11723        final int uid = Binder.getCallingUid();
11724        final int permission = mContext.checkCallingOrSelfPermission(
11725                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11726        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11727        enforceCrossUserPermission(uid, userId, true, "stop package");
11728        // writer
11729        synchronized (mPackages) {
11730            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11731                    uid, userId)) {
11732                scheduleWritePackageRestrictionsLocked(userId);
11733            }
11734        }
11735    }
11736
11737    @Override
11738    public String getInstallerPackageName(String packageName) {
11739        // reader
11740        synchronized (mPackages) {
11741            return mSettings.getInstallerPackageNameLPr(packageName);
11742        }
11743    }
11744
11745    @Override
11746    public int getApplicationEnabledSetting(String packageName, int userId) {
11747        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11748        int uid = Binder.getCallingUid();
11749        enforceCrossUserPermission(uid, userId, false, "get enabled");
11750        // reader
11751        synchronized (mPackages) {
11752            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11753        }
11754    }
11755
11756    @Override
11757    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11758        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11759        int uid = Binder.getCallingUid();
11760        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11761        // reader
11762        synchronized (mPackages) {
11763            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11764        }
11765    }
11766
11767    @Override
11768    public void enterSafeMode() {
11769        enforceSystemOrRoot("Only the system can request entering safe mode");
11770
11771        if (!mSystemReady) {
11772            mSafeMode = true;
11773        }
11774    }
11775
11776    @Override
11777    public void systemReady() {
11778        mSystemReady = true;
11779
11780        // Read the compatibilty setting when the system is ready.
11781        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11782                mContext.getContentResolver(),
11783                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11784        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11785        if (DEBUG_SETTINGS) {
11786            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11787        }
11788
11789        synchronized (mPackages) {
11790            // Verify that all of the preferred activity components actually
11791            // exist.  It is possible for applications to be updated and at
11792            // that point remove a previously declared activity component that
11793            // had been set as a preferred activity.  We try to clean this up
11794            // the next time we encounter that preferred activity, but it is
11795            // possible for the user flow to never be able to return to that
11796            // situation so here we do a sanity check to make sure we haven't
11797            // left any junk around.
11798            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11799            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11800                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11801                removed.clear();
11802                for (PreferredActivity pa : pir.filterSet()) {
11803                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11804                        removed.add(pa);
11805                    }
11806                }
11807                if (removed.size() > 0) {
11808                    for (int r=0; r<removed.size(); r++) {
11809                        PreferredActivity pa = removed.get(r);
11810                        Slog.w(TAG, "Removing dangling preferred activity: "
11811                                + pa.mPref.mComponent);
11812                        pir.removeFilter(pa);
11813                    }
11814                    mSettings.writePackageRestrictionsLPr(
11815                            mSettings.mPreferredActivities.keyAt(i));
11816                }
11817            }
11818        }
11819        sUserManager.systemReady();
11820    }
11821
11822    @Override
11823    public boolean isSafeMode() {
11824        return mSafeMode;
11825    }
11826
11827    @Override
11828    public boolean hasSystemUidErrors() {
11829        return mHasSystemUidErrors;
11830    }
11831
11832    static String arrayToString(int[] array) {
11833        StringBuffer buf = new StringBuffer(128);
11834        buf.append('[');
11835        if (array != null) {
11836            for (int i=0; i<array.length; i++) {
11837                if (i > 0) buf.append(", ");
11838                buf.append(array[i]);
11839            }
11840        }
11841        buf.append(']');
11842        return buf.toString();
11843    }
11844
11845    static class DumpState {
11846        public static final int DUMP_LIBS = 1 << 0;
11847
11848        public static final int DUMP_FEATURES = 1 << 1;
11849
11850        public static final int DUMP_RESOLVERS = 1 << 2;
11851
11852        public static final int DUMP_PERMISSIONS = 1 << 3;
11853
11854        public static final int DUMP_PACKAGES = 1 << 4;
11855
11856        public static final int DUMP_SHARED_USERS = 1 << 5;
11857
11858        public static final int DUMP_MESSAGES = 1 << 6;
11859
11860        public static final int DUMP_PROVIDERS = 1 << 7;
11861
11862        public static final int DUMP_VERIFIERS = 1 << 8;
11863
11864        public static final int DUMP_PREFERRED = 1 << 9;
11865
11866        public static final int DUMP_PREFERRED_XML = 1 << 10;
11867
11868        public static final int DUMP_KEYSETS = 1 << 11;
11869
11870        public static final int DUMP_VERSION = 1 << 12;
11871
11872        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11873
11874        private int mTypes;
11875
11876        private int mOptions;
11877
11878        private boolean mTitlePrinted;
11879
11880        private SharedUserSetting mSharedUser;
11881
11882        public boolean isDumping(int type) {
11883            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11884                return true;
11885            }
11886
11887            return (mTypes & type) != 0;
11888        }
11889
11890        public void setDump(int type) {
11891            mTypes |= type;
11892        }
11893
11894        public boolean isOptionEnabled(int option) {
11895            return (mOptions & option) != 0;
11896        }
11897
11898        public void setOptionEnabled(int option) {
11899            mOptions |= option;
11900        }
11901
11902        public boolean onTitlePrinted() {
11903            final boolean printed = mTitlePrinted;
11904            mTitlePrinted = true;
11905            return printed;
11906        }
11907
11908        public boolean getTitlePrinted() {
11909            return mTitlePrinted;
11910        }
11911
11912        public void setTitlePrinted(boolean enabled) {
11913            mTitlePrinted = enabled;
11914        }
11915
11916        public SharedUserSetting getSharedUser() {
11917            return mSharedUser;
11918        }
11919
11920        public void setSharedUser(SharedUserSetting user) {
11921            mSharedUser = user;
11922        }
11923    }
11924
11925    @Override
11926    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11927        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11928                != PackageManager.PERMISSION_GRANTED) {
11929            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11930                    + Binder.getCallingPid()
11931                    + ", uid=" + Binder.getCallingUid()
11932                    + " without permission "
11933                    + android.Manifest.permission.DUMP);
11934            return;
11935        }
11936
11937        DumpState dumpState = new DumpState();
11938        boolean fullPreferred = false;
11939        boolean checkin = false;
11940
11941        String packageName = null;
11942
11943        int opti = 0;
11944        while (opti < args.length) {
11945            String opt = args[opti];
11946            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11947                break;
11948            }
11949            opti++;
11950            if ("-a".equals(opt)) {
11951                // Right now we only know how to print all.
11952            } else if ("-h".equals(opt)) {
11953                pw.println("Package manager dump options:");
11954                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11955                pw.println("    --checkin: dump for a checkin");
11956                pw.println("    -f: print details of intent filters");
11957                pw.println("    -h: print this help");
11958                pw.println("  cmd may be one of:");
11959                pw.println("    l[ibraries]: list known shared libraries");
11960                pw.println("    f[ibraries]: list device features");
11961                pw.println("    k[eysets]: print known keysets");
11962                pw.println("    r[esolvers]: dump intent resolvers");
11963                pw.println("    perm[issions]: dump permissions");
11964                pw.println("    pref[erred]: print preferred package settings");
11965                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11966                pw.println("    prov[iders]: dump content providers");
11967                pw.println("    p[ackages]: dump installed packages");
11968                pw.println("    s[hared-users]: dump shared user IDs");
11969                pw.println("    m[essages]: print collected runtime messages");
11970                pw.println("    v[erifiers]: print package verifier info");
11971                pw.println("    version: print database version info");
11972                pw.println("    write: write current settings now");
11973                pw.println("    <package.name>: info about given package");
11974                return;
11975            } else if ("--checkin".equals(opt)) {
11976                checkin = true;
11977            } else if ("-f".equals(opt)) {
11978                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11979            } else {
11980                pw.println("Unknown argument: " + opt + "; use -h for help");
11981            }
11982        }
11983
11984        // Is the caller requesting to dump a particular piece of data?
11985        if (opti < args.length) {
11986            String cmd = args[opti];
11987            opti++;
11988            // Is this a package name?
11989            if ("android".equals(cmd) || cmd.contains(".")) {
11990                packageName = cmd;
11991                // When dumping a single package, we always dump all of its
11992                // filter information since the amount of data will be reasonable.
11993                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11994            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11995                dumpState.setDump(DumpState.DUMP_LIBS);
11996            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11997                dumpState.setDump(DumpState.DUMP_FEATURES);
11998            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11999                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12000            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12001                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12002            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12003                dumpState.setDump(DumpState.DUMP_PREFERRED);
12004            } else if ("preferred-xml".equals(cmd)) {
12005                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12006                if (opti < args.length && "--full".equals(args[opti])) {
12007                    fullPreferred = true;
12008                    opti++;
12009                }
12010            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12011                dumpState.setDump(DumpState.DUMP_PACKAGES);
12012            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12013                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12014            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12015                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12016            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12017                dumpState.setDump(DumpState.DUMP_MESSAGES);
12018            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12019                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12020            } else if ("version".equals(cmd)) {
12021                dumpState.setDump(DumpState.DUMP_VERSION);
12022            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12023                dumpState.setDump(DumpState.DUMP_KEYSETS);
12024            } else if ("write".equals(cmd)) {
12025                synchronized (mPackages) {
12026                    mSettings.writeLPr();
12027                    pw.println("Settings written.");
12028                    return;
12029                }
12030            }
12031        }
12032
12033        if (checkin) {
12034            pw.println("vers,1");
12035        }
12036
12037        // reader
12038        synchronized (mPackages) {
12039            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12040                if (!checkin) {
12041                    if (dumpState.onTitlePrinted())
12042                        pw.println();
12043                    pw.println("Database versions:");
12044                    pw.print("  SDK Version:");
12045                    pw.print(" internal=");
12046                    pw.print(mSettings.mInternalSdkPlatform);
12047                    pw.print(" external=");
12048                    pw.println(mSettings.mExternalSdkPlatform);
12049                    pw.print("  DB Version:");
12050                    pw.print(" internal=");
12051                    pw.print(mSettings.mInternalDatabaseVersion);
12052                    pw.print(" external=");
12053                    pw.println(mSettings.mExternalDatabaseVersion);
12054                }
12055            }
12056
12057            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12058                if (!checkin) {
12059                    if (dumpState.onTitlePrinted())
12060                        pw.println();
12061                    pw.println("Verifiers:");
12062                    pw.print("  Required: ");
12063                    pw.print(mRequiredVerifierPackage);
12064                    pw.print(" (uid=");
12065                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12066                    pw.println(")");
12067                } else if (mRequiredVerifierPackage != null) {
12068                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12069                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12070                }
12071            }
12072
12073            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12074                boolean printedHeader = false;
12075                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12076                while (it.hasNext()) {
12077                    String name = it.next();
12078                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12079                    if (!checkin) {
12080                        if (!printedHeader) {
12081                            if (dumpState.onTitlePrinted())
12082                                pw.println();
12083                            pw.println("Libraries:");
12084                            printedHeader = true;
12085                        }
12086                        pw.print("  ");
12087                    } else {
12088                        pw.print("lib,");
12089                    }
12090                    pw.print(name);
12091                    if (!checkin) {
12092                        pw.print(" -> ");
12093                    }
12094                    if (ent.path != null) {
12095                        if (!checkin) {
12096                            pw.print("(jar) ");
12097                            pw.print(ent.path);
12098                        } else {
12099                            pw.print(",jar,");
12100                            pw.print(ent.path);
12101                        }
12102                    } else {
12103                        if (!checkin) {
12104                            pw.print("(apk) ");
12105                            pw.print(ent.apk);
12106                        } else {
12107                            pw.print(",apk,");
12108                            pw.print(ent.apk);
12109                        }
12110                    }
12111                    pw.println();
12112                }
12113            }
12114
12115            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12116                if (dumpState.onTitlePrinted())
12117                    pw.println();
12118                if (!checkin) {
12119                    pw.println("Features:");
12120                }
12121                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12122                while (it.hasNext()) {
12123                    String name = it.next();
12124                    if (!checkin) {
12125                        pw.print("  ");
12126                    } else {
12127                        pw.print("feat,");
12128                    }
12129                    pw.println(name);
12130                }
12131            }
12132
12133            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12134                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12135                        : "Activity Resolver Table:", "  ", packageName,
12136                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12137                    dumpState.setTitlePrinted(true);
12138                }
12139                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12140                        : "Receiver Resolver Table:", "  ", packageName,
12141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12142                    dumpState.setTitlePrinted(true);
12143                }
12144                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12145                        : "Service Resolver Table:", "  ", packageName,
12146                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12147                    dumpState.setTitlePrinted(true);
12148                }
12149                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12150                        : "Provider Resolver Table:", "  ", packageName,
12151                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12152                    dumpState.setTitlePrinted(true);
12153                }
12154            }
12155
12156            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12157                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12158                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12159                    int user = mSettings.mPreferredActivities.keyAt(i);
12160                    if (pir.dump(pw,
12161                            dumpState.getTitlePrinted()
12162                                ? "\nPreferred Activities User " + user + ":"
12163                                : "Preferred Activities User " + user + ":", "  ",
12164                            packageName, true)) {
12165                        dumpState.setTitlePrinted(true);
12166                    }
12167                }
12168            }
12169
12170            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12171                pw.flush();
12172                FileOutputStream fout = new FileOutputStream(fd);
12173                BufferedOutputStream str = new BufferedOutputStream(fout);
12174                XmlSerializer serializer = new FastXmlSerializer();
12175                try {
12176                    serializer.setOutput(str, "utf-8");
12177                    serializer.startDocument(null, true);
12178                    serializer.setFeature(
12179                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12180                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12181                    serializer.endDocument();
12182                    serializer.flush();
12183                } catch (IllegalArgumentException e) {
12184                    pw.println("Failed writing: " + e);
12185                } catch (IllegalStateException e) {
12186                    pw.println("Failed writing: " + e);
12187                } catch (IOException e) {
12188                    pw.println("Failed writing: " + e);
12189                }
12190            }
12191
12192            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12193                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12194            }
12195
12196            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12197                boolean printedSomething = false;
12198                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12199                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12200                        continue;
12201                    }
12202                    if (!printedSomething) {
12203                        if (dumpState.onTitlePrinted())
12204                            pw.println();
12205                        pw.println("Registered ContentProviders:");
12206                        printedSomething = true;
12207                    }
12208                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12209                    pw.print("    "); pw.println(p.toString());
12210                }
12211                printedSomething = false;
12212                for (Map.Entry<String, PackageParser.Provider> entry :
12213                        mProvidersByAuthority.entrySet()) {
12214                    PackageParser.Provider p = entry.getValue();
12215                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12216                        continue;
12217                    }
12218                    if (!printedSomething) {
12219                        if (dumpState.onTitlePrinted())
12220                            pw.println();
12221                        pw.println("ContentProvider Authorities:");
12222                        printedSomething = true;
12223                    }
12224                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12225                    pw.print("    "); pw.println(p.toString());
12226                    if (p.info != null && p.info.applicationInfo != null) {
12227                        final String appInfo = p.info.applicationInfo.toString();
12228                        pw.print("      applicationInfo="); pw.println(appInfo);
12229                    }
12230                }
12231            }
12232
12233            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12234                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12235            }
12236
12237            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12238                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12239            }
12240
12241            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12242                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12243            }
12244
12245            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12246                if (dumpState.onTitlePrinted())
12247                    pw.println();
12248                mSettings.dumpReadMessagesLPr(pw, dumpState);
12249
12250                pw.println();
12251                pw.println("Package warning messages:");
12252                final File fname = getSettingsProblemFile();
12253                FileInputStream in = null;
12254                try {
12255                    in = new FileInputStream(fname);
12256                    final int avail = in.available();
12257                    final byte[] data = new byte[avail];
12258                    in.read(data);
12259                    pw.print(new String(data));
12260                } catch (FileNotFoundException e) {
12261                } catch (IOException e) {
12262                } finally {
12263                    if (in != null) {
12264                        try {
12265                            in.close();
12266                        } catch (IOException e) {
12267                        }
12268                    }
12269                }
12270            }
12271        }
12272    }
12273
12274    // ------- apps on sdcard specific code -------
12275    static final boolean DEBUG_SD_INSTALL = false;
12276
12277    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12278
12279    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12280
12281    private boolean mMediaMounted = false;
12282
12283    private String getEncryptKey() {
12284        try {
12285            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12286                    SD_ENCRYPTION_KEYSTORE_NAME);
12287            if (sdEncKey == null) {
12288                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12289                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12290                if (sdEncKey == null) {
12291                    Slog.e(TAG, "Failed to create encryption keys");
12292                    return null;
12293                }
12294            }
12295            return sdEncKey;
12296        } catch (NoSuchAlgorithmException nsae) {
12297            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12298            return null;
12299        } catch (IOException ioe) {
12300            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12301            return null;
12302        }
12303
12304    }
12305
12306    /* package */static String getTempContainerId() {
12307        int tmpIdx = 1;
12308        String list[] = PackageHelper.getSecureContainerList();
12309        if (list != null) {
12310            for (final String name : list) {
12311                // Ignore null and non-temporary container entries
12312                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12313                    continue;
12314                }
12315
12316                String subStr = name.substring(mTempContainerPrefix.length());
12317                try {
12318                    int cid = Integer.parseInt(subStr);
12319                    if (cid >= tmpIdx) {
12320                        tmpIdx = cid + 1;
12321                    }
12322                } catch (NumberFormatException e) {
12323                }
12324            }
12325        }
12326        return mTempContainerPrefix + tmpIdx;
12327    }
12328
12329    /*
12330     * Update media status on PackageManager.
12331     */
12332    @Override
12333    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12334        int callingUid = Binder.getCallingUid();
12335        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12336            throw new SecurityException("Media status can only be updated by the system");
12337        }
12338        // reader; this apparently protects mMediaMounted, but should probably
12339        // be a different lock in that case.
12340        synchronized (mPackages) {
12341            Log.i(TAG, "Updating external media status from "
12342                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12343                    + (mediaStatus ? "mounted" : "unmounted"));
12344            if (DEBUG_SD_INSTALL)
12345                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12346                        + ", mMediaMounted=" + mMediaMounted);
12347            if (mediaStatus == mMediaMounted) {
12348                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12349                        : 0, -1);
12350                mHandler.sendMessage(msg);
12351                return;
12352            }
12353            mMediaMounted = mediaStatus;
12354        }
12355        // Queue up an async operation since the package installation may take a
12356        // little while.
12357        mHandler.post(new Runnable() {
12358            public void run() {
12359                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12360            }
12361        });
12362    }
12363
12364    /**
12365     * Called by MountService when the initial ASECs to scan are available.
12366     * Should block until all the ASEC containers are finished being scanned.
12367     */
12368    public void scanAvailableAsecs() {
12369        updateExternalMediaStatusInner(true, false, false);
12370        if (mShouldRestoreconData) {
12371            SELinuxMMAC.setRestoreconDone();
12372            mShouldRestoreconData = false;
12373        }
12374    }
12375
12376    /*
12377     * Collect information of applications on external media, map them against
12378     * existing containers and update information based on current mount status.
12379     * Please note that we always have to report status if reportStatus has been
12380     * set to true especially when unloading packages.
12381     */
12382    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12383            boolean externalStorage) {
12384        // Collection of uids
12385        int uidArr[] = null;
12386        // Collection of stale containers
12387        HashSet<String> removeCids = new HashSet<String>();
12388        // Collection of packages on external media with valid containers.
12389        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12390        // Get list of secure containers.
12391        final String list[] = PackageHelper.getSecureContainerList();
12392        if (list == null || list.length == 0) {
12393            Log.i(TAG, "No secure containers on sdcard");
12394        } else {
12395            // Process list of secure containers and categorize them
12396            // as active or stale based on their package internal state.
12397            int uidList[] = new int[list.length];
12398            int num = 0;
12399            // reader
12400            synchronized (mPackages) {
12401                for (String cid : list) {
12402                    if (DEBUG_SD_INSTALL)
12403                        Log.i(TAG, "Processing container " + cid);
12404                    String pkgName = getAsecPackageName(cid);
12405                    if (pkgName == null) {
12406                        if (DEBUG_SD_INSTALL)
12407                            Log.i(TAG, "Container : " + cid + " stale");
12408                        removeCids.add(cid);
12409                        continue;
12410                    }
12411                    if (DEBUG_SD_INSTALL)
12412                        Log.i(TAG, "Looking for pkg : " + pkgName);
12413
12414                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12415                    if (ps == null) {
12416                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12417                        removeCids.add(cid);
12418                        continue;
12419                    }
12420
12421                    /*
12422                     * Skip packages that are not external if we're unmounting
12423                     * external storage.
12424                     */
12425                    if (externalStorage && !isMounted && !isExternal(ps)) {
12426                        continue;
12427                    }
12428
12429                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12430                            getAppInstructionSetFromSettings(ps),
12431                            isForwardLocked(ps));
12432                    // The package status is changed only if the code path
12433                    // matches between settings and the container id.
12434                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12435                        if (DEBUG_SD_INSTALL) {
12436                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12437                                    + " at code path: " + ps.codePathString);
12438                        }
12439
12440                        // We do have a valid package installed on sdcard
12441                        processCids.put(args, ps.codePathString);
12442                        final int uid = ps.appId;
12443                        if (uid != -1) {
12444                            uidList[num++] = uid;
12445                        }
12446                    } else {
12447                        Log.i(TAG, "Deleting stale container for " + cid);
12448                        removeCids.add(cid);
12449                    }
12450                }
12451            }
12452
12453            if (num > 0) {
12454                // Sort uid list
12455                Arrays.sort(uidList, 0, num);
12456                // Throw away duplicates
12457                uidArr = new int[num];
12458                uidArr[0] = uidList[0];
12459                int di = 0;
12460                for (int i = 1; i < num; i++) {
12461                    if (uidList[i - 1] != uidList[i]) {
12462                        uidArr[di++] = uidList[i];
12463                    }
12464                }
12465            }
12466        }
12467        // Process packages with valid entries.
12468        if (isMounted) {
12469            if (DEBUG_SD_INSTALL)
12470                Log.i(TAG, "Loading packages");
12471            loadMediaPackages(processCids, uidArr, removeCids);
12472            startCleaningPackages();
12473        } else {
12474            if (DEBUG_SD_INSTALL)
12475                Log.i(TAG, "Unloading packages");
12476            unloadMediaPackages(processCids, uidArr, reportStatus);
12477        }
12478    }
12479
12480   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12481           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12482        int size = pkgList.size();
12483        if (size > 0) {
12484            // Send broadcasts here
12485            Bundle extras = new Bundle();
12486            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12487                    .toArray(new String[size]));
12488            if (uidArr != null) {
12489                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12490            }
12491            if (replacing) {
12492                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12493            }
12494            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12495                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12496            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12497        }
12498    }
12499
12500   /*
12501     * Look at potentially valid container ids from processCids If package
12502     * information doesn't match the one on record or package scanning fails,
12503     * the cid is added to list of removeCids. We currently don't delete stale
12504     * containers.
12505     */
12506   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12507            HashSet<String> removeCids) {
12508        ArrayList<String> pkgList = new ArrayList<String>();
12509        Set<AsecInstallArgs> keys = processCids.keySet();
12510        boolean doGc = false;
12511        for (AsecInstallArgs args : keys) {
12512            String codePath = processCids.get(args);
12513            if (DEBUG_SD_INSTALL)
12514                Log.i(TAG, "Loading container : " + args.cid);
12515            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12516            try {
12517                // Make sure there are no container errors first.
12518                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12519                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12520                            + " when installing from sdcard");
12521                    continue;
12522                }
12523                // Check code path here.
12524                if (codePath == null || !codePath.equals(args.getCodePath())) {
12525                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12526                            + " does not match one in settings " + codePath);
12527                    continue;
12528                }
12529                // Parse package
12530                int parseFlags = mDefParseFlags;
12531                if (args.isExternal()) {
12532                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12533                }
12534                if (args.isFwdLocked()) {
12535                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12536                }
12537
12538                doGc = true;
12539                synchronized (mInstallLock) {
12540                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12541                            0, 0, null, null);
12542                    // Scan the package
12543                    if (pkg != null) {
12544                        /*
12545                         * TODO why is the lock being held? doPostInstall is
12546                         * called in other places without the lock. This needs
12547                         * to be straightened out.
12548                         */
12549                        // writer
12550                        synchronized (mPackages) {
12551                            retCode = PackageManager.INSTALL_SUCCEEDED;
12552                            pkgList.add(pkg.packageName);
12553                            // Post process args
12554                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12555                                    pkg.applicationInfo.uid);
12556                        }
12557                    } else {
12558                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12559                    }
12560                }
12561
12562            } finally {
12563                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12564                    // Don't destroy container here. Wait till gc clears things
12565                    // up.
12566                    removeCids.add(args.cid);
12567                }
12568            }
12569        }
12570        // writer
12571        synchronized (mPackages) {
12572            // If the platform SDK has changed since the last time we booted,
12573            // we need to re-grant app permission to catch any new ones that
12574            // appear. This is really a hack, and means that apps can in some
12575            // cases get permissions that the user didn't initially explicitly
12576            // allow... it would be nice to have some better way to handle
12577            // this situation.
12578            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12579            if (regrantPermissions)
12580                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12581                        + mSdkVersion + "; regranting permissions for external storage");
12582            mSettings.mExternalSdkPlatform = mSdkVersion;
12583
12584            // Make sure group IDs have been assigned, and any permission
12585            // changes in other apps are accounted for
12586            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12587                    | (regrantPermissions
12588                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12589                            : 0));
12590
12591            mSettings.updateExternalDatabaseVersion();
12592
12593            // can downgrade to reader
12594            // Persist settings
12595            mSettings.writeLPr();
12596        }
12597        // Send a broadcast to let everyone know we are done processing
12598        if (pkgList.size() > 0) {
12599            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12600        }
12601        // Force gc to avoid any stale parser references that we might have.
12602        if (doGc) {
12603            Runtime.getRuntime().gc();
12604        }
12605        // List stale containers and destroy stale temporary containers.
12606        if (removeCids != null) {
12607            for (String cid : removeCids) {
12608                if (cid.startsWith(mTempContainerPrefix)) {
12609                    Log.i(TAG, "Destroying stale temporary container " + cid);
12610                    PackageHelper.destroySdDir(cid);
12611                } else {
12612                    Log.w(TAG, "Container " + cid + " is stale");
12613               }
12614           }
12615        }
12616    }
12617
12618   /*
12619     * Utility method to unload a list of specified containers
12620     */
12621    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12622        // Just unmount all valid containers.
12623        for (AsecInstallArgs arg : cidArgs) {
12624            synchronized (mInstallLock) {
12625                arg.doPostDeleteLI(false);
12626           }
12627       }
12628   }
12629
12630    /*
12631     * Unload packages mounted on external media. This involves deleting package
12632     * data from internal structures, sending broadcasts about diabled packages,
12633     * gc'ing to free up references, unmounting all secure containers
12634     * corresponding to packages on external media, and posting a
12635     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12636     * that we always have to post this message if status has been requested no
12637     * matter what.
12638     */
12639    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12640            final boolean reportStatus) {
12641        if (DEBUG_SD_INSTALL)
12642            Log.i(TAG, "unloading media packages");
12643        ArrayList<String> pkgList = new ArrayList<String>();
12644        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12645        final Set<AsecInstallArgs> keys = processCids.keySet();
12646        for (AsecInstallArgs args : keys) {
12647            String pkgName = args.getPackageName();
12648            if (DEBUG_SD_INSTALL)
12649                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12650            // Delete package internally
12651            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12652            synchronized (mInstallLock) {
12653                boolean res = deletePackageLI(pkgName, null, false, null, null,
12654                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12655                if (res) {
12656                    pkgList.add(pkgName);
12657                } else {
12658                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12659                    failedList.add(args);
12660                }
12661            }
12662        }
12663
12664        // reader
12665        synchronized (mPackages) {
12666            // We didn't update the settings after removing each package;
12667            // write them now for all packages.
12668            mSettings.writeLPr();
12669        }
12670
12671        // We have to absolutely send UPDATED_MEDIA_STATUS only
12672        // after confirming that all the receivers processed the ordered
12673        // broadcast when packages get disabled, force a gc to clean things up.
12674        // and unload all the containers.
12675        if (pkgList.size() > 0) {
12676            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12677                    new IIntentReceiver.Stub() {
12678                public void performReceive(Intent intent, int resultCode, String data,
12679                        Bundle extras, boolean ordered, boolean sticky,
12680                        int sendingUser) throws RemoteException {
12681                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12682                            reportStatus ? 1 : 0, 1, keys);
12683                    mHandler.sendMessage(msg);
12684                }
12685            });
12686        } else {
12687            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12688                    keys);
12689            mHandler.sendMessage(msg);
12690        }
12691    }
12692
12693    /** Binder call */
12694    @Override
12695    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12696            final int flags) {
12697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12698        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12699        int returnCode = PackageManager.MOVE_SUCCEEDED;
12700        int currFlags = 0;
12701        int newFlags = 0;
12702        // reader
12703        synchronized (mPackages) {
12704            PackageParser.Package pkg = mPackages.get(packageName);
12705            if (pkg == null) {
12706                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12707            } else {
12708                // Disable moving fwd locked apps and system packages
12709                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12710                    Slog.w(TAG, "Cannot move system application");
12711                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12712                } else if (pkg.mOperationPending) {
12713                    Slog.w(TAG, "Attempt to move package which has pending operations");
12714                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12715                } else {
12716                    // Find install location first
12717                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12718                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12719                        Slog.w(TAG, "Ambigous flags specified for move location.");
12720                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12721                    } else {
12722                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12723                                : PackageManager.INSTALL_INTERNAL;
12724                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12725                                : PackageManager.INSTALL_INTERNAL;
12726
12727                        if (newFlags == currFlags) {
12728                            Slog.w(TAG, "No move required. Trying to move to same location");
12729                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12730                        } else {
12731                            if (isForwardLocked(pkg)) {
12732                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12733                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12734                            }
12735                        }
12736                    }
12737                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12738                        pkg.mOperationPending = true;
12739                    }
12740                }
12741            }
12742
12743            /*
12744             * TODO this next block probably shouldn't be inside the lock. We
12745             * can't guarantee these won't change after this is fired off
12746             * anyway.
12747             */
12748            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12749                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12750                        null, -1, user),
12751                        returnCode);
12752            } else {
12753                Message msg = mHandler.obtainMessage(INIT_COPY);
12754                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12755                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12756                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12757                        instructionSet);
12758                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12759                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12760                msg.obj = mp;
12761                mHandler.sendMessage(msg);
12762            }
12763        }
12764    }
12765
12766    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12767        // Queue up an async operation since the package deletion may take a
12768        // little while.
12769        mHandler.post(new Runnable() {
12770            public void run() {
12771                // TODO fix this; this does nothing.
12772                mHandler.removeCallbacks(this);
12773                int returnCode = currentStatus;
12774                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12775                    int uidArr[] = null;
12776                    ArrayList<String> pkgList = null;
12777                    synchronized (mPackages) {
12778                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12779                        if (pkg == null) {
12780                            Slog.w(TAG, " Package " + mp.packageName
12781                                    + " doesn't exist. Aborting move");
12782                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12783                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12784                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12785                                    + mp.srcArgs.getCodePath() + " to "
12786                                    + pkg.applicationInfo.sourceDir
12787                                    + " Aborting move and returning error");
12788                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12789                        } else {
12790                            uidArr = new int[] {
12791                                pkg.applicationInfo.uid
12792                            };
12793                            pkgList = new ArrayList<String>();
12794                            pkgList.add(mp.packageName);
12795                        }
12796                    }
12797                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12798                        // Send resources unavailable broadcast
12799                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12800                        // Update package code and resource paths
12801                        synchronized (mInstallLock) {
12802                            synchronized (mPackages) {
12803                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12804                                // Recheck for package again.
12805                                if (pkg == null) {
12806                                    Slog.w(TAG, " Package " + mp.packageName
12807                                            + " doesn't exist. Aborting move");
12808                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12809                                } else if (!mp.srcArgs.getCodePath().equals(
12810                                        pkg.applicationInfo.sourceDir)) {
12811                                    Slog.w(TAG, "Package " + mp.packageName
12812                                            + " code path changed from " + mp.srcArgs.getCodePath()
12813                                            + " to " + pkg.applicationInfo.sourceDir
12814                                            + " Aborting move and returning error");
12815                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12816                                } else {
12817                                    final String oldCodePath = pkg.mPath;
12818                                    final String newCodePath = mp.targetArgs.getCodePath();
12819                                    final String newResPath = mp.targetArgs.getResourcePath();
12820                                    final String newNativePath = mp.targetArgs
12821                                            .getNativeLibraryPath();
12822
12823                                    final File newNativeDir = new File(newNativePath);
12824
12825                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12826                                        // NOTE: We do not report any errors from the APK scan and library
12827                                        // copy at this point.
12828                                        NativeLibraryHelper.ApkHandle handle =
12829                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12830                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12831                                                handle, Build.SUPPORTED_ABIS);
12832                                        if (abi >= 0) {
12833                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12834                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12835                                        }
12836                                        handle.close();
12837                                    }
12838                                    final int[] users = sUserManager.getUserIds();
12839                                    for (int user : users) {
12840                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12841                                                newNativePath, user) < 0) {
12842                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12843                                        }
12844                                    }
12845
12846                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12847                                        pkg.mPath = newCodePath;
12848                                        // Move dex files around
12849                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12850                                            // Moving of dex files failed. Set
12851                                            // error code and abort move.
12852                                            pkg.mPath = pkg.mScanPath;
12853                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12854                                        }
12855                                    }
12856
12857                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12858                                        pkg.mScanPath = newCodePath;
12859                                        pkg.applicationInfo.sourceDir = newCodePath;
12860                                        pkg.applicationInfo.publicSourceDir = newResPath;
12861                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12862                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12863                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12864                                        ps.codePathString = ps.codePath.getPath();
12865                                        ps.resourcePath = new File(
12866                                                pkg.applicationInfo.publicSourceDir);
12867                                        ps.resourcePathString = ps.resourcePath.getPath();
12868                                        ps.nativeLibraryPathString = newNativePath;
12869                                        // Set the application info flag
12870                                        // correctly.
12871                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12872                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12873                                        } else {
12874                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12875                                        }
12876                                        ps.setFlags(pkg.applicationInfo.flags);
12877                                        mAppDirs.remove(oldCodePath);
12878                                        mAppDirs.put(newCodePath, pkg);
12879                                        // Persist settings
12880                                        mSettings.writeLPr();
12881                                    }
12882                                }
12883                            }
12884                        }
12885                        // Send resources available broadcast
12886                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12887                    }
12888                }
12889                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12890                    // Clean up failed installation
12891                    if (mp.targetArgs != null) {
12892                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12893                                -1);
12894                    }
12895                } else {
12896                    // Force a gc to clear things up.
12897                    Runtime.getRuntime().gc();
12898                    // Delete older code
12899                    synchronized (mInstallLock) {
12900                        mp.srcArgs.doPostDeleteLI(true);
12901                    }
12902                }
12903
12904                // Allow more operations on this file if we didn't fail because
12905                // an operation was already pending for this package.
12906                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12907                    synchronized (mPackages) {
12908                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12909                        if (pkg != null) {
12910                            pkg.mOperationPending = false;
12911                       }
12912                   }
12913                }
12914
12915                IPackageMoveObserver observer = mp.observer;
12916                if (observer != null) {
12917                    try {
12918                        observer.packageMoved(mp.packageName, returnCode);
12919                    } catch (RemoteException e) {
12920                        Log.i(TAG, "Observer no longer exists.");
12921                    }
12922                }
12923            }
12924        });
12925    }
12926
12927    @Override
12928    public boolean setInstallLocation(int loc) {
12929        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12930                null);
12931        if (getInstallLocation() == loc) {
12932            return true;
12933        }
12934        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12935                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12936            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12937                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12938            return true;
12939        }
12940        return false;
12941   }
12942
12943    @Override
12944    public int getInstallLocation() {
12945        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12946                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12947                PackageHelper.APP_INSTALL_AUTO);
12948    }
12949
12950    /** Called by UserManagerService */
12951    void cleanUpUserLILPw(int userHandle) {
12952        mDirtyUsers.remove(userHandle);
12953        mSettings.removeUserLPr(userHandle);
12954        mPendingBroadcasts.remove(userHandle);
12955        if (mInstaller != null) {
12956            // Technically, we shouldn't be doing this with the package lock
12957            // held.  However, this is very rare, and there is already so much
12958            // other disk I/O going on, that we'll let it slide for now.
12959            mInstaller.removeUserDataDirs(userHandle);
12960        }
12961    }
12962
12963    /** Called by UserManagerService */
12964    void createNewUserLILPw(int userHandle, File path) {
12965        if (mInstaller != null) {
12966            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12967        }
12968    }
12969
12970    @Override
12971    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12972        mContext.enforceCallingOrSelfPermission(
12973                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12974                "Only package verification agents can read the verifier device identity");
12975
12976        synchronized (mPackages) {
12977            return mSettings.getVerifierDeviceIdentityLPw();
12978        }
12979    }
12980
12981    @Override
12982    public void setPermissionEnforced(String permission, boolean enforced) {
12983        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12984        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12985            synchronized (mPackages) {
12986                if (mSettings.mReadExternalStorageEnforced == null
12987                        || mSettings.mReadExternalStorageEnforced != enforced) {
12988                    mSettings.mReadExternalStorageEnforced = enforced;
12989                    mSettings.writeLPr();
12990                }
12991            }
12992            // kill any non-foreground processes so we restart them and
12993            // grant/revoke the GID.
12994            final IActivityManager am = ActivityManagerNative.getDefault();
12995            if (am != null) {
12996                final long token = Binder.clearCallingIdentity();
12997                try {
12998                    am.killProcessesBelowForeground("setPermissionEnforcement");
12999                } catch (RemoteException e) {
13000                } finally {
13001                    Binder.restoreCallingIdentity(token);
13002                }
13003            }
13004        } else {
13005            throw new IllegalArgumentException("No selective enforcement for " + permission);
13006        }
13007    }
13008
13009    @Override
13010    @Deprecated
13011    public boolean isPermissionEnforced(String permission) {
13012        return true;
13013    }
13014
13015    @Override
13016    public boolean isStorageLow() {
13017        final long token = Binder.clearCallingIdentity();
13018        try {
13019            final DeviceStorageMonitorInternal
13020                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13021            if (dsm != null) {
13022                return dsm.isMemoryLow();
13023            } else {
13024                return false;
13025            }
13026        } finally {
13027            Binder.restoreCallingIdentity(token);
13028        }
13029    }
13030
13031    @Override
13032    public IPackageInstaller getPackageInstaller() {
13033        return mInstallerService;
13034    }
13035}
13036