PackageManagerService.java revision 96f4e595ba09bf9a5a5b58882d6e4cebdcf06503
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.PackageParserException;
97import android.content.pm.PackageParser;
98import android.content.pm.PackageStats;
99import android.content.pm.PackageUserState;
100import android.content.pm.ParceledListSlice;
101import android.content.pm.PermissionGroupInfo;
102import android.content.pm.PermissionInfo;
103import android.content.pm.ProviderInfo;
104import android.content.pm.ResolveInfo;
105import android.content.pm.ServiceInfo;
106import android.content.pm.Signature;
107import android.content.pm.VerificationParams;
108import android.content.pm.VerifierDeviceIdentity;
109import android.content.pm.VerifierInfo;
110import android.content.res.Resources;
111import android.hardware.display.DisplayManager;
112import android.net.Uri;
113import android.os.Binder;
114import android.os.Build;
115import android.os.Bundle;
116import android.os.Environment;
117import android.os.Environment.UserEnvironment;
118import android.os.FileObserver;
119import android.os.FileUtils;
120import android.os.Handler;
121import android.os.IBinder;
122import android.os.Looper;
123import android.os.Message;
124import android.os.Parcel;
125import android.os.ParcelFileDescriptor;
126import android.os.Process;
127import android.os.RemoteException;
128import android.os.SELinux;
129import android.os.ServiceManager;
130import android.os.SystemClock;
131import android.os.SystemProperties;
132import android.os.UserHandle;
133import android.os.UserManager;
134import android.security.KeyStore;
135import android.security.SystemKeyStore;
136import android.system.ErrnoException;
137import android.system.Os;
138import android.system.StructStat;
139import android.text.TextUtils;
140import android.util.ArraySet;
141import android.util.AtomicFile;
142import android.util.DisplayMetrics;
143import android.util.EventLog;
144import android.util.Log;
145import android.util.LogPrinter;
146import android.util.PrintStreamPrinter;
147import android.util.Slog;
148import android.util.SparseArray;
149import android.util.Xml;
150import android.view.Display;
151
152import java.io.BufferedInputStream;
153import java.io.BufferedOutputStream;
154import java.io.File;
155import java.io.FileDescriptor;
156import java.io.FileInputStream;
157import java.io.FileNotFoundException;
158import java.io.FileOutputStream;
159import java.io.FileReader;
160import java.io.FilenameFilter;
161import java.io.IOException;
162import java.io.InputStream;
163import java.io.PrintWriter;
164import java.nio.charset.StandardCharsets;
165import java.security.NoSuchAlgorithmException;
166import java.security.PublicKey;
167import java.security.cert.CertificateEncodingException;
168import java.security.cert.CertificateException;
169import java.text.SimpleDateFormat;
170import java.util.ArrayList;
171import java.util.Arrays;
172import java.util.Collection;
173import java.util.Collections;
174import java.util.Comparator;
175import java.util.Date;
176import java.util.HashMap;
177import java.util.HashSet;
178import java.util.Iterator;
179import java.util.List;
180import java.util.Map;
181import java.util.Set;
182import java.util.concurrent.atomic.AtomicBoolean;
183import java.util.concurrent.atomic.AtomicLong;
184
185import dalvik.system.DexFile;
186import dalvik.system.StaleDexCacheError;
187import dalvik.system.VMRuntime;
188
189import libcore.io.IoUtils;
190
191/**
192 * Keep track of all those .apks everywhere.
193 *
194 * This is very central to the platform's security; please run the unit
195 * tests whenever making modifications here:
196 *
197mmm frameworks/base/tests/AndroidTests
198adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
199adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
200 *
201 * {@hide}
202 */
203public class PackageManagerService extends IPackageManager.Stub {
204    static final String TAG = "PackageManager";
205    static final boolean DEBUG_SETTINGS = false;
206    static final boolean DEBUG_PREFERRED = false;
207    static final boolean DEBUG_UPGRADE = false;
208    private static final boolean DEBUG_INSTALL = false;
209    private static final boolean DEBUG_REMOVE = false;
210    private static final boolean DEBUG_BROADCASTS = false;
211    private static final boolean DEBUG_SHOW_INFO = false;
212    private static final boolean DEBUG_PACKAGE_INFO = false;
213    private static final boolean DEBUG_INTENT_MATCHING = false;
214    private static final boolean DEBUG_PACKAGE_SCANNING = false;
215    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
216    private static final boolean DEBUG_VERIFY = false;
217    private static final boolean DEBUG_DEXOPT = false;
218
219    private static final int RADIO_UID = Process.PHONE_UID;
220    private static final int LOG_UID = Process.LOG_UID;
221    private static final int NFC_UID = Process.NFC_UID;
222    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
223    private static final int SHELL_UID = Process.SHELL_UID;
224
225    // Cap the size of permission trees that 3rd party apps can define
226    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
227
228    private static final int REMOVE_EVENTS =
229        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
230    private static final int ADD_EVENTS =
231        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
232
233    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
234    // Suffix used during package installation when copying/moving
235    // package apks to install directory.
236    private static final String INSTALL_PACKAGE_SUFFIX = "-";
237
238    static final int SCAN_MONITOR = 1<<0;
239    static final int SCAN_NO_DEX = 1<<1;
240    static final int SCAN_FORCE_DEX = 1<<2;
241    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
242    static final int SCAN_NEW_INSTALL = 1<<4;
243    static final int SCAN_NO_PATHS = 1<<5;
244    static final int SCAN_UPDATE_TIME = 1<<6;
245    static final int SCAN_DEFER_DEX = 1<<7;
246    static final int SCAN_BOOTING = 1<<8;
247    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
248    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
249
250    static final int REMOVE_CHATTY = 1<<16;
251
252    /**
253     * Timeout (in milliseconds) after which the watchdog should declare that
254     * our handler thread is wedged.  The usual default for such things is one
255     * minute but we sometimes do very lengthy I/O operations on this thread,
256     * such as installing multi-gigabyte applications, so ours needs to be longer.
257     */
258    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
259
260    /**
261     * Whether verification is enabled by default.
262     */
263    private static final boolean DEFAULT_VERIFY_ENABLE = true;
264
265    /**
266     * The default maximum time to wait for the verification agent to return in
267     * milliseconds.
268     */
269    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
270
271    /**
272     * The default response for package verification timeout.
273     *
274     * This can be either PackageManager.VERIFICATION_ALLOW or
275     * PackageManager.VERIFICATION_REJECT.
276     */
277    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
278
279    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
280
281    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
282            DEFAULT_CONTAINER_PACKAGE,
283            "com.android.defcontainer.DefaultContainerService");
284
285    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
286
287    private static final String LIB_DIR_NAME = "lib";
288    private static final String LIB64_DIR_NAME = "lib64";
289
290    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
291
292    static final String mTempContainerPrefix = "smdl2tmp";
293
294    private static String sPreferredInstructionSet;
295
296    final ServiceThread mHandlerThread;
297
298    private static final String IDMAP_PREFIX = "/data/resource-cache/";
299    private static final String IDMAP_SUFFIX = "@idmap";
300
301    final PackageHandler mHandler;
302
303    final int mSdkVersion = Build.VERSION.SDK_INT;
304
305    final Context mContext;
306    final boolean mFactoryTest;
307    final boolean mOnlyCore;
308    final DisplayMetrics mMetrics;
309    final int mDefParseFlags;
310    final String[] mSeparateProcesses;
311
312    // This is where all application persistent data goes.
313    final File mAppDataDir;
314
315    // This is where all application persistent data goes for secondary users.
316    final File mUserAppDataDir;
317
318    /** The location for ASEC container files on internal storage. */
319    final String mAsecInternalPath;
320
321    // This is the object monitoring the framework dir.
322    final FileObserver mFrameworkInstallObserver;
323
324    // This is the object monitoring the system app dir.
325    final FileObserver mSystemInstallObserver;
326
327    // This is the object monitoring the privileged system app dir.
328    final FileObserver mPrivilegedInstallObserver;
329
330    // This is the object monitoring the vendor app dir.
331    final FileObserver mVendorInstallObserver;
332
333    // This is the object monitoring the vendor overlay package dir.
334    final FileObserver mVendorOverlayInstallObserver;
335
336    // This is the object monitoring the OEM app dir.
337    final FileObserver mOemInstallObserver;
338
339    // This is the object monitoring mAppInstallDir.
340    final FileObserver mAppInstallObserver;
341
342    // This is the object monitoring mDrmAppPrivateInstallDir.
343    final FileObserver mDrmAppInstallObserver;
344
345    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
346    // LOCK HELD.  Can be called with mInstallLock held.
347    final Installer mInstaller;
348
349    final File mAppInstallDir;
350
351    /**
352     * Directory to which applications installed internally have native
353     * libraries copied.
354     */
355    private File mAppLibInstallDir;
356
357    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
358    // apps.
359    final File mDrmAppPrivateInstallDir;
360
361    final File mAppStagingDir;
362
363    // ----------------------------------------------------------------
364
365    // Lock for state used when installing and doing other long running
366    // operations.  Methods that must be called with this lock held have
367    // the suffix "LI".
368    final Object mInstallLock = new Object();
369
370    // These are the directories in the 3rd party applications installed dir
371    // that we have currently loaded packages from.  Keys are the application's
372    // installed zip file (absolute codePath), and values are Package.
373    final HashMap<String, PackageParser.Package> mAppDirs =
374            new HashMap<String, PackageParser.Package>();
375
376    // Information for the parser to write more useful error messages.
377    int mLastScanError;
378
379    // ----------------------------------------------------------------
380
381    // Keys are String (package name), values are Package.  This also serves
382    // as the lock for the global state.  Methods that must be called with
383    // this lock held have the prefix "LP".
384    final HashMap<String, PackageParser.Package> mPackages =
385            new HashMap<String, PackageParser.Package>();
386
387    // Tracks available target package names -> overlay package paths.
388    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
389        new HashMap<String, HashMap<String, PackageParser.Package>>();
390
391    final Settings mSettings;
392    boolean mRestoredSettings;
393
394    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
395    int[] mGlobalGids;
396
397    // These are the built-in uid -> permission mappings that were read from the
398    // etc/permissions.xml file.
399    final SparseArray<HashSet<String>> mSystemPermissions =
400            new SparseArray<HashSet<String>>();
401
402    static final class SharedLibraryEntry {
403        final String path;
404        final String apk;
405
406        SharedLibraryEntry(String _path, String _apk) {
407            path = _path;
408            apk = _apk;
409        }
410    }
411
412    // These are the built-in shared libraries that were read from the
413    // etc/permissions.xml file.
414    final HashMap<String, SharedLibraryEntry> mSharedLibraries
415            = new HashMap<String, SharedLibraryEntry>();
416
417    // These are the features this devices supports that were read from the
418    // etc/permissions.xml file.
419    final HashMap<String, FeatureInfo> mAvailableFeatures =
420            new HashMap<String, FeatureInfo>();
421
422    // If mac_permissions.xml was found for seinfo labeling.
423    boolean mFoundPolicyFile;
424
425    // If a recursive restorecon of /data/data/<pkg> is needed.
426    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
427
428    // All available activities, for your resolving pleasure.
429    final ActivityIntentResolver mActivities =
430            new ActivityIntentResolver();
431
432    // All available receivers, for your resolving pleasure.
433    final ActivityIntentResolver mReceivers =
434            new ActivityIntentResolver();
435
436    // All available services, for your resolving pleasure.
437    final ServiceIntentResolver mServices = new ServiceIntentResolver();
438
439    // All available providers, for your resolving pleasure.
440    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
441
442    // Mapping from provider base names (first directory in content URI codePath)
443    // to the provider information.
444    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
445            new HashMap<String, PackageParser.Provider>();
446
447    // Mapping from instrumentation class names to info about them.
448    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
449            new HashMap<ComponentName, PackageParser.Instrumentation>();
450
451    // Mapping from permission names to info about them.
452    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
453            new HashMap<String, PackageParser.PermissionGroup>();
454
455    // Packages whose data we have transfered into another package, thus
456    // should no longer exist.
457    final HashSet<String> mTransferedPackages = new HashSet<String>();
458
459    // Broadcast actions that are only available to the system.
460    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
461
462    /** List of packages waiting for verification. */
463    final SparseArray<PackageVerificationState> mPendingVerification
464            = new SparseArray<PackageVerificationState>();
465
466    final PackageInstallerService mInstallerService;
467
468    HashSet<PackageParser.Package> mDeferredDexOpt = null;
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    boolean mSystemReady;
474    boolean mSafeMode;
475    boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new HashMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsFirstBoot = false;
625
626        boolean isFirstBoot() {
627            return mIsFirstBoot;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsFirstBoot = true;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                args.observer.packageInstalled(res.name, res.returnCode);
1081                            } catch (RemoteException e) {
1082                                Slog.i(TAG, "Observer no longer exists.");
1083                            }
1084                        }
1085                        if (args.observer2 != null) {
1086                            try {
1087                                Bundle extras = extrasForInstallResult(res);
1088                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1089                            } catch (RemoteException e) {
1090                                Slog.i(TAG, "Observer no longer exists.");
1091                            }
1092                        }
1093                    } else {
1094                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1095                    }
1096                } break;
1097                case UPDATED_MEDIA_STATUS: {
1098                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1099                    boolean reportStatus = msg.arg1 == 1;
1100                    boolean doGc = msg.arg2 == 1;
1101                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1102                    if (doGc) {
1103                        // Force a gc to clear up stale containers.
1104                        Runtime.getRuntime().gc();
1105                    }
1106                    if (msg.obj != null) {
1107                        @SuppressWarnings("unchecked")
1108                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1109                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1110                        // Unload containers
1111                        unloadAllContainers(args);
1112                    }
1113                    if (reportStatus) {
1114                        try {
1115                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1116                            PackageHelper.getMountService().finishMediaUpdate();
1117                        } catch (RemoteException e) {
1118                            Log.e(TAG, "MountService not running?");
1119                        }
1120                    }
1121                } break;
1122                case WRITE_SETTINGS: {
1123                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124                    synchronized (mPackages) {
1125                        removeMessages(WRITE_SETTINGS);
1126                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1127                        mSettings.writeLPr();
1128                        mDirtyUsers.clear();
1129                    }
1130                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131                } break;
1132                case WRITE_PACKAGE_RESTRICTIONS: {
1133                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134                    synchronized (mPackages) {
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        for (int userId : mDirtyUsers) {
1137                            mSettings.writePackageRestrictionsLPr(userId);
1138                        }
1139                        mDirtyUsers.clear();
1140                    }
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142                } break;
1143                case CHECK_PENDING_VERIFICATION: {
1144                    final int verificationId = msg.arg1;
1145                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1146
1147                    if ((state != null) && !state.timeoutExtended()) {
1148                        final InstallArgs args = state.getInstallArgs();
1149                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of "
1156                                    + args.packageURI.toString());
1157                            state.setVerifierResponse(Binder.getCallingUid(),
1158                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1159                            broadcastPackageVerified(verificationId, args.packageURI,
1160                                    PackageManager.VERIFICATION_ALLOW,
1161                                    state.getInstallArgs().getUser());
1162                            try {
1163                                ret = args.copyApk(mContainerService, true);
1164                            } catch (RemoteException e) {
1165                                Slog.e(TAG, "Could not contact the ContainerService");
1166                            }
1167                        } else {
1168                            broadcastPackageVerified(verificationId, args.packageURI,
1169                                    PackageManager.VERIFICATION_REJECT,
1170                                    state.getInstallArgs().getUser());
1171                        }
1172
1173                        processPendingInstall(args, ret);
1174                        mHandler.sendEmptyMessage(MCS_UNBIND);
1175                    }
1176                    break;
1177                }
1178                case PACKAGE_VERIFIED: {
1179                    final int verificationId = msg.arg1;
1180
1181                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1182                    if (state == null) {
1183                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1184                        break;
1185                    }
1186
1187                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1188
1189                    state.setVerifierResponse(response.callerUid, response.code);
1190
1191                    if (state.isVerificationComplete()) {
1192                        mPendingVerification.remove(verificationId);
1193
1194                        final InstallArgs args = state.getInstallArgs();
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, args.packageURI,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final IPackageManager main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mMetrics = new DisplayMetrics();
1299        mSettings = new Settings(context);
1300        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1301                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1302        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1303                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1304        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1305                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312
1313        String separateProcesses = SystemProperties.get("debug.separate_processes");
1314        if (separateProcesses != null && separateProcesses.length() > 0) {
1315            if ("*".equals(separateProcesses)) {
1316                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1317                mSeparateProcesses = null;
1318                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1319            } else {
1320                mDefParseFlags = 0;
1321                mSeparateProcesses = separateProcesses.split(",");
1322                Slog.w(TAG, "Running with debug.separate_processes: "
1323                        + separateProcesses);
1324            }
1325        } else {
1326            mDefParseFlags = 0;
1327            mSeparateProcesses = null;
1328        }
1329
1330        mInstaller = installer;
1331
1332        getDefaultDisplayMetrics(context, mMetrics);
1333
1334        synchronized (mInstallLock) {
1335        // writer
1336        synchronized (mPackages) {
1337            mHandlerThread = new ServiceThread(TAG,
1338                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1339            mHandlerThread.start();
1340            mHandler = new PackageHandler(mHandlerThread.getLooper());
1341            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1342
1343            File dataDir = Environment.getDataDirectory();
1344            mAppDataDir = new File(dataDir, "data");
1345            mAppInstallDir = new File(dataDir, "app");
1346            mAppLibInstallDir = new File(dataDir, "app-lib");
1347            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1348            mUserAppDataDir = new File(dataDir, "user");
1349            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1350            mAppStagingDir = new File(dataDir, "app-staging");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Read permissions and features from system
1356            readPermissions(Environment.buildPath(
1357                    Environment.getRootDirectory(), "etc", "permissions"), false);
1358            // Only read features from OEM
1359            readPermissions(Environment.buildPath(
1360                    Environment.getOemDirectory(), "etc", "permissions"), true);
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            String bootClassPath = System.getProperty("java.boot.class.path");
1393            if (bootClassPath != null) {
1394                String[] paths = splitString(bootClassPath, ':');
1395                for (int i=0; i<paths.length; i++) {
1396                    alreadyDexOpted.add(paths[i]);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            boolean didDexOptLibraryOrTool = false;
1403
1404            final List<String> instructionSets = getAllInstructionSets();
1405
1406            /**
1407             * Ensure all external libraries have had dexopt run on them.
1408             */
1409            if (mSharedLibraries.size() > 0) {
1410                // NOTE: For now, we're compiling these system "shared libraries"
1411                // (and framework jars) into all available architectures. It's possible
1412                // to compile them only when we come across an app that uses them (there's
1413                // already logic for that in scanPackageLI) but that adds some complexity.
1414                for (String instructionSet : instructionSets) {
1415                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1416                        final String lib = libEntry.path;
1417                        if (lib == null) {
1418                            continue;
1419                        }
1420
1421                        try {
1422                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1423                                alreadyDexOpted.add(lib);
1424
1425                                // The list of "shared libraries" we have at this point is
1426                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1427                                didDexOptLibraryOrTool = true;
1428                            }
1429                        } catch (FileNotFoundException e) {
1430                            Slog.w(TAG, "Library not found: " + lib);
1431                        } catch (IOException e) {
1432                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1433                                    + e.getMessage());
1434                        }
1435                    }
1436                }
1437            }
1438
1439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1440
1441            // Gross hack for now: we know this file doesn't contain any
1442            // code, so don't dexopt it to avoid the resulting log spew.
1443            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1444
1445            // Gross hack for now: we know this file is only part of
1446            // the boot class path for art, so don't dexopt it to
1447            // avoid the resulting log spew.
1448            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1449
1450            /**
1451             * And there are a number of commands implemented in Java, which
1452             * we currently need to do the dexopt on so that they can be
1453             * run from a non-root shell.
1454             */
1455            String[] frameworkFiles = frameworkDir.list();
1456            if (frameworkFiles != null) {
1457                // TODO: We could compile these only for the most preferred ABI. We should
1458                // first double check that the dex files for these commands are not referenced
1459                // by other system apps.
1460                for (String instructionSet : instructionSets) {
1461                    for (int i=0; i<frameworkFiles.length; i++) {
1462                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1463                        String path = libPath.getPath();
1464                        // Skip the file if we already did it.
1465                        if (alreadyDexOpted.contains(path)) {
1466                            continue;
1467                        }
1468                        // Skip the file if it is not a type we want to dexopt.
1469                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1470                            continue;
1471                        }
1472                        try {
1473                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1474                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1475                                didDexOptLibraryOrTool = true;
1476                            }
1477                        } catch (FileNotFoundException e) {
1478                            Slog.w(TAG, "Jar not found: " + path);
1479                        } catch (IOException e) {
1480                            Slog.w(TAG, "Exception reading jar: " + path, e);
1481                        }
1482                    }
1483                }
1484            }
1485
1486            if (didDexOptLibraryOrTool) {
1487                // If we dexopted a library or tool, then something on the system has
1488                // changed. Consider this significant, and wipe away all other
1489                // existing dexopt files to ensure we don't leave any dangling around.
1490                //
1491                // Additionally, delete all dex files from the root directory
1492                // since there shouldn't be any there anyway.
1493                //
1494                // TODO: This should be revisited because it isn't as good an indicator
1495                // as it used to be. It used to include the boot classpath but at some point
1496                // DexFile.isDexOptNeeded started returning false for the boot
1497                // class path files in all cases. It is very possible in a
1498                // small maintenance release update that the library and tool
1499                // jars may be unchanged but APK could be removed resulting in
1500                // unused dalvik-cache files.
1501                mInstaller.pruneDexCache();
1502            }
1503
1504            // Collect vendor overlay packages.
1505            // (Do this before scanning any apps.)
1506            // For security and version matching reason, only consider
1507            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1508            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1509            mVendorOverlayInstallObserver = new AppDirObserver(
1510                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1511            mVendorOverlayInstallObserver.startWatching();
1512            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1513                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1514
1515            // Find base frameworks (resource packages without code).
1516            mFrameworkInstallObserver = new AppDirObserver(
1517                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1518            mFrameworkInstallObserver.startWatching();
1519            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR
1521                    | PackageParser.PARSE_IS_PRIVILEGED,
1522                    scanMode | SCAN_NO_DEX, 0);
1523
1524            // Collected privileged system packages.
1525            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1526            mPrivilegedInstallObserver = new AppDirObserver(
1527                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1528            mPrivilegedInstallObserver.startWatching();
1529                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1530                        | PackageParser.PARSE_IS_SYSTEM_DIR
1531                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1532
1533            // Collect ordinary system packages.
1534            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1535            mSystemInstallObserver = new AppDirObserver(
1536                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1537            mSystemInstallObserver.startWatching();
1538            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1540
1541            // Collect all vendor packages.
1542            File vendorAppDir = new File("/vendor/app");
1543            try {
1544                vendorAppDir = vendorAppDir.getCanonicalFile();
1545            } catch (IOException e) {
1546                // failed to look up canonical path, continue with original one
1547            }
1548            mVendorInstallObserver = new AppDirObserver(
1549                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1550            mVendorInstallObserver.startWatching();
1551            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1553
1554            // Collect all OEM packages.
1555            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1556            mOemInstallObserver = new AppDirObserver(
1557                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1558            mOemInstallObserver.startWatching();
1559            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1560                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1561
1562            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1563            mInstaller.moveFiles();
1564
1565            // Prune any system packages that no longer exist.
1566            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1567            if (!mOnlyCore) {
1568                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1569                while (psit.hasNext()) {
1570                    PackageSetting ps = psit.next();
1571
1572                    /*
1573                     * If this is not a system app, it can't be a
1574                     * disable system app.
1575                     */
1576                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1577                        continue;
1578                    }
1579
1580                    /*
1581                     * If the package is scanned, it's not erased.
1582                     */
1583                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1584                    if (scannedPkg != null) {
1585                        /*
1586                         * If the system app is both scanned and in the
1587                         * disabled packages list, then it must have been
1588                         * added via OTA. Remove it from the currently
1589                         * scanned package so the previously user-installed
1590                         * application can be scanned.
1591                         */
1592                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1593                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1594                                    + "; removing system app");
1595                            removePackageLI(ps, true);
1596                        }
1597
1598                        continue;
1599                    }
1600
1601                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1602                        psit.remove();
1603                        String msg = "System package " + ps.name
1604                                + " no longer exists; wiping its data";
1605                        reportSettingsProblem(Log.WARN, msg);
1606                        removeDataDirsLI(ps.name);
1607                    } else {
1608                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1609                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1610                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1611                        }
1612                    }
1613                }
1614            }
1615
1616            //look for any incomplete package installations
1617            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1618            //clean up list
1619            for(int i = 0; i < deletePkgsList.size(); i++) {
1620                //clean up here
1621                cleanupInstallFailedPackage(deletePkgsList.get(i));
1622            }
1623            //delete tmp files
1624            deleteTempPackageFiles();
1625
1626            // Remove any shared userIDs that have no associated packages
1627            mSettings.pruneSharedUsersLPw();
1628
1629            if (!mOnlyCore) {
1630                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1631                        SystemClock.uptimeMillis());
1632                mAppInstallObserver = new AppDirObserver(
1633                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1634                mAppInstallObserver.startWatching();
1635                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1636
1637                mDrmAppInstallObserver = new AppDirObserver(
1638                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1639                mDrmAppInstallObserver.startWatching();
1640                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1641                        scanMode, 0);
1642
1643                /**
1644                 * Remove disable package settings for any updated system
1645                 * apps that were removed via an OTA. If they're not a
1646                 * previously-updated app, remove them completely.
1647                 * Otherwise, just revoke their system-level permissions.
1648                 */
1649                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1650                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1651                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1652
1653                    String msg;
1654                    if (deletedPkg == null) {
1655                        msg = "Updated system package " + deletedAppName
1656                                + " no longer exists; wiping its data";
1657                        removeDataDirsLI(deletedAppName);
1658                    } else {
1659                        msg = "Updated system app + " + deletedAppName
1660                                + " no longer present; removing system privileges for "
1661                                + deletedAppName;
1662
1663                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1664
1665                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1666                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1667                    }
1668                    reportSettingsProblem(Log.WARN, msg);
1669                }
1670            } else {
1671                mAppInstallObserver = null;
1672                mDrmAppInstallObserver = null;
1673            }
1674
1675            // Now that we know all of the shared libraries, update all clients to have
1676            // the correct library paths.
1677            updateAllSharedLibrariesLPw();
1678
1679            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1680                // NOTE: We ignore potential failures here during a system scan (like
1681                // the rest of the commands above) because there's precious little we
1682                // can do about it. A settings error is reported, though.
1683                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1684                        false /* force dexopt */, false /* defer dexopt */);
1685            }
1686
1687            // Now that we know all the packages we are keeping,
1688            // read and update their last usage times.
1689            mPackageUsage.readLP();
1690
1691            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1692                    SystemClock.uptimeMillis());
1693            Slog.i(TAG, "Time to scan packages: "
1694                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1695                    + " seconds");
1696
1697            // If the platform SDK has changed since the last time we booted,
1698            // we need to re-grant app permission to catch any new ones that
1699            // appear.  This is really a hack, and means that apps can in some
1700            // cases get permissions that the user didn't initially explicitly
1701            // allow...  it would be nice to have some better way to handle
1702            // this situation.
1703            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1704                    != mSdkVersion;
1705            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1706                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1707                    + "; regranting permissions for internal storage");
1708            mSettings.mInternalSdkPlatform = mSdkVersion;
1709
1710            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1711                    | (regrantPermissions
1712                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1713                            : 0));
1714
1715            // If this is the first boot, and it is a normal boot, then
1716            // we need to initialize the default preferred apps.
1717            if (!mRestoredSettings && !onlyCore) {
1718                mSettings.readDefaultPreferredAppsLPw(this, 0);
1719            }
1720
1721            // All the changes are done during package scanning.
1722            mSettings.updateInternalDatabaseVersion();
1723
1724            // can downgrade to reader
1725            mSettings.writeLPr();
1726
1727            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1728                    SystemClock.uptimeMillis());
1729
1730
1731            mRequiredVerifierPackage = getRequiredVerifierLPr();
1732        } // synchronized (mPackages)
1733        } // synchronized (mInstallLock)
1734
1735        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1736
1737        // Now after opening every single application zip, make sure they
1738        // are all flushed.  Not really needed, but keeps things nice and
1739        // tidy.
1740        Runtime.getRuntime().gc();
1741    }
1742
1743    @Override
1744    public boolean isFirstBoot() {
1745        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1746    }
1747
1748    @Override
1749    public boolean isOnlyCoreApps() {
1750        return mOnlyCore;
1751    }
1752
1753    private String getRequiredVerifierLPr() {
1754        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1755        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1756                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1757
1758        String requiredVerifier = null;
1759
1760        final int N = receivers.size();
1761        for (int i = 0; i < N; i++) {
1762            final ResolveInfo info = receivers.get(i);
1763
1764            if (info.activityInfo == null) {
1765                continue;
1766            }
1767
1768            final String packageName = info.activityInfo.packageName;
1769
1770            final PackageSetting ps = mSettings.mPackages.get(packageName);
1771            if (ps == null) {
1772                continue;
1773            }
1774
1775            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1776            if (!gp.grantedPermissions
1777                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1778                continue;
1779            }
1780
1781            if (requiredVerifier != null) {
1782                throw new RuntimeException("There can be only one required verifier");
1783            }
1784
1785            requiredVerifier = packageName;
1786        }
1787
1788        return requiredVerifier;
1789    }
1790
1791    @Override
1792    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1793            throws RemoteException {
1794        try {
1795            return super.onTransact(code, data, reply, flags);
1796        } catch (RuntimeException e) {
1797            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1798                Slog.wtf(TAG, "Package Manager Crash", e);
1799            }
1800            throw e;
1801        }
1802    }
1803
1804    void cleanupInstallFailedPackage(PackageSetting ps) {
1805        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1806        removeDataDirsLI(ps.name);
1807        if (ps.codePath != null) {
1808            if (!ps.codePath.delete()) {
1809                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1810            }
1811        }
1812        if (ps.resourcePath != null) {
1813            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1814                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1815            }
1816        }
1817        mSettings.removePackageLPw(ps.name);
1818    }
1819
1820    void readPermissions(File libraryDir, boolean onlyFeatures) {
1821        // Read permissions from .../etc/permission directory.
1822        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1823            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1824            return;
1825        }
1826        if (!libraryDir.canRead()) {
1827            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1828            return;
1829        }
1830
1831        // Iterate over the files in the directory and scan .xml files
1832        for (File f : libraryDir.listFiles()) {
1833            // We'll read platform.xml last
1834            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1835                continue;
1836            }
1837
1838            if (!f.getPath().endsWith(".xml")) {
1839                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1840                continue;
1841            }
1842            if (!f.canRead()) {
1843                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1844                continue;
1845            }
1846
1847            readPermissionsFromXml(f, onlyFeatures);
1848        }
1849
1850        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1851        final File permFile = new File(Environment.getRootDirectory(),
1852                "etc/permissions/platform.xml");
1853        readPermissionsFromXml(permFile, onlyFeatures);
1854    }
1855
1856    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1857        FileReader permReader = null;
1858        try {
1859            permReader = new FileReader(permFile);
1860        } catch (FileNotFoundException e) {
1861            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1862            return;
1863        }
1864
1865        try {
1866            XmlPullParser parser = Xml.newPullParser();
1867            parser.setInput(permReader);
1868
1869            XmlUtils.beginDocument(parser, "permissions");
1870
1871            while (true) {
1872                XmlUtils.nextElement(parser);
1873                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1874                    break;
1875                }
1876
1877                String name = parser.getName();
1878                if ("group".equals(name) && !onlyFeatures) {
1879                    String gidStr = parser.getAttributeValue(null, "gid");
1880                    if (gidStr != null) {
1881                        int gid = Process.getGidForName(gidStr);
1882                        mGlobalGids = appendInt(mGlobalGids, gid);
1883                    } else {
1884                        Slog.w(TAG, "<group> without gid at "
1885                                + parser.getPositionDescription());
1886                    }
1887
1888                    XmlUtils.skipCurrentTag(parser);
1889                    continue;
1890                } else if ("permission".equals(name) && !onlyFeatures) {
1891                    String perm = parser.getAttributeValue(null, "name");
1892                    if (perm == null) {
1893                        Slog.w(TAG, "<permission> without name at "
1894                                + parser.getPositionDescription());
1895                        XmlUtils.skipCurrentTag(parser);
1896                        continue;
1897                    }
1898                    perm = perm.intern();
1899                    readPermission(parser, perm);
1900
1901                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1902                    String perm = parser.getAttributeValue(null, "name");
1903                    if (perm == null) {
1904                        Slog.w(TAG, "<assign-permission> without name at "
1905                                + parser.getPositionDescription());
1906                        XmlUtils.skipCurrentTag(parser);
1907                        continue;
1908                    }
1909                    String uidStr = parser.getAttributeValue(null, "uid");
1910                    if (uidStr == null) {
1911                        Slog.w(TAG, "<assign-permission> without uid at "
1912                                + parser.getPositionDescription());
1913                        XmlUtils.skipCurrentTag(parser);
1914                        continue;
1915                    }
1916                    int uid = Process.getUidForName(uidStr);
1917                    if (uid < 0) {
1918                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1919                                + uidStr + "\" at "
1920                                + parser.getPositionDescription());
1921                        XmlUtils.skipCurrentTag(parser);
1922                        continue;
1923                    }
1924                    perm = perm.intern();
1925                    HashSet<String> perms = mSystemPermissions.get(uid);
1926                    if (perms == null) {
1927                        perms = new HashSet<String>();
1928                        mSystemPermissions.put(uid, perms);
1929                    }
1930                    perms.add(perm);
1931                    XmlUtils.skipCurrentTag(parser);
1932
1933                } else if ("library".equals(name) && !onlyFeatures) {
1934                    String lname = parser.getAttributeValue(null, "name");
1935                    String lfile = parser.getAttributeValue(null, "file");
1936                    if (lname == null) {
1937                        Slog.w(TAG, "<library> without name at "
1938                                + parser.getPositionDescription());
1939                    } else if (lfile == null) {
1940                        Slog.w(TAG, "<library> without file at "
1941                                + parser.getPositionDescription());
1942                    } else {
1943                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1944                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1945                    }
1946                    XmlUtils.skipCurrentTag(parser);
1947                    continue;
1948
1949                } else if ("feature".equals(name)) {
1950                    String fname = parser.getAttributeValue(null, "name");
1951                    if (fname == null) {
1952                        Slog.w(TAG, "<feature> without name at "
1953                                + parser.getPositionDescription());
1954                    } else {
1955                        //Log.i(TAG, "Got feature " + fname);
1956                        FeatureInfo fi = new FeatureInfo();
1957                        fi.name = fname;
1958                        mAvailableFeatures.put(fname, fi);
1959                    }
1960                    XmlUtils.skipCurrentTag(parser);
1961                    continue;
1962
1963                } else {
1964                    XmlUtils.skipCurrentTag(parser);
1965                    continue;
1966                }
1967
1968            }
1969            permReader.close();
1970        } catch (XmlPullParserException e) {
1971            Slog.w(TAG, "Got execption parsing permissions.", e);
1972        } catch (IOException e) {
1973            Slog.w(TAG, "Got execption parsing permissions.", e);
1974        }
1975    }
1976
1977    void readPermission(XmlPullParser parser, String name)
1978            throws IOException, XmlPullParserException {
1979
1980        name = name.intern();
1981
1982        BasePermission bp = mSettings.mPermissions.get(name);
1983        if (bp == null) {
1984            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1985            mSettings.mPermissions.put(name, bp);
1986        }
1987        int outerDepth = parser.getDepth();
1988        int type;
1989        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1990               && (type != XmlPullParser.END_TAG
1991                       || parser.getDepth() > outerDepth)) {
1992            if (type == XmlPullParser.END_TAG
1993                    || type == XmlPullParser.TEXT) {
1994                continue;
1995            }
1996
1997            String tagName = parser.getName();
1998            if ("group".equals(tagName)) {
1999                String gidStr = parser.getAttributeValue(null, "gid");
2000                if (gidStr != null) {
2001                    int gid = Process.getGidForName(gidStr);
2002                    bp.gids = appendInt(bp.gids, gid);
2003                } else {
2004                    Slog.w(TAG, "<group> without gid at "
2005                            + parser.getPositionDescription());
2006                }
2007            }
2008            XmlUtils.skipCurrentTag(parser);
2009        }
2010    }
2011
2012    static int[] appendInts(int[] cur, int[] add) {
2013        if (add == null) return cur;
2014        if (cur == null) return add;
2015        final int N = add.length;
2016        for (int i=0; i<N; i++) {
2017            cur = appendInt(cur, add[i]);
2018        }
2019        return cur;
2020    }
2021
2022    static int[] removeInts(int[] cur, int[] rem) {
2023        if (rem == null) return cur;
2024        if (cur == null) return cur;
2025        final int N = rem.length;
2026        for (int i=0; i<N; i++) {
2027            cur = removeInt(cur, rem[i]);
2028        }
2029        return cur;
2030    }
2031
2032    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2033        if (!sUserManager.exists(userId)) return null;
2034        final PackageSetting ps = (PackageSetting) p.mExtras;
2035        if (ps == null) {
2036            return null;
2037        }
2038        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2039        final PackageUserState state = ps.readUserState(userId);
2040        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2041                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2042                state, userId);
2043    }
2044
2045    @Override
2046    public boolean isPackageAvailable(String packageName, int userId) {
2047        if (!sUserManager.exists(userId)) return false;
2048        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2049        synchronized (mPackages) {
2050            PackageParser.Package p = mPackages.get(packageName);
2051            if (p != null) {
2052                final PackageSetting ps = (PackageSetting) p.mExtras;
2053                if (ps != null) {
2054                    final PackageUserState state = ps.readUserState(userId);
2055                    if (state != null) {
2056                        return PackageParser.isAvailable(state);
2057                    }
2058                }
2059            }
2060        }
2061        return false;
2062    }
2063
2064    @Override
2065    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2066        if (!sUserManager.exists(userId)) return null;
2067        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2068        // reader
2069        synchronized (mPackages) {
2070            PackageParser.Package p = mPackages.get(packageName);
2071            if (DEBUG_PACKAGE_INFO)
2072                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2073            if (p != null) {
2074                return generatePackageInfo(p, flags, userId);
2075            }
2076            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2077                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2078            }
2079        }
2080        return null;
2081    }
2082
2083    @Override
2084    public String[] currentToCanonicalPackageNames(String[] names) {
2085        String[] out = new String[names.length];
2086        // reader
2087        synchronized (mPackages) {
2088            for (int i=names.length-1; i>=0; i--) {
2089                PackageSetting ps = mSettings.mPackages.get(names[i]);
2090                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2091            }
2092        }
2093        return out;
2094    }
2095
2096    @Override
2097    public String[] canonicalToCurrentPackageNames(String[] names) {
2098        String[] out = new String[names.length];
2099        // reader
2100        synchronized (mPackages) {
2101            for (int i=names.length-1; i>=0; i--) {
2102                String cur = mSettings.mRenamedPackages.get(names[i]);
2103                out[i] = cur != null ? cur : names[i];
2104            }
2105        }
2106        return out;
2107    }
2108
2109    @Override
2110    public int getPackageUid(String packageName, int userId) {
2111        if (!sUserManager.exists(userId)) return -1;
2112        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2113        // reader
2114        synchronized (mPackages) {
2115            PackageParser.Package p = mPackages.get(packageName);
2116            if(p != null) {
2117                return UserHandle.getUid(userId, p.applicationInfo.uid);
2118            }
2119            PackageSetting ps = mSettings.mPackages.get(packageName);
2120            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2121                return -1;
2122            }
2123            p = ps.pkg;
2124            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2125        }
2126    }
2127
2128    @Override
2129    public int[] getPackageGids(String packageName) {
2130        // reader
2131        synchronized (mPackages) {
2132            PackageParser.Package p = mPackages.get(packageName);
2133            if (DEBUG_PACKAGE_INFO)
2134                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2135            if (p != null) {
2136                final PackageSetting ps = (PackageSetting)p.mExtras;
2137                return ps.getGids();
2138            }
2139        }
2140        // stupid thing to indicate an error.
2141        return new int[0];
2142    }
2143
2144    static final PermissionInfo generatePermissionInfo(
2145            BasePermission bp, int flags) {
2146        if (bp.perm != null) {
2147            return PackageParser.generatePermissionInfo(bp.perm, flags);
2148        }
2149        PermissionInfo pi = new PermissionInfo();
2150        pi.name = bp.name;
2151        pi.packageName = bp.sourcePackage;
2152        pi.nonLocalizedLabel = bp.name;
2153        pi.protectionLevel = bp.protectionLevel;
2154        return pi;
2155    }
2156
2157    @Override
2158    public PermissionInfo getPermissionInfo(String name, int flags) {
2159        // reader
2160        synchronized (mPackages) {
2161            final BasePermission p = mSettings.mPermissions.get(name);
2162            if (p != null) {
2163                return generatePermissionInfo(p, flags);
2164            }
2165            return null;
2166        }
2167    }
2168
2169    @Override
2170    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2171        // reader
2172        synchronized (mPackages) {
2173            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2174            for (BasePermission p : mSettings.mPermissions.values()) {
2175                if (group == null) {
2176                    if (p.perm == null || p.perm.info.group == null) {
2177                        out.add(generatePermissionInfo(p, flags));
2178                    }
2179                } else {
2180                    if (p.perm != null && group.equals(p.perm.info.group)) {
2181                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2182                    }
2183                }
2184            }
2185
2186            if (out.size() > 0) {
2187                return out;
2188            }
2189            return mPermissionGroups.containsKey(group) ? out : null;
2190        }
2191    }
2192
2193    @Override
2194    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2195        // reader
2196        synchronized (mPackages) {
2197            return PackageParser.generatePermissionGroupInfo(
2198                    mPermissionGroups.get(name), flags);
2199        }
2200    }
2201
2202    @Override
2203    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2204        // reader
2205        synchronized (mPackages) {
2206            final int N = mPermissionGroups.size();
2207            ArrayList<PermissionGroupInfo> out
2208                    = new ArrayList<PermissionGroupInfo>(N);
2209            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2210                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2211            }
2212            return out;
2213        }
2214    }
2215
2216    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2217            int userId) {
2218        if (!sUserManager.exists(userId)) return null;
2219        PackageSetting ps = mSettings.mPackages.get(packageName);
2220        if (ps != null) {
2221            if (ps.pkg == null) {
2222                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2223                        flags, userId);
2224                if (pInfo != null) {
2225                    return pInfo.applicationInfo;
2226                }
2227                return null;
2228            }
2229            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2230                    ps.readUserState(userId), userId);
2231        }
2232        return null;
2233    }
2234
2235    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2236            int userId) {
2237        if (!sUserManager.exists(userId)) return null;
2238        PackageSetting ps = mSettings.mPackages.get(packageName);
2239        if (ps != null) {
2240            PackageParser.Package pkg = ps.pkg;
2241            if (pkg == null) {
2242                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2243                    return null;
2244                }
2245                pkg = new PackageParser.Package(packageName);
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.codePath + " and " +
4074                    opkg.codePath + ": 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.codePath + " and " +
4080                    opkg.codePath + " 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.codePath, opkg.codePath, sharedGid) != 0) {
4085            Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath);
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        try {
4181            pp.collectCertificates(pkg, parseFlags);
4182        } catch (PackageParserException e) {
4183            mLastScanError = e.error;
4184            return false;
4185        }
4186        return true;
4187    }
4188
4189    /*
4190     *  Scan a package and return the newly parsed package.
4191     *  Returns null in case of errors and the error code is stored in mLastScanError
4192     */
4193    private PackageParser.Package scanPackageLI(File scanFile,
4194            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4195        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4196        String scanPath = scanFile.getPath();
4197        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4198        parseFlags |= mDefParseFlags;
4199        PackageParser pp = new PackageParser(scanPath);
4200        pp.setSeparateProcesses(mSeparateProcesses);
4201        pp.setOnlyCoreApps(mOnlyCore);
4202
4203        final PackageParser.Package pkg;
4204        try {
4205            pkg = pp.parseMonolithicPackage(scanFile, mMetrics, parseFlags,
4206                (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4207        } catch (PackageParserException e) {
4208            mLastScanError = e.error;
4209            return null;
4210        }
4211
4212        PackageSetting ps = null;
4213        PackageSetting updatedPkg;
4214        // reader
4215        synchronized (mPackages) {
4216            // Look to see if we already know about this package.
4217            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4218            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4219                // This package has been renamed to its original name.  Let's
4220                // use that.
4221                ps = mSettings.peekPackageLPr(oldName);
4222            }
4223            // If there was no original package, see one for the real package name.
4224            if (ps == null) {
4225                ps = mSettings.peekPackageLPr(pkg.packageName);
4226            }
4227            // Check to see if this package could be hiding/updating a system
4228            // package.  Must look for it either under the original or real
4229            // package name depending on our state.
4230            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4231            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4232        }
4233        boolean updatedPkgBetter = false;
4234        // First check if this is a system package that may involve an update
4235        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4236            if (ps != null && !ps.codePath.equals(scanFile)) {
4237                // The path has changed from what was last scanned...  check the
4238                // version of the new path against what we have stored to determine
4239                // what to do.
4240                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4241                if (pkg.mVersionCode < ps.versionCode) {
4242                    // The system package has been updated and the code path does not match
4243                    // Ignore entry. Skip it.
4244                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4245                            + " ignored: updated version " + ps.versionCode
4246                            + " better than this " + pkg.mVersionCode);
4247                    if (!updatedPkg.codePath.equals(scanFile)) {
4248                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4249                                + ps.name + " changing from " + updatedPkg.codePathString
4250                                + " to " + scanFile);
4251                        updatedPkg.codePath = scanFile;
4252                        updatedPkg.codePathString = scanFile.toString();
4253                        // This is the point at which we know that the system-disk APK
4254                        // for this package has moved during a reboot (e.g. due to an OTA),
4255                        // so we need to reevaluate it for privilege policy.
4256                        if (locationIsPrivileged(scanFile)) {
4257                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4258                        }
4259                    }
4260                    updatedPkg.pkg = pkg;
4261                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4262                    return null;
4263                } else {
4264                    // The current app on the system partition is better than
4265                    // what we have updated to on the data partition; switch
4266                    // back to the system partition version.
4267                    // At this point, its safely assumed that package installation for
4268                    // apps in system partition will go through. If not there won't be a working
4269                    // version of the app
4270                    // writer
4271                    synchronized (mPackages) {
4272                        // Just remove the loaded entries from package lists.
4273                        mPackages.remove(ps.name);
4274                    }
4275                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4276                            + "reverting from " + ps.codePathString
4277                            + ": new version " + pkg.mVersionCode
4278                            + " better than installed " + ps.versionCode);
4279
4280                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4281                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4282                            getAppInstructionSetFromSettings(ps));
4283                    synchronized (mInstallLock) {
4284                        args.cleanUpResourcesLI();
4285                    }
4286                    synchronized (mPackages) {
4287                        mSettings.enableSystemPackageLPw(ps.name);
4288                    }
4289                    updatedPkgBetter = true;
4290                }
4291            }
4292        }
4293
4294        if (updatedPkg != null) {
4295            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4296            // initially
4297            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4298
4299            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4300            // flag set initially
4301            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4302                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4303            }
4304        }
4305        // Verify certificates against what was last scanned
4306        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4307            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4308            return null;
4309        }
4310
4311        /*
4312         * A new system app appeared, but we already had a non-system one of the
4313         * same name installed earlier.
4314         */
4315        boolean shouldHideSystemApp = false;
4316        if (updatedPkg == null && ps != null
4317                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4318            /*
4319             * Check to make sure the signatures match first. If they don't,
4320             * wipe the installed application and its data.
4321             */
4322            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4323                    != PackageManager.SIGNATURE_MATCH) {
4324                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4325                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4326                ps = null;
4327            } else {
4328                /*
4329                 * If the newly-added system app is an older version than the
4330                 * already installed version, hide it. It will be scanned later
4331                 * and re-added like an update.
4332                 */
4333                if (pkg.mVersionCode < ps.versionCode) {
4334                    shouldHideSystemApp = true;
4335                } else {
4336                    /*
4337                     * The newly found system app is a newer version that the
4338                     * one previously installed. Simply remove the
4339                     * already-installed application and replace it with our own
4340                     * while keeping the application data.
4341                     */
4342                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4343                            + ps.codePathString + ": new version " + pkg.mVersionCode
4344                            + " better than installed " + ps.versionCode);
4345                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4346                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4347                            getAppInstructionSetFromSettings(ps));
4348                    synchronized (mInstallLock) {
4349                        args.cleanUpResourcesLI();
4350                    }
4351                }
4352            }
4353        }
4354
4355        // The apk is forward locked (not public) if its code and resources
4356        // are kept in different files. (except for app in either system or
4357        // vendor path).
4358        // TODO grab this value from PackageSettings
4359        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4360            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4361                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4362            }
4363        }
4364
4365        String codePath = null;
4366        String resPath = null;
4367        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4368            if (ps != null && ps.resourcePathString != null) {
4369                resPath = ps.resourcePathString;
4370            } else {
4371                // Should not happen at all. Just log an error.
4372                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4373            }
4374        } else {
4375            resPath = pkg.codePath;
4376        }
4377
4378        codePath = pkg.codePath;
4379        // Set application objects path explicitly.
4380        pkg.applicationInfo.sourceDir = codePath;
4381        pkg.applicationInfo.publicSourceDir = resPath;
4382        // Note that we invoke the following method only if we are about to unpack an application
4383        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4384                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4385
4386        /*
4387         * If the system app should be overridden by a previously installed
4388         * data, hide the system app now and let the /data/app scan pick it up
4389         * again.
4390         */
4391        if (shouldHideSystemApp) {
4392            synchronized (mPackages) {
4393                /*
4394                 * We have to grant systems permissions before we hide, because
4395                 * grantPermissions will assume the package update is trying to
4396                 * expand its permissions.
4397                 */
4398                grantPermissionsLPw(pkg, true);
4399                mSettings.disableSystemPackageLPw(pkg.packageName);
4400            }
4401        }
4402
4403        return scannedPkg;
4404    }
4405
4406    private static String fixProcessName(String defProcessName,
4407            String processName, int uid) {
4408        if (processName == null) {
4409            return defProcessName;
4410        }
4411        return processName;
4412    }
4413
4414    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4415        if (pkgSetting.signatures.mSignatures != null) {
4416            // Already existing package. Make sure signatures match
4417            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4418                    == PackageManager.SIGNATURE_MATCH;
4419            if (!match) {
4420                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4421                        == PackageManager.SIGNATURE_MATCH;
4422            }
4423            if (!match) {
4424                Slog.e(TAG, "Package " + pkg.packageName
4425                        + " signatures do not match the previously installed version; ignoring!");
4426                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4427                return false;
4428            }
4429        }
4430        // Check for shared user signatures
4431        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4432            // Already existing package. Make sure signatures match
4433            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4434                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4435            if (!match) {
4436                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4437                        == PackageManager.SIGNATURE_MATCH;
4438            }
4439            if (!match) {
4440                Slog.e(TAG, "Package " + pkg.packageName
4441                        + " has no signatures that match those in shared user "
4442                        + pkgSetting.sharedUser.name + "; ignoring!");
4443                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4444                return false;
4445            }
4446        }
4447        return true;
4448    }
4449
4450    /**
4451     * Enforces that only the system UID or root's UID can call a method exposed
4452     * via Binder.
4453     *
4454     * @param message used as message if SecurityException is thrown
4455     * @throws SecurityException if the caller is not system or root
4456     */
4457    private static final void enforceSystemOrRoot(String message) {
4458        final int uid = Binder.getCallingUid();
4459        if (uid != Process.SYSTEM_UID && uid != 0) {
4460            throw new SecurityException(message);
4461        }
4462    }
4463
4464    @Override
4465    public void performBootDexOpt() {
4466        enforceSystemOrRoot("Only the system can request dexopt be performed");
4467
4468        final HashSet<PackageParser.Package> pkgs;
4469        synchronized (mPackages) {
4470            pkgs = mDeferredDexOpt;
4471            mDeferredDexOpt = null;
4472        }
4473
4474        if (pkgs != null) {
4475            // Filter out packages that aren't recently used.
4476            //
4477            // The exception is first boot of a non-eng device, which
4478            // should do a full dexopt.
4479            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4480            if (eng || !isFirstBoot()) {
4481                // TODO: add a property to control this?
4482                long dexOptLRUThresholdInMinutes;
4483                if (eng) {
4484                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4485                } else {
4486                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4487                }
4488                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4489
4490                int total = pkgs.size();
4491                int skipped = 0;
4492                long now = System.currentTimeMillis();
4493                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4494                    PackageParser.Package pkg = i.next();
4495                    long then = pkg.mLastPackageUsageTimeInMills;
4496                    if (then + dexOptLRUThresholdInMills < now) {
4497                        if (DEBUG_DEXOPT) {
4498                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4499                                  ((then == 0) ? "never" : new Date(then)));
4500                        }
4501                        i.remove();
4502                        skipped++;
4503                    }
4504                }
4505                if (DEBUG_DEXOPT) {
4506                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4507                }
4508            }
4509
4510            int i = 0;
4511            for (PackageParser.Package pkg : pkgs) {
4512                i++;
4513                if (DEBUG_DEXOPT) {
4514                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4515                          + ": " + pkg.packageName);
4516                }
4517                if (!isFirstBoot()) {
4518                    try {
4519                        ActivityManagerNative.getDefault().showBootMessage(
4520                                mContext.getResources().getString(
4521                                        R.string.android_upgrading_apk,
4522                                        i, pkgs.size()), true);
4523                    } catch (RemoteException e) {
4524                    }
4525                }
4526                PackageParser.Package p = pkg;
4527                synchronized (mInstallLock) {
4528                    if (p.mDexOptNeeded) {
4529                        performDexOptLI(p, false /* force dex */, false /* defer */,
4530                                true /* include dependencies */);
4531                    }
4532                }
4533            }
4534        }
4535    }
4536
4537    @Override
4538    public boolean performDexOpt(String packageName) {
4539        enforceSystemOrRoot("Only the system can request dexopt be performed");
4540        return performDexOpt(packageName, true);
4541    }
4542
4543    public boolean performDexOpt(String packageName, boolean updateUsage) {
4544
4545        PackageParser.Package p;
4546        synchronized (mPackages) {
4547            p = mPackages.get(packageName);
4548            if (p == null) {
4549                return false;
4550            }
4551            if (updateUsage) {
4552                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4553            }
4554            mPackageUsage.write(false);
4555            if (!p.mDexOptNeeded) {
4556                return false;
4557            }
4558        }
4559
4560        synchronized (mInstallLock) {
4561            return performDexOptLI(p, false /* force dex */, false /* defer */,
4562                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4563        }
4564    }
4565
4566    public HashSet<String> getPackagesThatNeedDexOpt() {
4567        HashSet<String> pkgs = null;
4568        synchronized (mPackages) {
4569            for (PackageParser.Package p : mPackages.values()) {
4570                if (DEBUG_DEXOPT) {
4571                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4572                }
4573                if (!p.mDexOptNeeded) {
4574                    continue;
4575                }
4576                if (pkgs == null) {
4577                    pkgs = new HashSet<String>();
4578                }
4579                pkgs.add(p.packageName);
4580            }
4581        }
4582        return pkgs;
4583    }
4584
4585    public void shutdown() {
4586        mPackageUsage.write(true);
4587    }
4588
4589    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4590             boolean forceDex, boolean defer, HashSet<String> done) {
4591        for (int i=0; i<libs.size(); i++) {
4592            PackageParser.Package libPkg;
4593            String libName;
4594            synchronized (mPackages) {
4595                libName = libs.get(i);
4596                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4597                if (lib != null && lib.apk != null) {
4598                    libPkg = mPackages.get(lib.apk);
4599                } else {
4600                    libPkg = null;
4601                }
4602            }
4603            if (libPkg != null && !done.contains(libName)) {
4604                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4605            }
4606        }
4607    }
4608
4609    static final int DEX_OPT_SKIPPED = 0;
4610    static final int DEX_OPT_PERFORMED = 1;
4611    static final int DEX_OPT_DEFERRED = 2;
4612    static final int DEX_OPT_FAILED = -1;
4613
4614    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4615            boolean forceDex, boolean defer, HashSet<String> done) {
4616        final String instructionSet = instructionSetOverride != null ?
4617                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4618
4619        if (done != null) {
4620            done.add(pkg.packageName);
4621            if (pkg.usesLibraries != null) {
4622                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4623            }
4624            if (pkg.usesOptionalLibraries != null) {
4625                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4626            }
4627        }
4628
4629        boolean performed = false;
4630        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4631            String path = pkg.codePath;
4632            try {
4633                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4634                                                                                pkg.packageName,
4635                                                                                instructionSet,
4636                                                                                defer);
4637                // There are three basic cases here:
4638                // 1.) we need to dexopt, either because we are forced or it is needed
4639                // 2.) we are defering a needed dexopt
4640                // 3.) we are skipping an unneeded dexopt
4641                if (forceDex || (!defer && isDexOptNeededInternal)) {
4642                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4643                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4644                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4645                                                pkg.packageName, instructionSet);
4646                    // Note that we ran dexopt, since rerunning will
4647                    // probably just result in an error again.
4648                    pkg.mDexOptNeeded = false;
4649                    if (ret < 0) {
4650                        return DEX_OPT_FAILED;
4651                    }
4652                    return DEX_OPT_PERFORMED;
4653                }
4654                if (defer && isDexOptNeededInternal) {
4655                    if (mDeferredDexOpt == null) {
4656                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4657                    }
4658                    mDeferredDexOpt.add(pkg);
4659                    return DEX_OPT_DEFERRED;
4660                }
4661                pkg.mDexOptNeeded = false;
4662                return DEX_OPT_SKIPPED;
4663            } catch (FileNotFoundException e) {
4664                Slog.w(TAG, "Apk not found for dexopt: " + path);
4665                return DEX_OPT_FAILED;
4666            } catch (IOException e) {
4667                Slog.w(TAG, "IOException reading apk: " + path, e);
4668                return DEX_OPT_FAILED;
4669            } catch (StaleDexCacheError e) {
4670                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4671                return DEX_OPT_FAILED;
4672            } catch (Exception e) {
4673                Slog.w(TAG, "Exception when doing dexopt : ", e);
4674                return DEX_OPT_FAILED;
4675            }
4676        }
4677        return DEX_OPT_SKIPPED;
4678    }
4679
4680    private String getAppInstructionSet(ApplicationInfo info) {
4681        String instructionSet = getPreferredInstructionSet();
4682
4683        if (info.cpuAbi != null) {
4684            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4685        }
4686
4687        return instructionSet;
4688    }
4689
4690    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4691        String instructionSet = getPreferredInstructionSet();
4692
4693        if (ps.cpuAbiString != null) {
4694            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4695        }
4696
4697        return instructionSet;
4698    }
4699
4700    private static String getPreferredInstructionSet() {
4701        if (sPreferredInstructionSet == null) {
4702            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4703        }
4704
4705        return sPreferredInstructionSet;
4706    }
4707
4708    private static List<String> getAllInstructionSets() {
4709        final String[] allAbis = Build.SUPPORTED_ABIS;
4710        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4711
4712        for (String abi : allAbis) {
4713            final String instructionSet = VMRuntime.getInstructionSet(abi);
4714            if (!allInstructionSets.contains(instructionSet)) {
4715                allInstructionSets.add(instructionSet);
4716            }
4717        }
4718
4719        return allInstructionSets;
4720    }
4721
4722    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4723            boolean inclDependencies) {
4724        HashSet<String> done;
4725        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4726            done = new HashSet<String>();
4727            done.add(pkg.packageName);
4728        } else {
4729            done = null;
4730        }
4731        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4732    }
4733
4734    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4735        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4736            Slog.w(TAG, "Unable to update from " + oldPkg.name
4737                    + " to " + newPkg.packageName
4738                    + ": old package not in system partition");
4739            return false;
4740        } else if (mPackages.get(oldPkg.name) != null) {
4741            Slog.w(TAG, "Unable to update from " + oldPkg.name
4742                    + " to " + newPkg.packageName
4743                    + ": old package still exists");
4744            return false;
4745        }
4746        return true;
4747    }
4748
4749    File getDataPathForUser(int userId) {
4750        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4751    }
4752
4753    private File getDataPathForPackage(String packageName, int userId) {
4754        /*
4755         * Until we fully support multiple users, return the directory we
4756         * previously would have. The PackageManagerTests will need to be
4757         * revised when this is changed back..
4758         */
4759        if (userId == 0) {
4760            return new File(mAppDataDir, packageName);
4761        } else {
4762            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4763                + File.separator + packageName);
4764        }
4765    }
4766
4767    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4768        int[] users = sUserManager.getUserIds();
4769        int res = mInstaller.install(packageName, uid, uid, seinfo);
4770        if (res < 0) {
4771            return res;
4772        }
4773        for (int user : users) {
4774            if (user != 0) {
4775                res = mInstaller.createUserData(packageName,
4776                        UserHandle.getUid(user, uid), user, seinfo);
4777                if (res < 0) {
4778                    return res;
4779                }
4780            }
4781        }
4782        return res;
4783    }
4784
4785    private int removeDataDirsLI(String packageName) {
4786        int[] users = sUserManager.getUserIds();
4787        int res = 0;
4788        for (int user : users) {
4789            int resInner = mInstaller.remove(packageName, user);
4790            if (resInner < 0) {
4791                res = resInner;
4792            }
4793        }
4794
4795        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4796        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4797        if (!nativeLibraryFile.delete()) {
4798            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4799        }
4800
4801        return res;
4802    }
4803
4804    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4805            PackageParser.Package changingLib) {
4806        if (file.path != null) {
4807            usesLibraryFiles.add(file.path);
4808            return;
4809        }
4810        PackageParser.Package p = mPackages.get(file.apk);
4811        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4812            // If we are doing this while in the middle of updating a library apk,
4813            // then we need to make sure to use that new apk for determining the
4814            // dependencies here.  (We haven't yet finished committing the new apk
4815            // to the package manager state.)
4816            if (p == null || p.packageName.equals(changingLib.packageName)) {
4817                p = changingLib;
4818            }
4819        }
4820        if (p != null) {
4821            usesLibraryFiles.add(p.codePath);
4822        }
4823    }
4824
4825    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4826            PackageParser.Package changingLib) {
4827        // We might be upgrading from a version of the platform that did not
4828        // provide per-package native library directories for system apps.
4829        // Fix that up here.
4830        if (isSystemApp(pkg)) {
4831            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4832            setInternalAppNativeLibraryPath(pkg, ps);
4833        }
4834
4835        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4836            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4837            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4838            for (int i=0; i<N; i++) {
4839                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4840                if (file == null) {
4841                    Slog.e(TAG, "Package " + pkg.packageName
4842                            + " requires unavailable shared library "
4843                            + pkg.usesLibraries.get(i) + "; failing!");
4844                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4845                    return false;
4846                }
4847                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4848            }
4849            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4850            for (int i=0; i<N; i++) {
4851                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4852                if (file == null) {
4853                    Slog.w(TAG, "Package " + pkg.packageName
4854                            + " desires unavailable shared library "
4855                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4856                } else {
4857                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4858                }
4859            }
4860            N = usesLibraryFiles.size();
4861            if (N > 0) {
4862                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4863            } else {
4864                pkg.usesLibraryFiles = null;
4865            }
4866        }
4867        return true;
4868    }
4869
4870    private static boolean hasString(List<String> list, List<String> which) {
4871        if (list == null) {
4872            return false;
4873        }
4874        for (int i=list.size()-1; i>=0; i--) {
4875            for (int j=which.size()-1; j>=0; j--) {
4876                if (which.get(j).equals(list.get(i))) {
4877                    return true;
4878                }
4879            }
4880        }
4881        return false;
4882    }
4883
4884    private void updateAllSharedLibrariesLPw() {
4885        for (PackageParser.Package pkg : mPackages.values()) {
4886            updateSharedLibrariesLPw(pkg, null);
4887        }
4888    }
4889
4890    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4891            PackageParser.Package changingPkg) {
4892        ArrayList<PackageParser.Package> res = null;
4893        for (PackageParser.Package pkg : mPackages.values()) {
4894            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4895                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4896                if (res == null) {
4897                    res = new ArrayList<PackageParser.Package>();
4898                }
4899                res.add(pkg);
4900                updateSharedLibrariesLPw(pkg, changingPkg);
4901            }
4902        }
4903        return res;
4904    }
4905
4906    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4907            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4908        final File scanFile = new File(pkg.codePath);
4909        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4910                pkg.applicationInfo.publicSourceDir == null) {
4911            // Bail out. The resource and code paths haven't been set.
4912            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4913            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4914            return null;
4915        }
4916
4917        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4918            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4919        }
4920
4921        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4922            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4923        }
4924
4925        if (mCustomResolverComponentName != null &&
4926                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4927            setUpCustomResolverActivity(pkg);
4928        }
4929
4930        if (pkg.packageName.equals("android")) {
4931            synchronized (mPackages) {
4932                if (mAndroidApplication != null) {
4933                    Slog.w(TAG, "*************************************************");
4934                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4935                    Slog.w(TAG, " file=" + scanFile);
4936                    Slog.w(TAG, "*************************************************");
4937                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4938                    return null;
4939                }
4940
4941                // Set up information for our fall-back user intent resolution activity.
4942                mPlatformPackage = pkg;
4943                pkg.mVersionCode = mSdkVersion;
4944                mAndroidApplication = pkg.applicationInfo;
4945
4946                if (!mResolverReplaced) {
4947                    mResolveActivity.applicationInfo = mAndroidApplication;
4948                    mResolveActivity.name = ResolverActivity.class.getName();
4949                    mResolveActivity.packageName = mAndroidApplication.packageName;
4950                    mResolveActivity.processName = "system:ui";
4951                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4952                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4953                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4954                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4955                    mResolveActivity.exported = true;
4956                    mResolveActivity.enabled = true;
4957                    mResolveInfo.activityInfo = mResolveActivity;
4958                    mResolveInfo.priority = 0;
4959                    mResolveInfo.preferredOrder = 0;
4960                    mResolveInfo.match = 0;
4961                    mResolveComponentName = new ComponentName(
4962                            mAndroidApplication.packageName, mResolveActivity.name);
4963                }
4964            }
4965        }
4966
4967        if (DEBUG_PACKAGE_SCANNING) {
4968            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4969                Log.d(TAG, "Scanning package " + pkg.packageName);
4970        }
4971
4972        if (mPackages.containsKey(pkg.packageName)
4973                || mSharedLibraries.containsKey(pkg.packageName)) {
4974            Slog.w(TAG, "Application package " + pkg.packageName
4975                    + " already installed.  Skipping duplicate.");
4976            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4977            return null;
4978        }
4979
4980        // Initialize package source and resource directories
4981        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4982        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4983
4984        SharedUserSetting suid = null;
4985        PackageSetting pkgSetting = null;
4986
4987        if (!isSystemApp(pkg)) {
4988            // Only system apps can use these features.
4989            pkg.mOriginalPackages = null;
4990            pkg.mRealPackage = null;
4991            pkg.mAdoptPermissions = null;
4992        }
4993
4994        // writer
4995        synchronized (mPackages) {
4996            if (pkg.mSharedUserId != null) {
4997                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4998                if (suid == null) {
4999                    Slog.w(TAG, "Creating application package " + pkg.packageName
5000                            + " for shared user failed");
5001                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5002                    return null;
5003                }
5004                if (DEBUG_PACKAGE_SCANNING) {
5005                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5006                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5007                                + "): packages=" + suid.packages);
5008                }
5009            }
5010
5011            // Check if we are renaming from an original package name.
5012            PackageSetting origPackage = null;
5013            String realName = null;
5014            if (pkg.mOriginalPackages != null) {
5015                // This package may need to be renamed to a previously
5016                // installed name.  Let's check on that...
5017                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5018                if (pkg.mOriginalPackages.contains(renamed)) {
5019                    // This package had originally been installed as the
5020                    // original name, and we have already taken care of
5021                    // transitioning to the new one.  Just update the new
5022                    // one to continue using the old name.
5023                    realName = pkg.mRealPackage;
5024                    if (!pkg.packageName.equals(renamed)) {
5025                        // Callers into this function may have already taken
5026                        // care of renaming the package; only do it here if
5027                        // it is not already done.
5028                        pkg.setPackageName(renamed);
5029                    }
5030
5031                } else {
5032                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5033                        if ((origPackage = mSettings.peekPackageLPr(
5034                                pkg.mOriginalPackages.get(i))) != null) {
5035                            // We do have the package already installed under its
5036                            // original name...  should we use it?
5037                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5038                                // New package is not compatible with original.
5039                                origPackage = null;
5040                                continue;
5041                            } else if (origPackage.sharedUser != null) {
5042                                // Make sure uid is compatible between packages.
5043                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5044                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5045                                            + " to " + pkg.packageName + ": old uid "
5046                                            + origPackage.sharedUser.name
5047                                            + " differs from " + pkg.mSharedUserId);
5048                                    origPackage = null;
5049                                    continue;
5050                                }
5051                            } else {
5052                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5053                                        + pkg.packageName + " to old name " + origPackage.name);
5054                            }
5055                            break;
5056                        }
5057                    }
5058                }
5059            }
5060
5061            if (mTransferedPackages.contains(pkg.packageName)) {
5062                Slog.w(TAG, "Package " + pkg.packageName
5063                        + " was transferred to another, but its .apk remains");
5064            }
5065
5066            // Just create the setting, don't add it yet. For already existing packages
5067            // the PkgSetting exists already and doesn't have to be created.
5068            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5069                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5070                    pkg.applicationInfo.cpuAbi,
5071                    pkg.applicationInfo.flags, user, false);
5072            if (pkgSetting == null) {
5073                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5074                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5075                return null;
5076            }
5077
5078            if (pkgSetting.origPackage != null) {
5079                // If we are first transitioning from an original package,
5080                // fix up the new package's name now.  We need to do this after
5081                // looking up the package under its new name, so getPackageLP
5082                // can take care of fiddling things correctly.
5083                pkg.setPackageName(origPackage.name);
5084
5085                // File a report about this.
5086                String msg = "New package " + pkgSetting.realName
5087                        + " renamed to replace old package " + pkgSetting.name;
5088                reportSettingsProblem(Log.WARN, msg);
5089
5090                // Make a note of it.
5091                mTransferedPackages.add(origPackage.name);
5092
5093                // No longer need to retain this.
5094                pkgSetting.origPackage = null;
5095            }
5096
5097            if (realName != null) {
5098                // Make a note of it.
5099                mTransferedPackages.add(pkg.packageName);
5100            }
5101
5102            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5103                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5104            }
5105
5106            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5107                // Check all shared libraries and map to their actual file path.
5108                // We only do this here for apps not on a system dir, because those
5109                // are the only ones that can fail an install due to this.  We
5110                // will take care of the system apps by updating all of their
5111                // library paths after the scan is done.
5112                if (!updateSharedLibrariesLPw(pkg, null)) {
5113                    return null;
5114                }
5115            }
5116
5117            if (mFoundPolicyFile) {
5118                SELinuxMMAC.assignSeinfoValue(pkg);
5119            }
5120
5121            pkg.applicationInfo.uid = pkgSetting.appId;
5122            pkg.mExtras = pkgSetting;
5123
5124            if (!verifySignaturesLP(pkgSetting, pkg)) {
5125                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5126                    return null;
5127                }
5128                // The signature has changed, but this package is in the system
5129                // image...  let's recover!
5130                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5131                // However...  if this package is part of a shared user, but it
5132                // doesn't match the signature of the shared user, let's fail.
5133                // What this means is that you can't change the signatures
5134                // associated with an overall shared user, which doesn't seem all
5135                // that unreasonable.
5136                if (pkgSetting.sharedUser != null) {
5137                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5138                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5139                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5140                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5141                        return null;
5142                    }
5143                }
5144                // File a report about this.
5145                String msg = "System package " + pkg.packageName
5146                        + " signature changed; retaining data.";
5147                reportSettingsProblem(Log.WARN, msg);
5148            }
5149
5150            // Verify that this new package doesn't have any content providers
5151            // that conflict with existing packages.  Only do this if the
5152            // package isn't already installed, since we don't want to break
5153            // things that are installed.
5154            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5155                final int N = pkg.providers.size();
5156                int i;
5157                for (i=0; i<N; i++) {
5158                    PackageParser.Provider p = pkg.providers.get(i);
5159                    if (p.info.authority != null) {
5160                        String names[] = p.info.authority.split(";");
5161                        for (int j = 0; j < names.length; j++) {
5162                            if (mProvidersByAuthority.containsKey(names[j])) {
5163                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5164                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5165                                        " (in package " + pkg.applicationInfo.packageName +
5166                                        ") is already used by "
5167                                        + ((other != null && other.getComponentName() != null)
5168                                                ? other.getComponentName().getPackageName() : "?"));
5169                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5170                                return null;
5171                            }
5172                        }
5173                    }
5174                }
5175            }
5176
5177            if (pkg.mAdoptPermissions != null) {
5178                // This package wants to adopt ownership of permissions from
5179                // another package.
5180                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5181                    final String origName = pkg.mAdoptPermissions.get(i);
5182                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5183                    if (orig != null) {
5184                        if (verifyPackageUpdateLPr(orig, pkg)) {
5185                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5186                                    + pkg.packageName);
5187                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5188                        }
5189                    }
5190                }
5191            }
5192        }
5193
5194        final String pkgName = pkg.packageName;
5195
5196        final long scanFileTime = scanFile.lastModified();
5197        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5198        pkg.applicationInfo.processName = fixProcessName(
5199                pkg.applicationInfo.packageName,
5200                pkg.applicationInfo.processName,
5201                pkg.applicationInfo.uid);
5202
5203        File dataPath;
5204        if (mPlatformPackage == pkg) {
5205            // The system package is special.
5206            dataPath = new File (Environment.getDataDirectory(), "system");
5207            pkg.applicationInfo.dataDir = dataPath.getPath();
5208        } else {
5209            // This is a normal package, need to make its data directory.
5210            dataPath = getDataPathForPackage(pkg.packageName, 0);
5211
5212            boolean uidError = false;
5213
5214            if (dataPath.exists()) {
5215                int currentUid = 0;
5216                try {
5217                    StructStat stat = Os.stat(dataPath.getPath());
5218                    currentUid = stat.st_uid;
5219                } catch (ErrnoException e) {
5220                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5221                }
5222
5223                // If we have mismatched owners for the data path, we have a problem.
5224                if (currentUid != pkg.applicationInfo.uid) {
5225                    boolean recovered = false;
5226                    if (currentUid == 0) {
5227                        // The directory somehow became owned by root.  Wow.
5228                        // This is probably because the system was stopped while
5229                        // installd was in the middle of messing with its libs
5230                        // directory.  Ask installd to fix that.
5231                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5232                                pkg.applicationInfo.uid);
5233                        if (ret >= 0) {
5234                            recovered = true;
5235                            String msg = "Package " + pkg.packageName
5236                                    + " unexpectedly changed to uid 0; recovered to " +
5237                                    + pkg.applicationInfo.uid;
5238                            reportSettingsProblem(Log.WARN, msg);
5239                        }
5240                    }
5241                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5242                            || (scanMode&SCAN_BOOTING) != 0)) {
5243                        // If this is a system app, we can at least delete its
5244                        // current data so the application will still work.
5245                        int ret = removeDataDirsLI(pkgName);
5246                        if (ret >= 0) {
5247                            // TODO: Kill the processes first
5248                            // Old data gone!
5249                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5250                                    ? "System package " : "Third party package ";
5251                            String msg = prefix + pkg.packageName
5252                                    + " has changed from uid: "
5253                                    + currentUid + " to "
5254                                    + pkg.applicationInfo.uid + "; old data erased";
5255                            reportSettingsProblem(Log.WARN, msg);
5256                            recovered = true;
5257
5258                            // And now re-install the app.
5259                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5260                                                   pkg.applicationInfo.seinfo);
5261                            if (ret == -1) {
5262                                // Ack should not happen!
5263                                msg = prefix + pkg.packageName
5264                                        + " could not have data directory re-created after delete.";
5265                                reportSettingsProblem(Log.WARN, msg);
5266                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5267                                return null;
5268                            }
5269                        }
5270                        if (!recovered) {
5271                            mHasSystemUidErrors = true;
5272                        }
5273                    } else if (!recovered) {
5274                        // If we allow this install to proceed, we will be broken.
5275                        // Abort, abort!
5276                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5277                        return null;
5278                    }
5279                    if (!recovered) {
5280                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5281                            + pkg.applicationInfo.uid + "/fs_"
5282                            + currentUid;
5283                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5284                        String msg = "Package " + pkg.packageName
5285                                + " has mismatched uid: "
5286                                + currentUid + " on disk, "
5287                                + pkg.applicationInfo.uid + " in settings";
5288                        // writer
5289                        synchronized (mPackages) {
5290                            mSettings.mReadMessages.append(msg);
5291                            mSettings.mReadMessages.append('\n');
5292                            uidError = true;
5293                            if (!pkgSetting.uidError) {
5294                                reportSettingsProblem(Log.ERROR, msg);
5295                            }
5296                        }
5297                    }
5298                }
5299                pkg.applicationInfo.dataDir = dataPath.getPath();
5300                if (mShouldRestoreconData) {
5301                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5302                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5303                                pkg.applicationInfo.uid);
5304                }
5305            } else {
5306                if (DEBUG_PACKAGE_SCANNING) {
5307                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5308                        Log.v(TAG, "Want this data dir: " + dataPath);
5309                }
5310                //invoke installer to do the actual installation
5311                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5312                                           pkg.applicationInfo.seinfo);
5313                if (ret < 0) {
5314                    // Error from installer
5315                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5316                    return null;
5317                }
5318
5319                if (dataPath.exists()) {
5320                    pkg.applicationInfo.dataDir = dataPath.getPath();
5321                } else {
5322                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5323                    pkg.applicationInfo.dataDir = null;
5324                }
5325            }
5326
5327            /*
5328             * Set the data dir to the default "/data/data/<package name>/lib"
5329             * if we got here without anyone telling us different (e.g., apps
5330             * stored on SD card have their native libraries stored in the ASEC
5331             * container with the APK).
5332             *
5333             * This happens during an upgrade from a package settings file that
5334             * doesn't have a native library path attribute at all.
5335             */
5336            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5337                if (pkgSetting.nativeLibraryPathString == null) {
5338                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5339                } else {
5340                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5341                }
5342            }
5343            pkgSetting.uidError = uidError;
5344        }
5345
5346        final String path = scanFile.getPath();
5347        /* Note: We don't want to unpack the native binaries for
5348         *        system applications, unless they have been updated
5349         *        (the binaries are already under /system/lib).
5350         *        Also, don't unpack libs for apps on the external card
5351         *        since they should have their libraries in the ASEC
5352         *        container already.
5353         *
5354         *        In other words, we're going to unpack the binaries
5355         *        only for non-system apps and system app upgrades.
5356         */
5357        if (pkg.applicationInfo.nativeLibraryDir != null) {
5358            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5359            try {
5360                // Enable gross and lame hacks for apps that are built with old
5361                // SDK tools. We must scan their APKs for renderscript bitcode and
5362                // not launch them if it's present. Don't bother checking on devices
5363                // that don't have 64 bit support.
5364                String[] abiList = Build.SUPPORTED_ABIS;
5365                boolean hasLegacyRenderscriptBitcode = false;
5366                if (abiOverride != null) {
5367                    abiList = new String[] { abiOverride };
5368                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5369                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5370                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5371                    hasLegacyRenderscriptBitcode = true;
5372                }
5373
5374                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5375                final String dataPathString = dataPath.getCanonicalPath();
5376
5377                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5378                    /*
5379                     * Upgrading from a previous version of the OS sometimes
5380                     * leaves native libraries in the /data/data/<app>/lib
5381                     * directory for system apps even when they shouldn't be.
5382                     * Recent changes in the JNI library search path
5383                     * necessitates we remove those to match previous behavior.
5384                     */
5385                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5386                        Log.i(TAG, "removed obsolete native libraries for system package "
5387                                + path);
5388                    }
5389                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5390                        pkg.applicationInfo.cpuAbi = abiList[0];
5391                        pkgSetting.cpuAbiString = abiList[0];
5392                    } else {
5393                        setInternalAppAbi(pkg, pkgSetting);
5394                    }
5395                } else {
5396                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5397                        /*
5398                        * Update native library dir if it starts with
5399                        * /data/data
5400                        */
5401                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5402                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5403                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5404                        }
5405
5406                        try {
5407                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5408                                    nativeLibraryDir, abiList);
5409                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5410                                Slog.e(TAG, "Unable to copy native libraries");
5411                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5412                                return null;
5413                            }
5414
5415                            // We've successfully copied native libraries across, so we make a
5416                            // note of what ABI we're using
5417                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5418                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5419                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5420                                pkg.applicationInfo.cpuAbi = abiList[0];
5421                            } else {
5422                                pkg.applicationInfo.cpuAbi = null;
5423                            }
5424                        } catch (IOException e) {
5425                            Slog.e(TAG, "Unable to copy native libraries", e);
5426                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5427                            return null;
5428                        }
5429                    } else {
5430                        // We don't have to copy the shared libraries if we're in the ASEC container
5431                        // but we still need to scan the file to figure out what ABI the app needs.
5432                        //
5433                        // TODO: This duplicates work done in the default container service. It's possible
5434                        // to clean this up but we'll need to change the interface between this service
5435                        // and IMediaContainerService (but doing so will spread this logic out, rather
5436                        // than centralizing it).
5437                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5438                        if (abi >= 0) {
5439                            pkg.applicationInfo.cpuAbi = abiList[abi];
5440                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5441                            // Note that (non upgraded) system apps will not have any native
5442                            // libraries bundled in their APK, but we're guaranteed not to be
5443                            // such an app at this point.
5444                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5445                                pkg.applicationInfo.cpuAbi = abiList[0];
5446                            } else {
5447                                pkg.applicationInfo.cpuAbi = null;
5448                            }
5449                        } else {
5450                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5451                            return null;
5452                        }
5453                    }
5454
5455                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5456                    final int[] userIds = sUserManager.getUserIds();
5457                    synchronized (mInstallLock) {
5458                        for (int userId : userIds) {
5459                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5460                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5461                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5462                                        + ")");
5463                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5464                                return null;
5465                            }
5466                        }
5467                    }
5468                }
5469
5470                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5471            } catch (IOException ioe) {
5472                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5473            } finally {
5474                handle.close();
5475            }
5476        }
5477
5478        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5479            // We don't do this here during boot because we can do it all
5480            // at once after scanning all existing packages.
5481            //
5482            // We also do this *before* we perform dexopt on this package, so that
5483            // we can avoid redundant dexopts, and also to make sure we've got the
5484            // code and package path correct.
5485            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5486                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5487                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5488                return null;
5489            }
5490        }
5491
5492        if ((scanMode&SCAN_NO_DEX) == 0) {
5493            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5494                    == DEX_OPT_FAILED) {
5495                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5496                    removeDataDirsLI(pkg.packageName);
5497                }
5498
5499                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5500                return null;
5501            }
5502        }
5503
5504        if (mFactoryTest && pkg.requestedPermissions.contains(
5505                android.Manifest.permission.FACTORY_TEST)) {
5506            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5507        }
5508
5509        ArrayList<PackageParser.Package> clientLibPkgs = null;
5510
5511        // writer
5512        synchronized (mPackages) {
5513            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5514                // Only system apps can add new shared libraries.
5515                if (pkg.libraryNames != null) {
5516                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5517                        String name = pkg.libraryNames.get(i);
5518                        boolean allowed = false;
5519                        if (isUpdatedSystemApp(pkg)) {
5520                            // New library entries can only be added through the
5521                            // system image.  This is important to get rid of a lot
5522                            // of nasty edge cases: for example if we allowed a non-
5523                            // system update of the app to add a library, then uninstalling
5524                            // the update would make the library go away, and assumptions
5525                            // we made such as through app install filtering would now
5526                            // have allowed apps on the device which aren't compatible
5527                            // with it.  Better to just have the restriction here, be
5528                            // conservative, and create many fewer cases that can negatively
5529                            // impact the user experience.
5530                            final PackageSetting sysPs = mSettings
5531                                    .getDisabledSystemPkgLPr(pkg.packageName);
5532                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5533                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5534                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5535                                        allowed = true;
5536                                        allowed = true;
5537                                        break;
5538                                    }
5539                                }
5540                            }
5541                        } else {
5542                            allowed = true;
5543                        }
5544                        if (allowed) {
5545                            if (!mSharedLibraries.containsKey(name)) {
5546                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5547                            } else if (!name.equals(pkg.packageName)) {
5548                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5549                                        + name + " already exists; skipping");
5550                            }
5551                        } else {
5552                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5553                                    + name + " that is not declared on system image; skipping");
5554                        }
5555                    }
5556                    if ((scanMode&SCAN_BOOTING) == 0) {
5557                        // If we are not booting, we need to update any applications
5558                        // that are clients of our shared library.  If we are booting,
5559                        // this will all be done once the scan is complete.
5560                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5561                    }
5562                }
5563            }
5564        }
5565
5566        // We also need to dexopt any apps that are dependent on this library.  Note that
5567        // if these fail, we should abort the install since installing the library will
5568        // result in some apps being broken.
5569        if (clientLibPkgs != null) {
5570            if ((scanMode&SCAN_NO_DEX) == 0) {
5571                for (int i=0; i<clientLibPkgs.size(); i++) {
5572                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5573                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5574                            == DEX_OPT_FAILED) {
5575                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5576                            removeDataDirsLI(pkg.packageName);
5577                        }
5578
5579                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5580                        return null;
5581                    }
5582                }
5583            }
5584        }
5585
5586        // Request the ActivityManager to kill the process(only for existing packages)
5587        // so that we do not end up in a confused state while the user is still using the older
5588        // version of the application while the new one gets installed.
5589        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5590            // If the package lives in an asec, tell everyone that the container is going
5591            // away so they can clean up any references to its resources (which would prevent
5592            // vold from being able to unmount the asec)
5593            if (isForwardLocked(pkg) || isExternal(pkg)) {
5594                if (DEBUG_INSTALL) {
5595                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5596                }
5597                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5598                final ArrayList<String> pkgList = new ArrayList<String>(1);
5599                pkgList.add(pkg.applicationInfo.packageName);
5600                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5601            }
5602
5603            // Post the request that it be killed now that the going-away broadcast is en route
5604            killApplication(pkg.applicationInfo.packageName,
5605                        pkg.applicationInfo.uid, "update pkg");
5606        }
5607
5608        // Also need to kill any apps that are dependent on the library.
5609        if (clientLibPkgs != null) {
5610            for (int i=0; i<clientLibPkgs.size(); i++) {
5611                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5612                killApplication(clientPkg.applicationInfo.packageName,
5613                        clientPkg.applicationInfo.uid, "update lib");
5614            }
5615        }
5616
5617        // writer
5618        synchronized (mPackages) {
5619            // We don't expect installation to fail beyond this point,
5620            if ((scanMode&SCAN_MONITOR) != 0) {
5621                mAppDirs.put(pkg.codePath, pkg);
5622            }
5623            // Add the new setting to mSettings
5624            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5625            // Add the new setting to mPackages
5626            mPackages.put(pkg.applicationInfo.packageName, pkg);
5627            // Make sure we don't accidentally delete its data.
5628            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5629            while (iter.hasNext()) {
5630                PackageCleanItem item = iter.next();
5631                if (pkgName.equals(item.packageName)) {
5632                    iter.remove();
5633                }
5634            }
5635
5636            // Take care of first install / last update times.
5637            if (currentTime != 0) {
5638                if (pkgSetting.firstInstallTime == 0) {
5639                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5640                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5641                    pkgSetting.lastUpdateTime = currentTime;
5642                }
5643            } else if (pkgSetting.firstInstallTime == 0) {
5644                // We need *something*.  Take time time stamp of the file.
5645                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5646            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5647                if (scanFileTime != pkgSetting.timeStamp) {
5648                    // A package on the system image has changed; consider this
5649                    // to be an update.
5650                    pkgSetting.lastUpdateTime = scanFileTime;
5651                }
5652            }
5653
5654            // Add the package's KeySets to the global KeySetManager
5655            KeySetManager ksm = mSettings.mKeySetManager;
5656            try {
5657                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5658                if (pkg.mKeySetMapping != null) {
5659                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5660                        if (entry.getValue() != null) {
5661                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5662                                entry.getValue(), entry.getKey());
5663                        }
5664                    }
5665                }
5666            } catch (NullPointerException e) {
5667                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5668            } catch (IllegalArgumentException e) {
5669                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5670            }
5671
5672            int N = pkg.providers.size();
5673            StringBuilder r = null;
5674            int i;
5675            for (i=0; i<N; i++) {
5676                PackageParser.Provider p = pkg.providers.get(i);
5677                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5678                        p.info.processName, pkg.applicationInfo.uid);
5679                mProviders.addProvider(p);
5680                p.syncable = p.info.isSyncable;
5681                if (p.info.authority != null) {
5682                    String names[] = p.info.authority.split(";");
5683                    p.info.authority = null;
5684                    for (int j = 0; j < names.length; j++) {
5685                        if (j == 1 && p.syncable) {
5686                            // We only want the first authority for a provider to possibly be
5687                            // syncable, so if we already added this provider using a different
5688                            // authority clear the syncable flag. We copy the provider before
5689                            // changing it because the mProviders object contains a reference
5690                            // to a provider that we don't want to change.
5691                            // Only do this for the second authority since the resulting provider
5692                            // object can be the same for all future authorities for this provider.
5693                            p = new PackageParser.Provider(p);
5694                            p.syncable = false;
5695                        }
5696                        if (!mProvidersByAuthority.containsKey(names[j])) {
5697                            mProvidersByAuthority.put(names[j], p);
5698                            if (p.info.authority == null) {
5699                                p.info.authority = names[j];
5700                            } else {
5701                                p.info.authority = p.info.authority + ";" + names[j];
5702                            }
5703                            if (DEBUG_PACKAGE_SCANNING) {
5704                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5705                                    Log.d(TAG, "Registered content provider: " + names[j]
5706                                            + ", className = " + p.info.name + ", isSyncable = "
5707                                            + p.info.isSyncable);
5708                            }
5709                        } else {
5710                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5711                            Slog.w(TAG, "Skipping provider name " + names[j] +
5712                                    " (in package " + pkg.applicationInfo.packageName +
5713                                    "): name already used by "
5714                                    + ((other != null && other.getComponentName() != null)
5715                                            ? other.getComponentName().getPackageName() : "?"));
5716                        }
5717                    }
5718                }
5719                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5720                    if (r == null) {
5721                        r = new StringBuilder(256);
5722                    } else {
5723                        r.append(' ');
5724                    }
5725                    r.append(p.info.name);
5726                }
5727            }
5728            if (r != null) {
5729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5730            }
5731
5732            N = pkg.services.size();
5733            r = null;
5734            for (i=0; i<N; i++) {
5735                PackageParser.Service s = pkg.services.get(i);
5736                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5737                        s.info.processName, pkg.applicationInfo.uid);
5738                mServices.addService(s);
5739                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5740                    if (r == null) {
5741                        r = new StringBuilder(256);
5742                    } else {
5743                        r.append(' ');
5744                    }
5745                    r.append(s.info.name);
5746                }
5747            }
5748            if (r != null) {
5749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5750            }
5751
5752            N = pkg.receivers.size();
5753            r = null;
5754            for (i=0; i<N; i++) {
5755                PackageParser.Activity a = pkg.receivers.get(i);
5756                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5757                        a.info.processName, pkg.applicationInfo.uid);
5758                mReceivers.addActivity(a, "receiver");
5759                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5760                    if (r == null) {
5761                        r = new StringBuilder(256);
5762                    } else {
5763                        r.append(' ');
5764                    }
5765                    r.append(a.info.name);
5766                }
5767            }
5768            if (r != null) {
5769                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5770            }
5771
5772            N = pkg.activities.size();
5773            r = null;
5774            for (i=0; i<N; i++) {
5775                PackageParser.Activity a = pkg.activities.get(i);
5776                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5777                        a.info.processName, pkg.applicationInfo.uid);
5778                mActivities.addActivity(a, "activity");
5779                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5780                    if (r == null) {
5781                        r = new StringBuilder(256);
5782                    } else {
5783                        r.append(' ');
5784                    }
5785                    r.append(a.info.name);
5786                }
5787            }
5788            if (r != null) {
5789                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5790            }
5791
5792            N = pkg.permissionGroups.size();
5793            r = null;
5794            for (i=0; i<N; i++) {
5795                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5796                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5797                if (cur == null) {
5798                    mPermissionGroups.put(pg.info.name, pg);
5799                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5800                        if (r == null) {
5801                            r = new StringBuilder(256);
5802                        } else {
5803                            r.append(' ');
5804                        }
5805                        r.append(pg.info.name);
5806                    }
5807                } else {
5808                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5809                            + pg.info.packageName + " ignored: original from "
5810                            + cur.info.packageName);
5811                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5812                        if (r == null) {
5813                            r = new StringBuilder(256);
5814                        } else {
5815                            r.append(' ');
5816                        }
5817                        r.append("DUP:");
5818                        r.append(pg.info.name);
5819                    }
5820                }
5821            }
5822            if (r != null) {
5823                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5824            }
5825
5826            N = pkg.permissions.size();
5827            r = null;
5828            for (i=0; i<N; i++) {
5829                PackageParser.Permission p = pkg.permissions.get(i);
5830                HashMap<String, BasePermission> permissionMap =
5831                        p.tree ? mSettings.mPermissionTrees
5832                        : mSettings.mPermissions;
5833                p.group = mPermissionGroups.get(p.info.group);
5834                if (p.info.group == null || p.group != null) {
5835                    BasePermission bp = permissionMap.get(p.info.name);
5836                    if (bp == null) {
5837                        bp = new BasePermission(p.info.name, p.info.packageName,
5838                                BasePermission.TYPE_NORMAL);
5839                        permissionMap.put(p.info.name, bp);
5840                    }
5841                    if (bp.perm == null) {
5842                        if (bp.sourcePackage != null
5843                                && !bp.sourcePackage.equals(p.info.packageName)) {
5844                            // If this is a permission that was formerly defined by a non-system
5845                            // app, but is now defined by a system app (following an upgrade),
5846                            // discard the previous declaration and consider the system's to be
5847                            // canonical.
5848                            if (isSystemApp(p.owner)) {
5849                                String msg = "New decl " + p.owner + " of permission  "
5850                                        + p.info.name + " is system";
5851                                reportSettingsProblem(Log.WARN, msg);
5852                                bp.sourcePackage = null;
5853                            }
5854                        }
5855                        if (bp.sourcePackage == null
5856                                || bp.sourcePackage.equals(p.info.packageName)) {
5857                            BasePermission tree = findPermissionTreeLP(p.info.name);
5858                            if (tree == null
5859                                    || tree.sourcePackage.equals(p.info.packageName)) {
5860                                bp.packageSetting = pkgSetting;
5861                                bp.perm = p;
5862                                bp.uid = pkg.applicationInfo.uid;
5863                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5864                                    if (r == null) {
5865                                        r = new StringBuilder(256);
5866                                    } else {
5867                                        r.append(' ');
5868                                    }
5869                                    r.append(p.info.name);
5870                                }
5871                            } else {
5872                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5873                                        + p.info.packageName + " ignored: base tree "
5874                                        + tree.name + " is from package "
5875                                        + tree.sourcePackage);
5876                            }
5877                        } else {
5878                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5879                                    + p.info.packageName + " ignored: original from "
5880                                    + bp.sourcePackage);
5881                        }
5882                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5883                        if (r == null) {
5884                            r = new StringBuilder(256);
5885                        } else {
5886                            r.append(' ');
5887                        }
5888                        r.append("DUP:");
5889                        r.append(p.info.name);
5890                    }
5891                    if (bp.perm == p) {
5892                        bp.protectionLevel = p.info.protectionLevel;
5893                    }
5894                } else {
5895                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5896                            + p.info.packageName + " ignored: no group "
5897                            + p.group);
5898                }
5899            }
5900            if (r != null) {
5901                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5902            }
5903
5904            N = pkg.instrumentation.size();
5905            r = null;
5906            for (i=0; i<N; i++) {
5907                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5908                a.info.packageName = pkg.applicationInfo.packageName;
5909                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5910                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5911                a.info.dataDir = pkg.applicationInfo.dataDir;
5912                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5913                mInstrumentation.put(a.getComponentName(), a);
5914                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5915                    if (r == null) {
5916                        r = new StringBuilder(256);
5917                    } else {
5918                        r.append(' ');
5919                    }
5920                    r.append(a.info.name);
5921                }
5922            }
5923            if (r != null) {
5924                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5925            }
5926
5927            if (pkg.protectedBroadcasts != null) {
5928                N = pkg.protectedBroadcasts.size();
5929                for (i=0; i<N; i++) {
5930                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5931                }
5932            }
5933
5934            pkgSetting.setTimeStamp(scanFileTime);
5935
5936            // Create idmap files for pairs of (packages, overlay packages).
5937            // Note: "android", ie framework-res.apk, is handled by native layers.
5938            if (pkg.mOverlayTarget != null) {
5939                // This is an overlay package.
5940                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5941                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5942                        mOverlays.put(pkg.mOverlayTarget,
5943                                new HashMap<String, PackageParser.Package>());
5944                    }
5945                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5946                    map.put(pkg.packageName, pkg);
5947                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5948                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5949                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5950                        return null;
5951                    }
5952                }
5953            } else if (mOverlays.containsKey(pkg.packageName) &&
5954                    !pkg.packageName.equals("android")) {
5955                // This is a regular package, with one or more known overlay packages.
5956                createIdmapsForPackageLI(pkg);
5957            }
5958        }
5959
5960        return pkg;
5961    }
5962
5963    /**
5964     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5965     * i.e, so that all packages can be run inside a single process if required.
5966     *
5967     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5968     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5969     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5970     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5971     * updating a package that belongs to a shared user.
5972     */
5973    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5974            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5975        String requiredInstructionSet = null;
5976        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5977            requiredInstructionSet = VMRuntime.getInstructionSet(
5978                     scannedPackage.applicationInfo.cpuAbi);
5979        }
5980
5981        PackageSetting requirer = null;
5982        for (PackageSetting ps : packagesForUser) {
5983            // If packagesForUser contains scannedPackage, we skip it. This will happen
5984            // when scannedPackage is an update of an existing package. Without this check,
5985            // we will never be able to change the ABI of any package belonging to a shared
5986            // user, even if it's compatible with other packages.
5987            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
5988                if (ps.cpuAbiString == null) {
5989                    continue;
5990                }
5991
5992                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5993                if (requiredInstructionSet != null) {
5994                    if (!instructionSet.equals(requiredInstructionSet)) {
5995                        // We have a mismatch between instruction sets (say arm vs arm64).
5996                        // bail out.
5997                        String errorMessage = "Instruction set mismatch, "
5998                                + ((requirer == null) ? "[caller]" : requirer)
5999                                + " requires " + requiredInstructionSet + " whereas " + ps
6000                                + " requires " + instructionSet;
6001                        Slog.e(TAG, errorMessage);
6002
6003                        reportSettingsProblem(Log.WARN, errorMessage);
6004                        // Give up, don't bother making any other changes to the package settings.
6005                        return false;
6006                    }
6007                } else {
6008                    requiredInstructionSet = instructionSet;
6009                    requirer = ps;
6010                }
6011            }
6012        }
6013
6014        if (requiredInstructionSet != null) {
6015            String adjustedAbi;
6016            if (requirer != null) {
6017                // requirer != null implies that either scannedPackage was null or that scannedPackage
6018                // did not require an ABI, in which case we have to adjust scannedPackage to match
6019                // the ABI of the set (which is the same as requirer's ABI)
6020                adjustedAbi = requirer.cpuAbiString;
6021                if (scannedPackage != null) {
6022                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6023                }
6024            } else {
6025                // requirer == null implies that we're updating all ABIs in the set to
6026                // match scannedPackage.
6027                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6028            }
6029
6030            for (PackageSetting ps : packagesForUser) {
6031                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6032                    if (ps.cpuAbiString != null) {
6033                        continue;
6034                    }
6035
6036                    ps.cpuAbiString = adjustedAbi;
6037                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6038                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6039                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6040
6041                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6042                            ps.cpuAbiString = null;
6043                            ps.pkg.applicationInfo.cpuAbi = null;
6044                            return false;
6045                        } else {
6046                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6047                        }
6048                    }
6049                }
6050            }
6051        }
6052
6053        return true;
6054    }
6055
6056    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6057        synchronized (mPackages) {
6058            mResolverReplaced = true;
6059            // Set up information for custom user intent resolution activity.
6060            mResolveActivity.applicationInfo = pkg.applicationInfo;
6061            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6062            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6063            mResolveActivity.processName = null;
6064            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6065            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6066                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6067            mResolveActivity.theme = 0;
6068            mResolveActivity.exported = true;
6069            mResolveActivity.enabled = true;
6070            mResolveInfo.activityInfo = mResolveActivity;
6071            mResolveInfo.priority = 0;
6072            mResolveInfo.preferredOrder = 0;
6073            mResolveInfo.match = 0;
6074            mResolveComponentName = mCustomResolverComponentName;
6075            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6076                    mResolveComponentName);
6077        }
6078    }
6079
6080    private String calculateApkRoot(final String codePathString) {
6081        final File codePath = new File(codePathString);
6082        final File codeRoot;
6083        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6084            codeRoot = Environment.getRootDirectory();
6085        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6086            codeRoot = Environment.getOemDirectory();
6087        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6088            codeRoot = Environment.getVendorDirectory();
6089        } else {
6090            // Unrecognized code path; take its top real segment as the apk root:
6091            // e.g. /something/app/blah.apk => /something
6092            try {
6093                File f = codePath.getCanonicalFile();
6094                File parent = f.getParentFile();    // non-null because codePath is a file
6095                File tmp;
6096                while ((tmp = parent.getParentFile()) != null) {
6097                    f = parent;
6098                    parent = tmp;
6099                }
6100                codeRoot = f;
6101                Slog.w(TAG, "Unrecognized code path "
6102                        + codePath + " - using " + codeRoot);
6103            } catch (IOException e) {
6104                // Can't canonicalize the lib path -- shenanigans?
6105                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6106                return Environment.getRootDirectory().getPath();
6107            }
6108        }
6109        return codeRoot.getPath();
6110    }
6111
6112    // This is the initial scan-time determination of how to handle a given
6113    // package for purposes of native library location.
6114    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6115            PackageSetting pkgSetting) {
6116        // "bundled" here means system-installed with no overriding update
6117        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6118        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6119        final File libDir;
6120        if (bundledApk) {
6121            // If "/system/lib64/apkname" exists, assume that is the per-package
6122            // native library directory to use; otherwise use "/system/lib/apkname".
6123            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6124            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6125            File packLib64 = new File(lib64, apkName);
6126            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6127        } else {
6128            libDir = mAppLibInstallDir;
6129        }
6130        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6131        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6132        // pkgSetting might be null during rescan following uninstall of updates
6133        // to a bundled app, so accommodate that possibility.  The settings in
6134        // that case will be established later from the parsed package.
6135        if (pkgSetting != null) {
6136            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6137        }
6138    }
6139
6140    // Deduces the required ABI of an upgraded system app.
6141    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6142        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6143        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6144
6145        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6146        // or similar.
6147        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6148        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6149
6150        // Assume that the bundled native libraries always correspond to the
6151        // most preferred 32 or 64 bit ABI.
6152        if (lib64.exists()) {
6153            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6154            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6155        } else if (lib.exists()) {
6156            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6157            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6158        } else {
6159            // This is the case where the app has no native code.
6160            pkg.applicationInfo.cpuAbi = null;
6161            pkgSetting.cpuAbiString = null;
6162        }
6163    }
6164
6165    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6166            final File nativeLibraryDir, String[] abiList) throws IOException {
6167        if (!nativeLibraryDir.isDirectory()) {
6168            nativeLibraryDir.delete();
6169
6170            if (!nativeLibraryDir.mkdir()) {
6171                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6172            }
6173
6174            try {
6175                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6176            } catch (ErrnoException e) {
6177                throw new IOException("Cannot chmod native library directory "
6178                        + nativeLibraryDir.getPath(), e);
6179            }
6180        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6181            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6182        }
6183
6184        /*
6185         * If this is an internal application or our nativeLibraryPath points to
6186         * the app-lib directory, unpack the libraries if necessary.
6187         */
6188        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6189        if (abi >= 0) {
6190            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6191                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6192            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6193                return copyRet;
6194            }
6195        }
6196
6197        return abi;
6198    }
6199
6200    private void killApplication(String pkgName, int appId, String reason) {
6201        // Request the ActivityManager to kill the process(only for existing packages)
6202        // so that we do not end up in a confused state while the user is still using the older
6203        // version of the application while the new one gets installed.
6204        IActivityManager am = ActivityManagerNative.getDefault();
6205        if (am != null) {
6206            try {
6207                am.killApplicationWithAppId(pkgName, appId, reason);
6208            } catch (RemoteException e) {
6209            }
6210        }
6211    }
6212
6213    void removePackageLI(PackageSetting ps, boolean chatty) {
6214        if (DEBUG_INSTALL) {
6215            if (chatty)
6216                Log.d(TAG, "Removing package " + ps.name);
6217        }
6218
6219        // writer
6220        synchronized (mPackages) {
6221            mPackages.remove(ps.name);
6222            if (ps.codePathString != null) {
6223                mAppDirs.remove(ps.codePathString);
6224            }
6225
6226            final PackageParser.Package pkg = ps.pkg;
6227            if (pkg != null) {
6228                cleanPackageDataStructuresLILPw(pkg, chatty);
6229            }
6230        }
6231    }
6232
6233    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6234        if (DEBUG_INSTALL) {
6235            if (chatty)
6236                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6237        }
6238
6239        // writer
6240        synchronized (mPackages) {
6241            mPackages.remove(pkg.applicationInfo.packageName);
6242            if (pkg.codePath != null) {
6243                mAppDirs.remove(pkg.codePath);
6244            }
6245            cleanPackageDataStructuresLILPw(pkg, chatty);
6246        }
6247    }
6248
6249    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6250        int N = pkg.providers.size();
6251        StringBuilder r = null;
6252        int i;
6253        for (i=0; i<N; i++) {
6254            PackageParser.Provider p = pkg.providers.get(i);
6255            mProviders.removeProvider(p);
6256            if (p.info.authority == null) {
6257
6258                /* There was another ContentProvider with this authority when
6259                 * this app was installed so this authority is null,
6260                 * Ignore it as we don't have to unregister the provider.
6261                 */
6262                continue;
6263            }
6264            String names[] = p.info.authority.split(";");
6265            for (int j = 0; j < names.length; j++) {
6266                if (mProvidersByAuthority.get(names[j]) == p) {
6267                    mProvidersByAuthority.remove(names[j]);
6268                    if (DEBUG_REMOVE) {
6269                        if (chatty)
6270                            Log.d(TAG, "Unregistered content provider: " + names[j]
6271                                    + ", className = " + p.info.name + ", isSyncable = "
6272                                    + p.info.isSyncable);
6273                    }
6274                }
6275            }
6276            if (DEBUG_REMOVE && chatty) {
6277                if (r == null) {
6278                    r = new StringBuilder(256);
6279                } else {
6280                    r.append(' ');
6281                }
6282                r.append(p.info.name);
6283            }
6284        }
6285        if (r != null) {
6286            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6287        }
6288
6289        N = pkg.services.size();
6290        r = null;
6291        for (i=0; i<N; i++) {
6292            PackageParser.Service s = pkg.services.get(i);
6293            mServices.removeService(s);
6294            if (chatty) {
6295                if (r == null) {
6296                    r = new StringBuilder(256);
6297                } else {
6298                    r.append(' ');
6299                }
6300                r.append(s.info.name);
6301            }
6302        }
6303        if (r != null) {
6304            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6305        }
6306
6307        N = pkg.receivers.size();
6308        r = null;
6309        for (i=0; i<N; i++) {
6310            PackageParser.Activity a = pkg.receivers.get(i);
6311            mReceivers.removeActivity(a, "receiver");
6312            if (DEBUG_REMOVE && chatty) {
6313                if (r == null) {
6314                    r = new StringBuilder(256);
6315                } else {
6316                    r.append(' ');
6317                }
6318                r.append(a.info.name);
6319            }
6320        }
6321        if (r != null) {
6322            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6323        }
6324
6325        N = pkg.activities.size();
6326        r = null;
6327        for (i=0; i<N; i++) {
6328            PackageParser.Activity a = pkg.activities.get(i);
6329            mActivities.removeActivity(a, "activity");
6330            if (DEBUG_REMOVE && chatty) {
6331                if (r == null) {
6332                    r = new StringBuilder(256);
6333                } else {
6334                    r.append(' ');
6335                }
6336                r.append(a.info.name);
6337            }
6338        }
6339        if (r != null) {
6340            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6341        }
6342
6343        N = pkg.permissions.size();
6344        r = null;
6345        for (i=0; i<N; i++) {
6346            PackageParser.Permission p = pkg.permissions.get(i);
6347            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6348            if (bp == null) {
6349                bp = mSettings.mPermissionTrees.get(p.info.name);
6350            }
6351            if (bp != null && bp.perm == p) {
6352                bp.perm = null;
6353                if (DEBUG_REMOVE && chatty) {
6354                    if (r == null) {
6355                        r = new StringBuilder(256);
6356                    } else {
6357                        r.append(' ');
6358                    }
6359                    r.append(p.info.name);
6360                }
6361            }
6362        }
6363        if (r != null) {
6364            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6365        }
6366
6367        N = pkg.instrumentation.size();
6368        r = null;
6369        for (i=0; i<N; i++) {
6370            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6371            mInstrumentation.remove(a.getComponentName());
6372            if (DEBUG_REMOVE && chatty) {
6373                if (r == null) {
6374                    r = new StringBuilder(256);
6375                } else {
6376                    r.append(' ');
6377                }
6378                r.append(a.info.name);
6379            }
6380        }
6381        if (r != null) {
6382            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6383        }
6384
6385        r = null;
6386        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6387            // Only system apps can hold shared libraries.
6388            if (pkg.libraryNames != null) {
6389                for (i=0; i<pkg.libraryNames.size(); i++) {
6390                    String name = pkg.libraryNames.get(i);
6391                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6392                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6393                        mSharedLibraries.remove(name);
6394                        if (DEBUG_REMOVE && chatty) {
6395                            if (r == null) {
6396                                r = new StringBuilder(256);
6397                            } else {
6398                                r.append(' ');
6399                            }
6400                            r.append(name);
6401                        }
6402                    }
6403                }
6404            }
6405        }
6406        if (r != null) {
6407            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6408        }
6409    }
6410
6411    private static final boolean isPackageFilename(String name) {
6412        return name != null && name.endsWith(".apk");
6413    }
6414
6415    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6416        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6417            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6418                return true;
6419            }
6420        }
6421        return false;
6422    }
6423
6424    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6425    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6426    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6427
6428    private void updatePermissionsLPw(String changingPkg,
6429            PackageParser.Package pkgInfo, int flags) {
6430        // Make sure there are no dangling permission trees.
6431        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6432        while (it.hasNext()) {
6433            final BasePermission bp = it.next();
6434            if (bp.packageSetting == null) {
6435                // We may not yet have parsed the package, so just see if
6436                // we still know about its settings.
6437                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6438            }
6439            if (bp.packageSetting == null) {
6440                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6441                        + " from package " + bp.sourcePackage);
6442                it.remove();
6443            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6444                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6445                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6446                            + " from package " + bp.sourcePackage);
6447                    flags |= UPDATE_PERMISSIONS_ALL;
6448                    it.remove();
6449                }
6450            }
6451        }
6452
6453        // Make sure all dynamic permissions have been assigned to a package,
6454        // and make sure there are no dangling permissions.
6455        it = mSettings.mPermissions.values().iterator();
6456        while (it.hasNext()) {
6457            final BasePermission bp = it.next();
6458            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6459                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6460                        + bp.name + " pkg=" + bp.sourcePackage
6461                        + " info=" + bp.pendingInfo);
6462                if (bp.packageSetting == null && bp.pendingInfo != null) {
6463                    final BasePermission tree = findPermissionTreeLP(bp.name);
6464                    if (tree != null && tree.perm != null) {
6465                        bp.packageSetting = tree.packageSetting;
6466                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6467                                new PermissionInfo(bp.pendingInfo));
6468                        bp.perm.info.packageName = tree.perm.info.packageName;
6469                        bp.perm.info.name = bp.name;
6470                        bp.uid = tree.uid;
6471                    }
6472                }
6473            }
6474            if (bp.packageSetting == null) {
6475                // We may not yet have parsed the package, so just see if
6476                // we still know about its settings.
6477                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6478            }
6479            if (bp.packageSetting == null) {
6480                Slog.w(TAG, "Removing dangling permission: " + bp.name
6481                        + " from package " + bp.sourcePackage);
6482                it.remove();
6483            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6484                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6485                    Slog.i(TAG, "Removing old permission: " + bp.name
6486                            + " from package " + bp.sourcePackage);
6487                    flags |= UPDATE_PERMISSIONS_ALL;
6488                    it.remove();
6489                }
6490            }
6491        }
6492
6493        // Now update the permissions for all packages, in particular
6494        // replace the granted permissions of the system packages.
6495        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6496            for (PackageParser.Package pkg : mPackages.values()) {
6497                if (pkg != pkgInfo) {
6498                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6499                }
6500            }
6501        }
6502
6503        if (pkgInfo != null) {
6504            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6505        }
6506    }
6507
6508    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6509        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6510        if (ps == null) {
6511            return;
6512        }
6513        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6514        HashSet<String> origPermissions = gp.grantedPermissions;
6515        boolean changedPermission = false;
6516
6517        if (replace) {
6518            ps.permissionsFixed = false;
6519            if (gp == ps) {
6520                origPermissions = new HashSet<String>(gp.grantedPermissions);
6521                gp.grantedPermissions.clear();
6522                gp.gids = mGlobalGids;
6523            }
6524        }
6525
6526        if (gp.gids == null) {
6527            gp.gids = mGlobalGids;
6528        }
6529
6530        final int N = pkg.requestedPermissions.size();
6531        for (int i=0; i<N; i++) {
6532            final String name = pkg.requestedPermissions.get(i);
6533            final boolean required = pkg.requestedPermissionsRequired.get(i);
6534            final BasePermission bp = mSettings.mPermissions.get(name);
6535            if (DEBUG_INSTALL) {
6536                if (gp != ps) {
6537                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6538                }
6539            }
6540
6541            if (bp == null || bp.packageSetting == null) {
6542                Slog.w(TAG, "Unknown permission " + name
6543                        + " in package " + pkg.packageName);
6544                continue;
6545            }
6546
6547            final String perm = bp.name;
6548            boolean allowed;
6549            boolean allowedSig = false;
6550            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6551            if (level == PermissionInfo.PROTECTION_NORMAL
6552                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6553                // We grant a normal or dangerous permission if any of the following
6554                // are true:
6555                // 1) The permission is required
6556                // 2) The permission is optional, but was granted in the past
6557                // 3) The permission is optional, but was requested by an
6558                //    app in /system (not /data)
6559                //
6560                // Otherwise, reject the permission.
6561                allowed = (required || origPermissions.contains(perm)
6562                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6563            } else if (bp.packageSetting == null) {
6564                // This permission is invalid; skip it.
6565                allowed = false;
6566            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6567                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6568                if (allowed) {
6569                    allowedSig = true;
6570                }
6571            } else {
6572                allowed = false;
6573            }
6574            if (DEBUG_INSTALL) {
6575                if (gp != ps) {
6576                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6577                }
6578            }
6579            if (allowed) {
6580                if (!isSystemApp(ps) && ps.permissionsFixed) {
6581                    // If this is an existing, non-system package, then
6582                    // we can't add any new permissions to it.
6583                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6584                        // Except...  if this is a permission that was added
6585                        // to the platform (note: need to only do this when
6586                        // updating the platform).
6587                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6588                    }
6589                }
6590                if (allowed) {
6591                    if (!gp.grantedPermissions.contains(perm)) {
6592                        changedPermission = true;
6593                        gp.grantedPermissions.add(perm);
6594                        gp.gids = appendInts(gp.gids, bp.gids);
6595                    } else if (!ps.haveGids) {
6596                        gp.gids = appendInts(gp.gids, bp.gids);
6597                    }
6598                } else {
6599                    Slog.w(TAG, "Not granting permission " + perm
6600                            + " to package " + pkg.packageName
6601                            + " because it was previously installed without");
6602                }
6603            } else {
6604                if (gp.grantedPermissions.remove(perm)) {
6605                    changedPermission = true;
6606                    gp.gids = removeInts(gp.gids, bp.gids);
6607                    Slog.i(TAG, "Un-granting permission " + perm
6608                            + " from package " + pkg.packageName
6609                            + " (protectionLevel=" + bp.protectionLevel
6610                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6611                            + ")");
6612                } else {
6613                    Slog.w(TAG, "Not granting permission " + perm
6614                            + " to package " + pkg.packageName
6615                            + " (protectionLevel=" + bp.protectionLevel
6616                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6617                            + ")");
6618                }
6619            }
6620        }
6621
6622        if ((changedPermission || replace) && !ps.permissionsFixed &&
6623                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6624            // This is the first that we have heard about this package, so the
6625            // permissions we have now selected are fixed until explicitly
6626            // changed.
6627            ps.permissionsFixed = true;
6628        }
6629        ps.haveGids = true;
6630    }
6631
6632    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6633        boolean allowed = false;
6634        final int NP = PackageParser.NEW_PERMISSIONS.length;
6635        for (int ip=0; ip<NP; ip++) {
6636            final PackageParser.NewPermissionInfo npi
6637                    = PackageParser.NEW_PERMISSIONS[ip];
6638            if (npi.name.equals(perm)
6639                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6640                allowed = true;
6641                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6642                        + pkg.packageName);
6643                break;
6644            }
6645        }
6646        return allowed;
6647    }
6648
6649    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6650                                          BasePermission bp, HashSet<String> origPermissions) {
6651        boolean allowed;
6652        allowed = (compareSignatures(
6653                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6654                        == PackageManager.SIGNATURE_MATCH)
6655                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6656                        == PackageManager.SIGNATURE_MATCH);
6657        if (!allowed && (bp.protectionLevel
6658                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6659            if (isSystemApp(pkg)) {
6660                // For updated system applications, a system permission
6661                // is granted only if it had been defined by the original application.
6662                if (isUpdatedSystemApp(pkg)) {
6663                    final PackageSetting sysPs = mSettings
6664                            .getDisabledSystemPkgLPr(pkg.packageName);
6665                    final GrantedPermissions origGp = sysPs.sharedUser != null
6666                            ? sysPs.sharedUser : sysPs;
6667
6668                    if (origGp.grantedPermissions.contains(perm)) {
6669                        // If the original was granted this permission, we take
6670                        // that grant decision as read and propagate it to the
6671                        // update.
6672                        allowed = true;
6673                    } else {
6674                        // The system apk may have been updated with an older
6675                        // version of the one on the data partition, but which
6676                        // granted a new system permission that it didn't have
6677                        // before.  In this case we do want to allow the app to
6678                        // now get the new permission if the ancestral apk is
6679                        // privileged to get it.
6680                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6681                            for (int j=0;
6682                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6683                                if (perm.equals(
6684                                        sysPs.pkg.requestedPermissions.get(j))) {
6685                                    allowed = true;
6686                                    break;
6687                                }
6688                            }
6689                        }
6690                    }
6691                } else {
6692                    allowed = isPrivilegedApp(pkg);
6693                }
6694            }
6695        }
6696        if (!allowed && (bp.protectionLevel
6697                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6698            // For development permissions, a development permission
6699            // is granted only if it was already granted.
6700            allowed = origPermissions.contains(perm);
6701        }
6702        return allowed;
6703    }
6704
6705    final class ActivityIntentResolver
6706            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6707        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6708                boolean defaultOnly, int userId) {
6709            if (!sUserManager.exists(userId)) return null;
6710            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6711            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6712        }
6713
6714        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6715                int userId) {
6716            if (!sUserManager.exists(userId)) return null;
6717            mFlags = flags;
6718            return super.queryIntent(intent, resolvedType,
6719                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6720        }
6721
6722        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6723                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6724            if (!sUserManager.exists(userId)) return null;
6725            if (packageActivities == null) {
6726                return null;
6727            }
6728            mFlags = flags;
6729            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6730            final int N = packageActivities.size();
6731            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6732                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6733
6734            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6735            for (int i = 0; i < N; ++i) {
6736                intentFilters = packageActivities.get(i).intents;
6737                if (intentFilters != null && intentFilters.size() > 0) {
6738                    PackageParser.ActivityIntentInfo[] array =
6739                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6740                    intentFilters.toArray(array);
6741                    listCut.add(array);
6742                }
6743            }
6744            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6745        }
6746
6747        public final void addActivity(PackageParser.Activity a, String type) {
6748            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6749            mActivities.put(a.getComponentName(), a);
6750            if (DEBUG_SHOW_INFO)
6751                Log.v(
6752                TAG, "  " + type + " " +
6753                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6754            if (DEBUG_SHOW_INFO)
6755                Log.v(TAG, "    Class=" + a.info.name);
6756            final int NI = a.intents.size();
6757            for (int j=0; j<NI; j++) {
6758                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6759                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6760                    intent.setPriority(0);
6761                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6762                            + a.className + " with priority > 0, forcing to 0");
6763                }
6764                if (DEBUG_SHOW_INFO) {
6765                    Log.v(TAG, "    IntentFilter:");
6766                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6767                }
6768                if (!intent.debugCheck()) {
6769                    Log.w(TAG, "==> For Activity " + a.info.name);
6770                }
6771                addFilter(intent);
6772            }
6773        }
6774
6775        public final void removeActivity(PackageParser.Activity a, String type) {
6776            mActivities.remove(a.getComponentName());
6777            if (DEBUG_SHOW_INFO) {
6778                Log.v(TAG, "  " + type + " "
6779                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6780                                : a.info.name) + ":");
6781                Log.v(TAG, "    Class=" + a.info.name);
6782            }
6783            final int NI = a.intents.size();
6784            for (int j=0; j<NI; j++) {
6785                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6786                if (DEBUG_SHOW_INFO) {
6787                    Log.v(TAG, "    IntentFilter:");
6788                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6789                }
6790                removeFilter(intent);
6791            }
6792        }
6793
6794        @Override
6795        protected boolean allowFilterResult(
6796                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6797            ActivityInfo filterAi = filter.activity.info;
6798            for (int i=dest.size()-1; i>=0; i--) {
6799                ActivityInfo destAi = dest.get(i).activityInfo;
6800                if (destAi.name == filterAi.name
6801                        && destAi.packageName == filterAi.packageName) {
6802                    return false;
6803                }
6804            }
6805            return true;
6806        }
6807
6808        @Override
6809        protected ActivityIntentInfo[] newArray(int size) {
6810            return new ActivityIntentInfo[size];
6811        }
6812
6813        @Override
6814        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6815            if (!sUserManager.exists(userId)) return true;
6816            PackageParser.Package p = filter.activity.owner;
6817            if (p != null) {
6818                PackageSetting ps = (PackageSetting)p.mExtras;
6819                if (ps != null) {
6820                    // System apps are never considered stopped for purposes of
6821                    // filtering, because there may be no way for the user to
6822                    // actually re-launch them.
6823                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6824                            && ps.getStopped(userId);
6825                }
6826            }
6827            return false;
6828        }
6829
6830        @Override
6831        protected boolean isPackageForFilter(String packageName,
6832                PackageParser.ActivityIntentInfo info) {
6833            return packageName.equals(info.activity.owner.packageName);
6834        }
6835
6836        @Override
6837        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6838                int match, int userId) {
6839            if (!sUserManager.exists(userId)) return null;
6840            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6841                return null;
6842            }
6843            final PackageParser.Activity activity = info.activity;
6844            if (mSafeMode && (activity.info.applicationInfo.flags
6845                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6846                return null;
6847            }
6848            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6849            if (ps == null) {
6850                return null;
6851            }
6852            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6853                    ps.readUserState(userId), userId);
6854            if (ai == null) {
6855                return null;
6856            }
6857            final ResolveInfo res = new ResolveInfo();
6858            res.activityInfo = ai;
6859            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6860                res.filter = info;
6861            }
6862            res.priority = info.getPriority();
6863            res.preferredOrder = activity.owner.mPreferredOrder;
6864            //System.out.println("Result: " + res.activityInfo.className +
6865            //                   " = " + res.priority);
6866            res.match = match;
6867            res.isDefault = info.hasDefault;
6868            res.labelRes = info.labelRes;
6869            res.nonLocalizedLabel = info.nonLocalizedLabel;
6870            res.icon = info.icon;
6871            res.system = isSystemApp(res.activityInfo.applicationInfo);
6872            return res;
6873        }
6874
6875        @Override
6876        protected void sortResults(List<ResolveInfo> results) {
6877            Collections.sort(results, mResolvePrioritySorter);
6878        }
6879
6880        @Override
6881        protected void dumpFilter(PrintWriter out, String prefix,
6882                PackageParser.ActivityIntentInfo filter) {
6883            out.print(prefix); out.print(
6884                    Integer.toHexString(System.identityHashCode(filter.activity)));
6885                    out.print(' ');
6886                    filter.activity.printComponentShortName(out);
6887                    out.print(" filter ");
6888                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6889        }
6890
6891//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6892//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6893//            final List<ResolveInfo> retList = Lists.newArrayList();
6894//            while (i.hasNext()) {
6895//                final ResolveInfo resolveInfo = i.next();
6896//                if (isEnabledLP(resolveInfo.activityInfo)) {
6897//                    retList.add(resolveInfo);
6898//                }
6899//            }
6900//            return retList;
6901//        }
6902
6903        // Keys are String (activity class name), values are Activity.
6904        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6905                = new HashMap<ComponentName, PackageParser.Activity>();
6906        private int mFlags;
6907    }
6908
6909    private final class ServiceIntentResolver
6910            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6911        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6912                boolean defaultOnly, int userId) {
6913            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6914            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6915        }
6916
6917        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6918                int userId) {
6919            if (!sUserManager.exists(userId)) return null;
6920            mFlags = flags;
6921            return super.queryIntent(intent, resolvedType,
6922                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6923        }
6924
6925        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6926                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6927            if (!sUserManager.exists(userId)) return null;
6928            if (packageServices == null) {
6929                return null;
6930            }
6931            mFlags = flags;
6932            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6933            final int N = packageServices.size();
6934            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6935                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6936
6937            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6938            for (int i = 0; i < N; ++i) {
6939                intentFilters = packageServices.get(i).intents;
6940                if (intentFilters != null && intentFilters.size() > 0) {
6941                    PackageParser.ServiceIntentInfo[] array =
6942                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6943                    intentFilters.toArray(array);
6944                    listCut.add(array);
6945                }
6946            }
6947            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6948        }
6949
6950        public final void addService(PackageParser.Service s) {
6951            mServices.put(s.getComponentName(), s);
6952            if (DEBUG_SHOW_INFO) {
6953                Log.v(TAG, "  "
6954                        + (s.info.nonLocalizedLabel != null
6955                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6956                Log.v(TAG, "    Class=" + s.info.name);
6957            }
6958            final int NI = s.intents.size();
6959            int j;
6960            for (j=0; j<NI; j++) {
6961                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6962                if (DEBUG_SHOW_INFO) {
6963                    Log.v(TAG, "    IntentFilter:");
6964                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6965                }
6966                if (!intent.debugCheck()) {
6967                    Log.w(TAG, "==> For Service " + s.info.name);
6968                }
6969                addFilter(intent);
6970            }
6971        }
6972
6973        public final void removeService(PackageParser.Service s) {
6974            mServices.remove(s.getComponentName());
6975            if (DEBUG_SHOW_INFO) {
6976                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6977                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6978                Log.v(TAG, "    Class=" + s.info.name);
6979            }
6980            final int NI = s.intents.size();
6981            int j;
6982            for (j=0; j<NI; j++) {
6983                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6984                if (DEBUG_SHOW_INFO) {
6985                    Log.v(TAG, "    IntentFilter:");
6986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6987                }
6988                removeFilter(intent);
6989            }
6990        }
6991
6992        @Override
6993        protected boolean allowFilterResult(
6994                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6995            ServiceInfo filterSi = filter.service.info;
6996            for (int i=dest.size()-1; i>=0; i--) {
6997                ServiceInfo destAi = dest.get(i).serviceInfo;
6998                if (destAi.name == filterSi.name
6999                        && destAi.packageName == filterSi.packageName) {
7000                    return false;
7001                }
7002            }
7003            return true;
7004        }
7005
7006        @Override
7007        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7008            return new PackageParser.ServiceIntentInfo[size];
7009        }
7010
7011        @Override
7012        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7013            if (!sUserManager.exists(userId)) return true;
7014            PackageParser.Package p = filter.service.owner;
7015            if (p != null) {
7016                PackageSetting ps = (PackageSetting)p.mExtras;
7017                if (ps != null) {
7018                    // System apps are never considered stopped for purposes of
7019                    // filtering, because there may be no way for the user to
7020                    // actually re-launch them.
7021                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7022                            && ps.getStopped(userId);
7023                }
7024            }
7025            return false;
7026        }
7027
7028        @Override
7029        protected boolean isPackageForFilter(String packageName,
7030                PackageParser.ServiceIntentInfo info) {
7031            return packageName.equals(info.service.owner.packageName);
7032        }
7033
7034        @Override
7035        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7036                int match, int userId) {
7037            if (!sUserManager.exists(userId)) return null;
7038            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7039            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7040                return null;
7041            }
7042            final PackageParser.Service service = info.service;
7043            if (mSafeMode && (service.info.applicationInfo.flags
7044                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7045                return null;
7046            }
7047            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7048            if (ps == null) {
7049                return null;
7050            }
7051            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7052                    ps.readUserState(userId), userId);
7053            if (si == null) {
7054                return null;
7055            }
7056            final ResolveInfo res = new ResolveInfo();
7057            res.serviceInfo = si;
7058            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7059                res.filter = filter;
7060            }
7061            res.priority = info.getPriority();
7062            res.preferredOrder = service.owner.mPreferredOrder;
7063            //System.out.println("Result: " + res.activityInfo.className +
7064            //                   " = " + res.priority);
7065            res.match = match;
7066            res.isDefault = info.hasDefault;
7067            res.labelRes = info.labelRes;
7068            res.nonLocalizedLabel = info.nonLocalizedLabel;
7069            res.icon = info.icon;
7070            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7071            return res;
7072        }
7073
7074        @Override
7075        protected void sortResults(List<ResolveInfo> results) {
7076            Collections.sort(results, mResolvePrioritySorter);
7077        }
7078
7079        @Override
7080        protected void dumpFilter(PrintWriter out, String prefix,
7081                PackageParser.ServiceIntentInfo filter) {
7082            out.print(prefix); out.print(
7083                    Integer.toHexString(System.identityHashCode(filter.service)));
7084                    out.print(' ');
7085                    filter.service.printComponentShortName(out);
7086                    out.print(" filter ");
7087                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7088        }
7089
7090//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7091//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7092//            final List<ResolveInfo> retList = Lists.newArrayList();
7093//            while (i.hasNext()) {
7094//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7095//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7096//                    retList.add(resolveInfo);
7097//                }
7098//            }
7099//            return retList;
7100//        }
7101
7102        // Keys are String (activity class name), values are Activity.
7103        private final HashMap<ComponentName, PackageParser.Service> mServices
7104                = new HashMap<ComponentName, PackageParser.Service>();
7105        private int mFlags;
7106    };
7107
7108    private final class ProviderIntentResolver
7109            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7110        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7111                boolean defaultOnly, int userId) {
7112            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7113            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7114        }
7115
7116        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7117                int userId) {
7118            if (!sUserManager.exists(userId))
7119                return null;
7120            mFlags = flags;
7121            return super.queryIntent(intent, resolvedType,
7122                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7123        }
7124
7125        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7126                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7127            if (!sUserManager.exists(userId))
7128                return null;
7129            if (packageProviders == null) {
7130                return null;
7131            }
7132            mFlags = flags;
7133            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7134            final int N = packageProviders.size();
7135            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7136                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7137
7138            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7139            for (int i = 0; i < N; ++i) {
7140                intentFilters = packageProviders.get(i).intents;
7141                if (intentFilters != null && intentFilters.size() > 0) {
7142                    PackageParser.ProviderIntentInfo[] array =
7143                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7144                    intentFilters.toArray(array);
7145                    listCut.add(array);
7146                }
7147            }
7148            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7149        }
7150
7151        public final void addProvider(PackageParser.Provider p) {
7152            if (mProviders.containsKey(p.getComponentName())) {
7153                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7154                return;
7155            }
7156
7157            mProviders.put(p.getComponentName(), p);
7158            if (DEBUG_SHOW_INFO) {
7159                Log.v(TAG, "  "
7160                        + (p.info.nonLocalizedLabel != null
7161                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7162                Log.v(TAG, "    Class=" + p.info.name);
7163            }
7164            final int NI = p.intents.size();
7165            int j;
7166            for (j = 0; j < NI; j++) {
7167                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7168                if (DEBUG_SHOW_INFO) {
7169                    Log.v(TAG, "    IntentFilter:");
7170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7171                }
7172                if (!intent.debugCheck()) {
7173                    Log.w(TAG, "==> For Provider " + p.info.name);
7174                }
7175                addFilter(intent);
7176            }
7177        }
7178
7179        public final void removeProvider(PackageParser.Provider p) {
7180            mProviders.remove(p.getComponentName());
7181            if (DEBUG_SHOW_INFO) {
7182                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7183                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7184                Log.v(TAG, "    Class=" + p.info.name);
7185            }
7186            final int NI = p.intents.size();
7187            int j;
7188            for (j = 0; j < NI; j++) {
7189                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7190                if (DEBUG_SHOW_INFO) {
7191                    Log.v(TAG, "    IntentFilter:");
7192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7193                }
7194                removeFilter(intent);
7195            }
7196        }
7197
7198        @Override
7199        protected boolean allowFilterResult(
7200                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7201            ProviderInfo filterPi = filter.provider.info;
7202            for (int i = dest.size() - 1; i >= 0; i--) {
7203                ProviderInfo destPi = dest.get(i).providerInfo;
7204                if (destPi.name == filterPi.name
7205                        && destPi.packageName == filterPi.packageName) {
7206                    return false;
7207                }
7208            }
7209            return true;
7210        }
7211
7212        @Override
7213        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7214            return new PackageParser.ProviderIntentInfo[size];
7215        }
7216
7217        @Override
7218        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7219            if (!sUserManager.exists(userId))
7220                return true;
7221            PackageParser.Package p = filter.provider.owner;
7222            if (p != null) {
7223                PackageSetting ps = (PackageSetting) p.mExtras;
7224                if (ps != null) {
7225                    // System apps are never considered stopped for purposes of
7226                    // filtering, because there may be no way for the user to
7227                    // actually re-launch them.
7228                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7229                            && ps.getStopped(userId);
7230                }
7231            }
7232            return false;
7233        }
7234
7235        @Override
7236        protected boolean isPackageForFilter(String packageName,
7237                PackageParser.ProviderIntentInfo info) {
7238            return packageName.equals(info.provider.owner.packageName);
7239        }
7240
7241        @Override
7242        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7243                int match, int userId) {
7244            if (!sUserManager.exists(userId))
7245                return null;
7246            final PackageParser.ProviderIntentInfo info = filter;
7247            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7248                return null;
7249            }
7250            final PackageParser.Provider provider = info.provider;
7251            if (mSafeMode && (provider.info.applicationInfo.flags
7252                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7253                return null;
7254            }
7255            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7256            if (ps == null) {
7257                return null;
7258            }
7259            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7260                    ps.readUserState(userId), userId);
7261            if (pi == null) {
7262                return null;
7263            }
7264            final ResolveInfo res = new ResolveInfo();
7265            res.providerInfo = pi;
7266            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7267                res.filter = filter;
7268            }
7269            res.priority = info.getPriority();
7270            res.preferredOrder = provider.owner.mPreferredOrder;
7271            res.match = match;
7272            res.isDefault = info.hasDefault;
7273            res.labelRes = info.labelRes;
7274            res.nonLocalizedLabel = info.nonLocalizedLabel;
7275            res.icon = info.icon;
7276            res.system = isSystemApp(res.providerInfo.applicationInfo);
7277            return res;
7278        }
7279
7280        @Override
7281        protected void sortResults(List<ResolveInfo> results) {
7282            Collections.sort(results, mResolvePrioritySorter);
7283        }
7284
7285        @Override
7286        protected void dumpFilter(PrintWriter out, String prefix,
7287                PackageParser.ProviderIntentInfo filter) {
7288            out.print(prefix);
7289            out.print(
7290                    Integer.toHexString(System.identityHashCode(filter.provider)));
7291            out.print(' ');
7292            filter.provider.printComponentShortName(out);
7293            out.print(" filter ");
7294            out.println(Integer.toHexString(System.identityHashCode(filter)));
7295        }
7296
7297        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7298                = new HashMap<ComponentName, PackageParser.Provider>();
7299        private int mFlags;
7300    };
7301
7302    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7303            new Comparator<ResolveInfo>() {
7304        public int compare(ResolveInfo r1, ResolveInfo r2) {
7305            int v1 = r1.priority;
7306            int v2 = r2.priority;
7307            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7308            if (v1 != v2) {
7309                return (v1 > v2) ? -1 : 1;
7310            }
7311            v1 = r1.preferredOrder;
7312            v2 = r2.preferredOrder;
7313            if (v1 != v2) {
7314                return (v1 > v2) ? -1 : 1;
7315            }
7316            if (r1.isDefault != r2.isDefault) {
7317                return r1.isDefault ? -1 : 1;
7318            }
7319            v1 = r1.match;
7320            v2 = r2.match;
7321            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7322            if (v1 != v2) {
7323                return (v1 > v2) ? -1 : 1;
7324            }
7325            if (r1.system != r2.system) {
7326                return r1.system ? -1 : 1;
7327            }
7328            return 0;
7329        }
7330    };
7331
7332    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7333            new Comparator<ProviderInfo>() {
7334        public int compare(ProviderInfo p1, ProviderInfo p2) {
7335            final int v1 = p1.initOrder;
7336            final int v2 = p2.initOrder;
7337            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7338        }
7339    };
7340
7341    static final void sendPackageBroadcast(String action, String pkg,
7342            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7343            int[] userIds) {
7344        IActivityManager am = ActivityManagerNative.getDefault();
7345        if (am != null) {
7346            try {
7347                if (userIds == null) {
7348                    userIds = am.getRunningUserIds();
7349                }
7350                for (int id : userIds) {
7351                    final Intent intent = new Intent(action,
7352                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7353                    if (extras != null) {
7354                        intent.putExtras(extras);
7355                    }
7356                    if (targetPkg != null) {
7357                        intent.setPackage(targetPkg);
7358                    }
7359                    // Modify the UID when posting to other users
7360                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7361                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7362                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7363                        intent.putExtra(Intent.EXTRA_UID, uid);
7364                    }
7365                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7366                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7367                    if (DEBUG_BROADCASTS) {
7368                        RuntimeException here = new RuntimeException("here");
7369                        here.fillInStackTrace();
7370                        Slog.d(TAG, "Sending to user " + id + ": "
7371                                + intent.toShortString(false, true, false, false)
7372                                + " " + intent.getExtras(), here);
7373                    }
7374                    am.broadcastIntent(null, intent, null, finishedReceiver,
7375                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7376                            finishedReceiver != null, false, id);
7377                }
7378            } catch (RemoteException ex) {
7379            }
7380        }
7381    }
7382
7383    /**
7384     * Check if the external storage media is available. This is true if there
7385     * is a mounted external storage medium or if the external storage is
7386     * emulated.
7387     */
7388    private boolean isExternalMediaAvailable() {
7389        return mMediaMounted || Environment.isExternalStorageEmulated();
7390    }
7391
7392    @Override
7393    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7394        // writer
7395        synchronized (mPackages) {
7396            if (!isExternalMediaAvailable()) {
7397                // If the external storage is no longer mounted at this point,
7398                // the caller may not have been able to delete all of this
7399                // packages files and can not delete any more.  Bail.
7400                return null;
7401            }
7402            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7403            if (lastPackage != null) {
7404                pkgs.remove(lastPackage);
7405            }
7406            if (pkgs.size() > 0) {
7407                return pkgs.get(0);
7408            }
7409        }
7410        return null;
7411    }
7412
7413    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7414        if (false) {
7415            RuntimeException here = new RuntimeException("here");
7416            here.fillInStackTrace();
7417            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7418                    + " andCode=" + andCode, here);
7419        }
7420        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7421                userId, andCode ? 1 : 0, packageName));
7422    }
7423
7424    void startCleaningPackages() {
7425        // reader
7426        synchronized (mPackages) {
7427            if (!isExternalMediaAvailable()) {
7428                return;
7429            }
7430            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7431                return;
7432            }
7433        }
7434        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7435        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7436        IActivityManager am = ActivityManagerNative.getDefault();
7437        if (am != null) {
7438            try {
7439                am.startService(null, intent, null, UserHandle.USER_OWNER);
7440            } catch (RemoteException e) {
7441            }
7442        }
7443    }
7444
7445    private final class AppDirObserver extends FileObserver {
7446        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7447            super(path, mask);
7448            mRootDir = path;
7449            mIsRom = isrom;
7450            mIsPrivileged = isPrivileged;
7451        }
7452
7453        public void onEvent(int event, String path) {
7454            String removedPackage = null;
7455            int removedAppId = -1;
7456            int[] removedUsers = null;
7457            String addedPackage = null;
7458            int addedAppId = -1;
7459            int[] addedUsers = null;
7460
7461            // TODO post a message to the handler to obtain serial ordering
7462            synchronized (mInstallLock) {
7463                String fullPathStr = null;
7464                File fullPath = null;
7465                if (path != null) {
7466                    fullPath = new File(mRootDir, path);
7467                    fullPathStr = fullPath.getPath();
7468                }
7469
7470                if (DEBUG_APP_DIR_OBSERVER)
7471                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7472
7473                if (!isPackageFilename(path)) {
7474                    if (DEBUG_APP_DIR_OBSERVER)
7475                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7476                    return;
7477                }
7478
7479                // Ignore packages that are being installed or
7480                // have just been installed.
7481                if (ignoreCodePath(fullPathStr)) {
7482                    return;
7483                }
7484                PackageParser.Package p = null;
7485                PackageSetting ps = null;
7486                // reader
7487                synchronized (mPackages) {
7488                    p = mAppDirs.get(fullPathStr);
7489                    if (p != null) {
7490                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7491                        if (ps != null) {
7492                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7493                        } else {
7494                            removedUsers = sUserManager.getUserIds();
7495                        }
7496                    }
7497                    addedUsers = sUserManager.getUserIds();
7498                }
7499                if ((event&REMOVE_EVENTS) != 0) {
7500                    if (ps != null) {
7501                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7502                        removePackageLI(ps, true);
7503                        removedPackage = ps.name;
7504                        removedAppId = ps.appId;
7505                    }
7506                }
7507
7508                if ((event&ADD_EVENTS) != 0) {
7509                    if (p == null) {
7510                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7511                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7512                        if (mIsRom) {
7513                            flags |= PackageParser.PARSE_IS_SYSTEM
7514                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7515                            if (mIsPrivileged) {
7516                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7517                            }
7518                        }
7519                        p = scanPackageLI(fullPath, flags,
7520                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7521                                System.currentTimeMillis(), UserHandle.ALL, null);
7522                        if (p != null) {
7523                            /*
7524                             * TODO this seems dangerous as the package may have
7525                             * changed since we last acquired the mPackages
7526                             * lock.
7527                             */
7528                            // writer
7529                            synchronized (mPackages) {
7530                                updatePermissionsLPw(p.packageName, p,
7531                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7532                            }
7533                            addedPackage = p.applicationInfo.packageName;
7534                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7535                        }
7536                    }
7537                }
7538
7539                // reader
7540                synchronized (mPackages) {
7541                    mSettings.writeLPr();
7542                }
7543            }
7544
7545            if (removedPackage != null) {
7546                Bundle extras = new Bundle(1);
7547                extras.putInt(Intent.EXTRA_UID, removedAppId);
7548                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7549                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7550                        extras, null, null, removedUsers);
7551            }
7552            if (addedPackage != null) {
7553                Bundle extras = new Bundle(1);
7554                extras.putInt(Intent.EXTRA_UID, addedAppId);
7555                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7556                        extras, null, null, addedUsers);
7557            }
7558        }
7559
7560        private final String mRootDir;
7561        private final boolean mIsRom;
7562        private final boolean mIsPrivileged;
7563    }
7564
7565    /*
7566     * The old-style observer methods all just trampoline to the newer signature with
7567     * expanded install observer API.  The older API continues to work but does not
7568     * supply the additional details of the Observer2 API.
7569     */
7570
7571    /* Called when a downloaded package installation has been confirmed by the user */
7572    public void installPackage(
7573            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7574        installPackageEtc(packageURI, observer, null, flags, null);
7575    }
7576
7577    /* Called when a downloaded package installation has been confirmed by the user */
7578    @Override
7579    public void installPackage(
7580            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7581            final String installerPackageName) {
7582        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7583                installerPackageName, null, null, null);
7584    }
7585
7586    @Override
7587    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7588            int flags, String installerPackageName, Uri verificationURI,
7589            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7590        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7591                VerificationParams.NO_UID, manifestDigest);
7592        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7593                installerPackageName, verificationParams, encryptionParams);
7594    }
7595
7596    @Override
7597    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7598            IPackageInstallObserver observer, int flags, String installerPackageName,
7599            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7600        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7601                installerPackageName, verificationParams, encryptionParams);
7602    }
7603
7604    /*
7605     * And here are the "live" versions that take both observer arguments
7606     */
7607    public void installPackageEtc(
7608            final Uri packageURI, final IPackageInstallObserver observer,
7609            IPackageInstallObserver2 observer2, final int flags) {
7610        installPackageEtc(packageURI, observer, observer2, flags, null);
7611    }
7612
7613    public void installPackageEtc(
7614            final Uri packageURI, final IPackageInstallObserver observer,
7615            final IPackageInstallObserver2 observer2, final int flags,
7616            final String installerPackageName) {
7617        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7618                installerPackageName, null, null, null);
7619    }
7620
7621    @Override
7622    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7623            IPackageInstallObserver2 observer2,
7624            int flags, String installerPackageName, Uri verificationURI,
7625            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7626        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7627                VerificationParams.NO_UID, manifestDigest);
7628        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7629                installerPackageName, verificationParams, encryptionParams);
7630    }
7631
7632    /*
7633     * All of the installPackage...*() methods redirect to this one for the master implementation
7634     */
7635    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7636            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7637            int flags, String installerPackageName,
7638            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7639        if (observer == null && observer2 == null) {
7640            throw new IllegalArgumentException("No install observer supplied");
7641        }
7642        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7643                flags, installerPackageName, verificationParams, encryptionParams, null);
7644    }
7645
7646    @Override
7647    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7648            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7649            int flags, String installerPackageName,
7650            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7651            String packageAbiOverride) {
7652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7653                null);
7654
7655        final int uid = Binder.getCallingUid();
7656        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7657            try {
7658                if (observer != null) {
7659                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7660                }
7661                if (observer2 != null) {
7662                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7663                }
7664            } catch (RemoteException re) {
7665            }
7666            return;
7667        }
7668
7669        UserHandle user;
7670        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7671            user = UserHandle.ALL;
7672        } else {
7673            user = new UserHandle(UserHandle.getUserId(uid));
7674        }
7675
7676        final int filteredFlags;
7677
7678        if (uid == Process.SHELL_UID || uid == 0) {
7679            if (DEBUG_INSTALL) {
7680                Slog.v(TAG, "Install from ADB");
7681            }
7682            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7683        } else {
7684            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7685        }
7686
7687        verificationParams.setInstallerUid(uid);
7688
7689        final Message msg = mHandler.obtainMessage(INIT_COPY);
7690        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7691                installerPackageName, verificationParams, encryptionParams, user,
7692                packageAbiOverride);
7693        mHandler.sendMessage(msg);
7694    }
7695
7696    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7697        Bundle extras = new Bundle(1);
7698        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7699
7700        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7701                packageName, extras, null, null, new int[] {userId});
7702        try {
7703            IActivityManager am = ActivityManagerNative.getDefault();
7704            final boolean isSystem =
7705                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7706            if (isSystem && am.isUserRunning(userId, false)) {
7707                // The just-installed/enabled app is bundled on the system, so presumed
7708                // to be able to run automatically without needing an explicit launch.
7709                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7710                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7711                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7712                        .setPackage(packageName);
7713                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7714                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7715            }
7716        } catch (RemoteException e) {
7717            // shouldn't happen
7718            Slog.w(TAG, "Unable to bootstrap installed package", e);
7719        }
7720    }
7721
7722    @Override
7723    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7724            int userId) {
7725        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7726        PackageSetting pkgSetting;
7727        final int uid = Binder.getCallingUid();
7728        if (UserHandle.getUserId(uid) != userId) {
7729            mContext.enforceCallingOrSelfPermission(
7730                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7731                    "setApplicationBlockedSetting for user " + userId);
7732        }
7733
7734        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7735            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7736            return false;
7737        }
7738
7739        long callingId = Binder.clearCallingIdentity();
7740        try {
7741            boolean sendAdded = false;
7742            boolean sendRemoved = false;
7743            // writer
7744            synchronized (mPackages) {
7745                pkgSetting = mSettings.mPackages.get(packageName);
7746                if (pkgSetting == null) {
7747                    return false;
7748                }
7749                if (pkgSetting.getBlocked(userId) != blocked) {
7750                    pkgSetting.setBlocked(blocked, userId);
7751                    mSettings.writePackageRestrictionsLPr(userId);
7752                    if (blocked) {
7753                        sendRemoved = true;
7754                    } else {
7755                        sendAdded = true;
7756                    }
7757                }
7758            }
7759            if (sendAdded) {
7760                sendPackageAddedForUser(packageName, pkgSetting, userId);
7761                return true;
7762            }
7763            if (sendRemoved) {
7764                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7765                        "blocking pkg");
7766                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7767            }
7768        } finally {
7769            Binder.restoreCallingIdentity(callingId);
7770        }
7771        return false;
7772    }
7773
7774    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7775            int userId) {
7776        final PackageRemovedInfo info = new PackageRemovedInfo();
7777        info.removedPackage = packageName;
7778        info.removedUsers = new int[] {userId};
7779        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7780        info.sendBroadcast(false, false, false);
7781    }
7782
7783    /**
7784     * Returns true if application is not found or there was an error. Otherwise it returns
7785     * the blocked state of the package for the given user.
7786     */
7787    @Override
7788    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7789        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7790        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7791                "getApplicationBlocked for user " + userId);
7792        PackageSetting pkgSetting;
7793        long callingId = Binder.clearCallingIdentity();
7794        try {
7795            // writer
7796            synchronized (mPackages) {
7797                pkgSetting = mSettings.mPackages.get(packageName);
7798                if (pkgSetting == null) {
7799                    return true;
7800                }
7801                return pkgSetting.getBlocked(userId);
7802            }
7803        } finally {
7804            Binder.restoreCallingIdentity(callingId);
7805        }
7806    }
7807
7808    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7809            int flags) {
7810        // TODO: install stage!
7811        try {
7812            observer.packageInstalled(basePackageName, null,
7813                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7814        } catch (RemoteException ignored) {
7815        }
7816    }
7817
7818    /**
7819     * @hide
7820     */
7821    @Override
7822    public int installExistingPackageAsUser(String packageName, int userId) {
7823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7824                null);
7825        PackageSetting pkgSetting;
7826        final int uid = Binder.getCallingUid();
7827        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7828        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7829            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7830        }
7831
7832        long callingId = Binder.clearCallingIdentity();
7833        try {
7834            boolean sendAdded = false;
7835            Bundle extras = new Bundle(1);
7836
7837            // writer
7838            synchronized (mPackages) {
7839                pkgSetting = mSettings.mPackages.get(packageName);
7840                if (pkgSetting == null) {
7841                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7842                }
7843                if (!pkgSetting.getInstalled(userId)) {
7844                    pkgSetting.setInstalled(true, userId);
7845                    pkgSetting.setBlocked(false, userId);
7846                    mSettings.writePackageRestrictionsLPr(userId);
7847                    sendAdded = true;
7848                }
7849            }
7850
7851            if (sendAdded) {
7852                sendPackageAddedForUser(packageName, pkgSetting, userId);
7853            }
7854        } finally {
7855            Binder.restoreCallingIdentity(callingId);
7856        }
7857
7858        return PackageManager.INSTALL_SUCCEEDED;
7859    }
7860
7861    boolean isUserRestricted(int userId, String restrictionKey) {
7862        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7863        if (restrictions.getBoolean(restrictionKey, false)) {
7864            Log.w(TAG, "User is restricted: " + restrictionKey);
7865            return true;
7866        }
7867        return false;
7868    }
7869
7870    @Override
7871    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7872        mContext.enforceCallingOrSelfPermission(
7873                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7874                "Only package verification agents can verify applications");
7875
7876        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7877        final PackageVerificationResponse response = new PackageVerificationResponse(
7878                verificationCode, Binder.getCallingUid());
7879        msg.arg1 = id;
7880        msg.obj = response;
7881        mHandler.sendMessage(msg);
7882    }
7883
7884    @Override
7885    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7886            long millisecondsToDelay) {
7887        mContext.enforceCallingOrSelfPermission(
7888                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7889                "Only package verification agents can extend verification timeouts");
7890
7891        final PackageVerificationState state = mPendingVerification.get(id);
7892        final PackageVerificationResponse response = new PackageVerificationResponse(
7893                verificationCodeAtTimeout, Binder.getCallingUid());
7894
7895        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7896            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7897        }
7898        if (millisecondsToDelay < 0) {
7899            millisecondsToDelay = 0;
7900        }
7901        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7902                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7903            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7904        }
7905
7906        if ((state != null) && !state.timeoutExtended()) {
7907            state.extendTimeout();
7908
7909            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7910            msg.arg1 = id;
7911            msg.obj = response;
7912            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7913        }
7914    }
7915
7916    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7917            int verificationCode, UserHandle user) {
7918        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7919        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7920        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7921        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7922        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7923
7924        mContext.sendBroadcastAsUser(intent, user,
7925                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7926    }
7927
7928    private ComponentName matchComponentForVerifier(String packageName,
7929            List<ResolveInfo> receivers) {
7930        ActivityInfo targetReceiver = null;
7931
7932        final int NR = receivers.size();
7933        for (int i = 0; i < NR; i++) {
7934            final ResolveInfo info = receivers.get(i);
7935            if (info.activityInfo == null) {
7936                continue;
7937            }
7938
7939            if (packageName.equals(info.activityInfo.packageName)) {
7940                targetReceiver = info.activityInfo;
7941                break;
7942            }
7943        }
7944
7945        if (targetReceiver == null) {
7946            return null;
7947        }
7948
7949        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7950    }
7951
7952    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7953            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7954        if (pkgInfo.verifiers.length == 0) {
7955            return null;
7956        }
7957
7958        final int N = pkgInfo.verifiers.length;
7959        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7960        for (int i = 0; i < N; i++) {
7961            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7962
7963            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7964                    receivers);
7965            if (comp == null) {
7966                continue;
7967            }
7968
7969            final int verifierUid = getUidForVerifier(verifierInfo);
7970            if (verifierUid == -1) {
7971                continue;
7972            }
7973
7974            if (DEBUG_VERIFY) {
7975                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7976                        + " with the correct signature");
7977            }
7978            sufficientVerifiers.add(comp);
7979            verificationState.addSufficientVerifier(verifierUid);
7980        }
7981
7982        return sufficientVerifiers;
7983    }
7984
7985    private int getUidForVerifier(VerifierInfo verifierInfo) {
7986        synchronized (mPackages) {
7987            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7988            if (pkg == null) {
7989                return -1;
7990            } else if (pkg.mSignatures.length != 1) {
7991                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7992                        + " has more than one signature; ignoring");
7993                return -1;
7994            }
7995
7996            /*
7997             * If the public key of the package's signature does not match
7998             * our expected public key, then this is a different package and
7999             * we should skip.
8000             */
8001
8002            final byte[] expectedPublicKey;
8003            try {
8004                final Signature verifierSig = pkg.mSignatures[0];
8005                final PublicKey publicKey = verifierSig.getPublicKey();
8006                expectedPublicKey = publicKey.getEncoded();
8007            } catch (CertificateException e) {
8008                return -1;
8009            }
8010
8011            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8012
8013            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8014                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8015                        + " does not have the expected public key; ignoring");
8016                return -1;
8017            }
8018
8019            return pkg.applicationInfo.uid;
8020        }
8021    }
8022
8023    @Override
8024    public void finishPackageInstall(int token) {
8025        enforceSystemOrRoot("Only the system is allowed to finish installs");
8026
8027        if (DEBUG_INSTALL) {
8028            Slog.v(TAG, "BM finishing package install for " + token);
8029        }
8030
8031        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8032        mHandler.sendMessage(msg);
8033    }
8034
8035    /**
8036     * Get the verification agent timeout.
8037     *
8038     * @return verification timeout in milliseconds
8039     */
8040    private long getVerificationTimeout() {
8041        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8042                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8043                DEFAULT_VERIFICATION_TIMEOUT);
8044    }
8045
8046    /**
8047     * Get the default verification agent response code.
8048     *
8049     * @return default verification response code
8050     */
8051    private int getDefaultVerificationResponse() {
8052        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8053                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8054                DEFAULT_VERIFICATION_RESPONSE);
8055    }
8056
8057    /**
8058     * Check whether or not package verification has been enabled.
8059     *
8060     * @return true if verification should be performed
8061     */
8062    private boolean isVerificationEnabled(int flags) {
8063        if (!DEFAULT_VERIFY_ENABLE) {
8064            return false;
8065        }
8066
8067        // Check if installing from ADB
8068        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8069            // Do not run verification in a test harness environment
8070            if (ActivityManager.isRunningInTestHarness()) {
8071                return false;
8072            }
8073            // Check if the developer does not want package verification for ADB installs
8074            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8075                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8076                return false;
8077            }
8078        }
8079
8080        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8081                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8082    }
8083
8084    /**
8085     * Get the "allow unknown sources" setting.
8086     *
8087     * @return the current "allow unknown sources" setting
8088     */
8089    private int getUnknownSourcesSettings() {
8090        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8091                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8092                -1);
8093    }
8094
8095    @Override
8096    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8097        final int uid = Binder.getCallingUid();
8098        // writer
8099        synchronized (mPackages) {
8100            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8101            if (targetPackageSetting == null) {
8102                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8103            }
8104
8105            PackageSetting installerPackageSetting;
8106            if (installerPackageName != null) {
8107                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8108                if (installerPackageSetting == null) {
8109                    throw new IllegalArgumentException("Unknown installer package: "
8110                            + installerPackageName);
8111                }
8112            } else {
8113                installerPackageSetting = null;
8114            }
8115
8116            Signature[] callerSignature;
8117            Object obj = mSettings.getUserIdLPr(uid);
8118            if (obj != null) {
8119                if (obj instanceof SharedUserSetting) {
8120                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8121                } else if (obj instanceof PackageSetting) {
8122                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8123                } else {
8124                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8125                }
8126            } else {
8127                throw new SecurityException("Unknown calling uid " + uid);
8128            }
8129
8130            // Verify: can't set installerPackageName to a package that is
8131            // not signed with the same cert as the caller.
8132            if (installerPackageSetting != null) {
8133                if (compareSignatures(callerSignature,
8134                        installerPackageSetting.signatures.mSignatures)
8135                        != PackageManager.SIGNATURE_MATCH) {
8136                    throw new SecurityException(
8137                            "Caller does not have same cert as new installer package "
8138                            + installerPackageName);
8139                }
8140            }
8141
8142            // Verify: if target already has an installer package, it must
8143            // be signed with the same cert as the caller.
8144            if (targetPackageSetting.installerPackageName != null) {
8145                PackageSetting setting = mSettings.mPackages.get(
8146                        targetPackageSetting.installerPackageName);
8147                // If the currently set package isn't valid, then it's always
8148                // okay to change it.
8149                if (setting != null) {
8150                    if (compareSignatures(callerSignature,
8151                            setting.signatures.mSignatures)
8152                            != PackageManager.SIGNATURE_MATCH) {
8153                        throw new SecurityException(
8154                                "Caller does not have same cert as old installer package "
8155                                + targetPackageSetting.installerPackageName);
8156                    }
8157                }
8158            }
8159
8160            // Okay!
8161            targetPackageSetting.installerPackageName = installerPackageName;
8162            scheduleWriteSettingsLocked();
8163        }
8164    }
8165
8166    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8167        // Queue up an async operation since the package installation may take a little while.
8168        mHandler.post(new Runnable() {
8169            public void run() {
8170                mHandler.removeCallbacks(this);
8171                 // Result object to be returned
8172                PackageInstalledInfo res = new PackageInstalledInfo();
8173                res.returnCode = currentStatus;
8174                res.uid = -1;
8175                res.pkg = null;
8176                res.removedInfo = new PackageRemovedInfo();
8177                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8178                    args.doPreInstall(res.returnCode);
8179                    synchronized (mInstallLock) {
8180                        installPackageLI(args, true, res);
8181                    }
8182                    args.doPostInstall(res.returnCode, res.uid);
8183                }
8184
8185                // A restore should be performed at this point if (a) the install
8186                // succeeded, (b) the operation is not an update, and (c) the new
8187                // package has a backupAgent defined.
8188                final boolean update = res.removedInfo.removedPackage != null;
8189                boolean doRestore = (!update
8190                        && res.pkg != null
8191                        && res.pkg.applicationInfo.backupAgentName != null);
8192
8193                // Set up the post-install work request bookkeeping.  This will be used
8194                // and cleaned up by the post-install event handling regardless of whether
8195                // there's a restore pass performed.  Token values are >= 1.
8196                int token;
8197                if (mNextInstallToken < 0) mNextInstallToken = 1;
8198                token = mNextInstallToken++;
8199
8200                PostInstallData data = new PostInstallData(args, res);
8201                mRunningInstalls.put(token, data);
8202                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8203
8204                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8205                    // Pass responsibility to the Backup Manager.  It will perform a
8206                    // restore if appropriate, then pass responsibility back to the
8207                    // Package Manager to run the post-install observer callbacks
8208                    // and broadcasts.
8209                    IBackupManager bm = IBackupManager.Stub.asInterface(
8210                            ServiceManager.getService(Context.BACKUP_SERVICE));
8211                    if (bm != null) {
8212                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8213                                + " to BM for possible restore");
8214                        try {
8215                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8216                        } catch (RemoteException e) {
8217                            // can't happen; the backup manager is local
8218                        } catch (Exception e) {
8219                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8220                            doRestore = false;
8221                        }
8222                    } else {
8223                        Slog.e(TAG, "Backup Manager not found!");
8224                        doRestore = false;
8225                    }
8226                }
8227
8228                if (!doRestore) {
8229                    // No restore possible, or the Backup Manager was mysteriously not
8230                    // available -- just fire the post-install work request directly.
8231                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8232                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8233                    mHandler.sendMessage(msg);
8234                }
8235            }
8236        });
8237    }
8238
8239    private abstract class HandlerParams {
8240        private static final int MAX_RETRIES = 4;
8241
8242        /**
8243         * Number of times startCopy() has been attempted and had a non-fatal
8244         * error.
8245         */
8246        private int mRetries = 0;
8247
8248        /** User handle for the user requesting the information or installation. */
8249        private final UserHandle mUser;
8250
8251        HandlerParams(UserHandle user) {
8252            mUser = user;
8253        }
8254
8255        UserHandle getUser() {
8256            return mUser;
8257        }
8258
8259        final boolean startCopy() {
8260            boolean res;
8261            try {
8262                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8263
8264                if (++mRetries > MAX_RETRIES) {
8265                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8266                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8267                    handleServiceError();
8268                    return false;
8269                } else {
8270                    handleStartCopy();
8271                    res = true;
8272                }
8273            } catch (RemoteException e) {
8274                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8275                mHandler.sendEmptyMessage(MCS_RECONNECT);
8276                res = false;
8277            }
8278            handleReturnCode();
8279            return res;
8280        }
8281
8282        final void serviceError() {
8283            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8284            handleServiceError();
8285            handleReturnCode();
8286        }
8287
8288        abstract void handleStartCopy() throws RemoteException;
8289        abstract void handleServiceError();
8290        abstract void handleReturnCode();
8291    }
8292
8293    class MeasureParams extends HandlerParams {
8294        private final PackageStats mStats;
8295        private boolean mSuccess;
8296
8297        private final IPackageStatsObserver mObserver;
8298
8299        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8300            super(new UserHandle(stats.userHandle));
8301            mObserver = observer;
8302            mStats = stats;
8303        }
8304
8305        @Override
8306        public String toString() {
8307            return "MeasureParams{"
8308                + Integer.toHexString(System.identityHashCode(this))
8309                + " " + mStats.packageName + "}";
8310        }
8311
8312        @Override
8313        void handleStartCopy() throws RemoteException {
8314            synchronized (mInstallLock) {
8315                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8316            }
8317
8318            if (mSuccess) {
8319                final boolean mounted;
8320                if (Environment.isExternalStorageEmulated()) {
8321                    mounted = true;
8322                } else {
8323                    final String status = Environment.getExternalStorageState();
8324                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8325                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8326                }
8327
8328                if (mounted) {
8329                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8330
8331                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8332                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8333
8334                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8335                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8336
8337                    // Always subtract cache size, since it's a subdirectory
8338                    mStats.externalDataSize -= mStats.externalCacheSize;
8339
8340                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8341                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8342
8343                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8344                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8345                }
8346            }
8347        }
8348
8349        @Override
8350        void handleReturnCode() {
8351            if (mObserver != null) {
8352                try {
8353                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8354                } catch (RemoteException e) {
8355                    Slog.i(TAG, "Observer no longer exists.");
8356                }
8357            }
8358        }
8359
8360        @Override
8361        void handleServiceError() {
8362            Slog.e(TAG, "Could not measure application " + mStats.packageName
8363                            + " external storage");
8364        }
8365    }
8366
8367    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8368            throws RemoteException {
8369        long result = 0;
8370        for (File path : paths) {
8371            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8372        }
8373        return result;
8374    }
8375
8376    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8377        for (File path : paths) {
8378            try {
8379                mcs.clearDirectory(path.getAbsolutePath());
8380            } catch (RemoteException e) {
8381            }
8382        }
8383    }
8384
8385    class InstallParams extends HandlerParams {
8386        final IPackageInstallObserver observer;
8387        final IPackageInstallObserver2 observer2;
8388        int flags;
8389
8390        private final Uri mPackageURI;
8391        final String installerPackageName;
8392        final VerificationParams verificationParams;
8393        private InstallArgs mArgs;
8394        private int mRet;
8395        private File mTempPackage;
8396        final ContainerEncryptionParams encryptionParams;
8397        final String packageAbiOverride;
8398        final String packageInstructionSetOverride;
8399
8400        InstallParams(Uri packageURI,
8401                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8402                int flags, String installerPackageName, VerificationParams verificationParams,
8403                ContainerEncryptionParams encryptionParams, UserHandle user,
8404                String packageAbiOverride) {
8405            super(user);
8406            this.mPackageURI = packageURI;
8407            this.flags = flags;
8408            this.observer = observer;
8409            this.observer2 = observer2;
8410            this.installerPackageName = installerPackageName;
8411            this.verificationParams = verificationParams;
8412            this.encryptionParams = encryptionParams;
8413            this.packageAbiOverride = packageAbiOverride;
8414            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8415                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8416        }
8417
8418        @Override
8419        public String toString() {
8420            return "InstallParams{"
8421                + Integer.toHexString(System.identityHashCode(this))
8422                + " " + mPackageURI + "}";
8423        }
8424
8425        public ManifestDigest getManifestDigest() {
8426            if (verificationParams == null) {
8427                return null;
8428            }
8429            return verificationParams.getManifestDigest();
8430        }
8431
8432        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8433            String packageName = pkgLite.packageName;
8434            int installLocation = pkgLite.installLocation;
8435            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8436            // reader
8437            synchronized (mPackages) {
8438                PackageParser.Package pkg = mPackages.get(packageName);
8439                if (pkg != null) {
8440                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8441                        // Check for downgrading.
8442                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8443                            if (pkgLite.versionCode < pkg.mVersionCode) {
8444                                Slog.w(TAG, "Can't install update of " + packageName
8445                                        + " update version " + pkgLite.versionCode
8446                                        + " is older than installed version "
8447                                        + pkg.mVersionCode);
8448                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8449                            }
8450                        }
8451                        // Check for updated system application.
8452                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8453                            if (onSd) {
8454                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8455                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8456                            }
8457                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8458                        } else {
8459                            if (onSd) {
8460                                // Install flag overrides everything.
8461                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8462                            }
8463                            // If current upgrade specifies particular preference
8464                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8465                                // Application explicitly specified internal.
8466                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8467                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8468                                // App explictly prefers external. Let policy decide
8469                            } else {
8470                                // Prefer previous location
8471                                if (isExternal(pkg)) {
8472                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8473                                }
8474                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8475                            }
8476                        }
8477                    } else {
8478                        // Invalid install. Return error code
8479                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8480                    }
8481                }
8482            }
8483            // All the special cases have been taken care of.
8484            // Return result based on recommended install location.
8485            if (onSd) {
8486                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8487            }
8488            return pkgLite.recommendedInstallLocation;
8489        }
8490
8491        private long getMemoryLowThreshold() {
8492            final DeviceStorageMonitorInternal
8493                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8494            if (dsm == null) {
8495                return 0L;
8496            }
8497            return dsm.getMemoryLowThreshold();
8498        }
8499
8500        /*
8501         * Invoke remote method to get package information and install
8502         * location values. Override install location based on default
8503         * policy if needed and then create install arguments based
8504         * on the install location.
8505         */
8506        public void handleStartCopy() throws RemoteException {
8507            int ret = PackageManager.INSTALL_SUCCEEDED;
8508            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8509            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8510            PackageInfoLite pkgLite = null;
8511
8512            if (onInt && onSd) {
8513                // Check if both bits are set.
8514                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8515                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8516            } else {
8517                final long lowThreshold = getMemoryLowThreshold();
8518                if (lowThreshold == 0L) {
8519                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8520                }
8521
8522                try {
8523                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8524                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8525
8526                    final File packageFile;
8527                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8528                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8529                        if (mTempPackage != null) {
8530                            ParcelFileDescriptor out;
8531                            try {
8532                                out = ParcelFileDescriptor.open(mTempPackage,
8533                                        ParcelFileDescriptor.MODE_READ_WRITE);
8534                            } catch (FileNotFoundException e) {
8535                                out = null;
8536                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8537                            }
8538
8539                            // Make a temporary file for decryption.
8540                            ret = mContainerService
8541                                    .copyResource(mPackageURI, encryptionParams, out);
8542                            IoUtils.closeQuietly(out);
8543
8544                            packageFile = mTempPackage;
8545
8546                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8547                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8548                                            | FileUtils.S_IROTH,
8549                                    -1, -1);
8550                        } else {
8551                            packageFile = null;
8552                        }
8553                    } else {
8554                        packageFile = new File(mPackageURI.getPath());
8555                    }
8556
8557                    if (packageFile != null) {
8558                        // Remote call to find out default install location
8559                        final String packageFilePath = packageFile.getAbsolutePath();
8560                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8561                                lowThreshold, packageAbiOverride);
8562
8563                        /*
8564                         * If we have too little free space, try to free cache
8565                         * before giving up.
8566                         */
8567                        if (pkgLite.recommendedInstallLocation
8568                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8569                            final long size = mContainerService.calculateInstalledSize(
8570                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8571                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8572                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8573                                        flags, lowThreshold, packageAbiOverride);
8574                            }
8575                            /*
8576                             * The cache free must have deleted the file we
8577                             * downloaded to install.
8578                             *
8579                             * TODO: fix the "freeCache" call to not delete
8580                             *       the file we care about.
8581                             */
8582                            if (pkgLite.recommendedInstallLocation
8583                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8584                                pkgLite.recommendedInstallLocation
8585                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8586                            }
8587                        }
8588                    }
8589                } finally {
8590                    mContext.revokeUriPermission(mPackageURI,
8591                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8592                }
8593            }
8594
8595            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8596                int loc = pkgLite.recommendedInstallLocation;
8597                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8598                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8599                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8600                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8601                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8602                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8603                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8604                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8605                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8606                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8607                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8608                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8609                } else {
8610                    // Override with defaults if needed.
8611                    loc = installLocationPolicy(pkgLite, flags);
8612                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8613                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8614                    } else if (!onSd && !onInt) {
8615                        // Override install location with flags
8616                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8617                            // Set the flag to install on external media.
8618                            flags |= PackageManager.INSTALL_EXTERNAL;
8619                            flags &= ~PackageManager.INSTALL_INTERNAL;
8620                        } else {
8621                            // Make sure the flag for installing on external
8622                            // media is unset
8623                            flags |= PackageManager.INSTALL_INTERNAL;
8624                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8625                        }
8626                    }
8627                }
8628            }
8629
8630            final InstallArgs args = createInstallArgs(this);
8631            mArgs = args;
8632
8633            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8634                 /*
8635                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8636                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8637                 */
8638                int userIdentifier = getUser().getIdentifier();
8639                if (userIdentifier == UserHandle.USER_ALL
8640                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8641                    userIdentifier = UserHandle.USER_OWNER;
8642                }
8643
8644                /*
8645                 * Determine if we have any installed package verifiers. If we
8646                 * do, then we'll defer to them to verify the packages.
8647                 */
8648                final int requiredUid = mRequiredVerifierPackage == null ? -1
8649                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8650                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8651                    final Intent verification = new Intent(
8652                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8653                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8654                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8655
8656                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8657                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8658                            0 /* TODO: Which userId? */);
8659
8660                    if (DEBUG_VERIFY) {
8661                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8662                                + verification.toString() + " with " + pkgLite.verifiers.length
8663                                + " optional verifiers");
8664                    }
8665
8666                    final int verificationId = mPendingVerificationToken++;
8667
8668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8669
8670                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8671                            installerPackageName);
8672
8673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8674
8675                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8676                            pkgLite.packageName);
8677
8678                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8679                            pkgLite.versionCode);
8680
8681                    if (verificationParams != null) {
8682                        if (verificationParams.getVerificationURI() != null) {
8683                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8684                                 verificationParams.getVerificationURI());
8685                        }
8686                        if (verificationParams.getOriginatingURI() != null) {
8687                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8688                                  verificationParams.getOriginatingURI());
8689                        }
8690                        if (verificationParams.getReferrer() != null) {
8691                            verification.putExtra(Intent.EXTRA_REFERRER,
8692                                  verificationParams.getReferrer());
8693                        }
8694                        if (verificationParams.getOriginatingUid() >= 0) {
8695                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8696                                  verificationParams.getOriginatingUid());
8697                        }
8698                        if (verificationParams.getInstallerUid() >= 0) {
8699                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8700                                  verificationParams.getInstallerUid());
8701                        }
8702                    }
8703
8704                    final PackageVerificationState verificationState = new PackageVerificationState(
8705                            requiredUid, args);
8706
8707                    mPendingVerification.append(verificationId, verificationState);
8708
8709                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8710                            receivers, verificationState);
8711
8712                    /*
8713                     * If any sufficient verifiers were listed in the package
8714                     * manifest, attempt to ask them.
8715                     */
8716                    if (sufficientVerifiers != null) {
8717                        final int N = sufficientVerifiers.size();
8718                        if (N == 0) {
8719                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8720                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8721                        } else {
8722                            for (int i = 0; i < N; i++) {
8723                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8724
8725                                final Intent sufficientIntent = new Intent(verification);
8726                                sufficientIntent.setComponent(verifierComponent);
8727
8728                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8729                            }
8730                        }
8731                    }
8732
8733                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8734                            mRequiredVerifierPackage, receivers);
8735                    if (ret == PackageManager.INSTALL_SUCCEEDED
8736                            && mRequiredVerifierPackage != null) {
8737                        /*
8738                         * Send the intent to the required verification agent,
8739                         * but only start the verification timeout after the
8740                         * target BroadcastReceivers have run.
8741                         */
8742                        verification.setComponent(requiredVerifierComponent);
8743                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8744                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8745                                new BroadcastReceiver() {
8746                                    @Override
8747                                    public void onReceive(Context context, Intent intent) {
8748                                        final Message msg = mHandler
8749                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8750                                        msg.arg1 = verificationId;
8751                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8752                                    }
8753                                }, null, 0, null, null);
8754
8755                        /*
8756                         * We don't want the copy to proceed until verification
8757                         * succeeds, so null out this field.
8758                         */
8759                        mArgs = null;
8760                    }
8761                } else {
8762                    /*
8763                     * No package verification is enabled, so immediately start
8764                     * the remote call to initiate copy using temporary file.
8765                     */
8766                    ret = args.copyApk(mContainerService, true);
8767                }
8768            }
8769
8770            mRet = ret;
8771        }
8772
8773        @Override
8774        void handleReturnCode() {
8775            // If mArgs is null, then MCS couldn't be reached. When it
8776            // reconnects, it will try again to install. At that point, this
8777            // will succeed.
8778            if (mArgs != null) {
8779                processPendingInstall(mArgs, mRet);
8780
8781                if (mTempPackage != null) {
8782                    if (!mTempPackage.delete()) {
8783                        Slog.w(TAG, "Couldn't delete temporary file: " +
8784                                mTempPackage.getAbsolutePath());
8785                    }
8786                }
8787            }
8788        }
8789
8790        @Override
8791        void handleServiceError() {
8792            mArgs = createInstallArgs(this);
8793            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8794        }
8795
8796        public boolean isForwardLocked() {
8797            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8798        }
8799
8800        public Uri getPackageUri() {
8801            if (mTempPackage != null) {
8802                return Uri.fromFile(mTempPackage);
8803            } else {
8804                return mPackageURI;
8805            }
8806        }
8807    }
8808
8809    /*
8810     * Utility class used in movePackage api.
8811     * srcArgs and targetArgs are not set for invalid flags and make
8812     * sure to do null checks when invoking methods on them.
8813     * We probably want to return ErrorPrams for both failed installs
8814     * and moves.
8815     */
8816    class MoveParams extends HandlerParams {
8817        final IPackageMoveObserver observer;
8818        final int flags;
8819        final String packageName;
8820        final InstallArgs srcArgs;
8821        final InstallArgs targetArgs;
8822        int uid;
8823        int mRet;
8824
8825        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8826                String packageName, String dataDir, String instructionSet,
8827                int uid, UserHandle user) {
8828            super(user);
8829            this.srcArgs = srcArgs;
8830            this.observer = observer;
8831            this.flags = flags;
8832            this.packageName = packageName;
8833            this.uid = uid;
8834            if (srcArgs != null) {
8835                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8836                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8837            } else {
8838                targetArgs = null;
8839            }
8840        }
8841
8842        @Override
8843        public String toString() {
8844            return "MoveParams{"
8845                + Integer.toHexString(System.identityHashCode(this))
8846                + " " + packageName + "}";
8847        }
8848
8849        public void handleStartCopy() throws RemoteException {
8850            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8851            // Check for storage space on target medium
8852            if (!targetArgs.checkFreeStorage(mContainerService)) {
8853                Log.w(TAG, "Insufficient storage to install");
8854                return;
8855            }
8856
8857            mRet = srcArgs.doPreCopy();
8858            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8859                return;
8860            }
8861
8862            mRet = targetArgs.copyApk(mContainerService, false);
8863            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8864                srcArgs.doPostCopy(uid);
8865                return;
8866            }
8867
8868            mRet = srcArgs.doPostCopy(uid);
8869            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8870                return;
8871            }
8872
8873            mRet = targetArgs.doPreInstall(mRet);
8874            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8875                return;
8876            }
8877
8878            if (DEBUG_SD_INSTALL) {
8879                StringBuilder builder = new StringBuilder();
8880                if (srcArgs != null) {
8881                    builder.append("src: ");
8882                    builder.append(srcArgs.getCodePath());
8883                }
8884                if (targetArgs != null) {
8885                    builder.append(" target : ");
8886                    builder.append(targetArgs.getCodePath());
8887                }
8888                Log.i(TAG, builder.toString());
8889            }
8890        }
8891
8892        @Override
8893        void handleReturnCode() {
8894            targetArgs.doPostInstall(mRet, uid);
8895            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8896            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8897                currentStatus = PackageManager.MOVE_SUCCEEDED;
8898            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8899                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8900            }
8901            processPendingMove(this, currentStatus);
8902        }
8903
8904        @Override
8905        void handleServiceError() {
8906            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8907        }
8908    }
8909
8910    /**
8911     * Used during creation of InstallArgs
8912     *
8913     * @param flags package installation flags
8914     * @return true if should be installed on external storage
8915     */
8916    private static boolean installOnSd(int flags) {
8917        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8918            return false;
8919        }
8920        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8921            return true;
8922        }
8923        return false;
8924    }
8925
8926    /**
8927     * Used during creation of InstallArgs
8928     *
8929     * @param flags package installation flags
8930     * @return true if should be installed as forward locked
8931     */
8932    private static boolean installForwardLocked(int flags) {
8933        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8934    }
8935
8936    private InstallArgs createInstallArgs(InstallParams params) {
8937        if (installOnSd(params.flags) || params.isForwardLocked()) {
8938            return new AsecInstallArgs(params);
8939        } else {
8940            return new FileInstallArgs(params);
8941        }
8942    }
8943
8944    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8945            String nativeLibraryPath, String instructionSet) {
8946        final boolean isInAsec;
8947        if (installOnSd(flags)) {
8948            /* Apps on SD card are always in ASEC containers. */
8949            isInAsec = true;
8950        } else if (installForwardLocked(flags)
8951                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8952            /*
8953             * Forward-locked apps are only in ASEC containers if they're the
8954             * new style
8955             */
8956            isInAsec = true;
8957        } else {
8958            isInAsec = false;
8959        }
8960
8961        if (isInAsec) {
8962            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8963                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8964        } else {
8965            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8966                    instructionSet);
8967        }
8968    }
8969
8970    // Used by package mover
8971    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8972            String instructionSet) {
8973        if (installOnSd(flags) || installForwardLocked(flags)) {
8974            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8975                    + AsecInstallArgs.RES_FILE_NAME);
8976            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8977                    installForwardLocked(flags));
8978        } else {
8979            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8980        }
8981    }
8982
8983    static abstract class InstallArgs {
8984        final IPackageInstallObserver observer;
8985        final IPackageInstallObserver2 observer2;
8986        // Always refers to PackageManager flags only
8987        final int flags;
8988        final Uri packageURI;
8989        final String installerPackageName;
8990        final ManifestDigest manifestDigest;
8991        final UserHandle user;
8992        final String instructionSet;
8993        final String abiOverride;
8994
8995        InstallArgs(Uri packageURI,
8996                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8997                int flags, String installerPackageName, ManifestDigest manifestDigest,
8998                UserHandle user, String instructionSet, String abiOverride) {
8999            this.packageURI = packageURI;
9000            this.flags = flags;
9001            this.observer = observer;
9002            this.observer2 = observer2;
9003            this.installerPackageName = installerPackageName;
9004            this.manifestDigest = manifestDigest;
9005            this.user = user;
9006            this.instructionSet = instructionSet;
9007            this.abiOverride = abiOverride;
9008        }
9009
9010        abstract void createCopyFile();
9011        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9012        abstract int doPreInstall(int status);
9013        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9014
9015        abstract int doPostInstall(int status, int uid);
9016        abstract String getCodePath();
9017        abstract String getResourcePath();
9018        abstract String getNativeLibraryPath();
9019        // Need installer lock especially for dex file removal.
9020        abstract void cleanUpResourcesLI();
9021        abstract boolean doPostDeleteLI(boolean delete);
9022        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9023
9024        /**
9025         * Called before the source arguments are copied. This is used mostly
9026         * for MoveParams when it needs to read the source file to put it in the
9027         * destination.
9028         */
9029        int doPreCopy() {
9030            return PackageManager.INSTALL_SUCCEEDED;
9031        }
9032
9033        /**
9034         * Called after the source arguments are copied. This is used mostly for
9035         * MoveParams when it needs to read the source file to put it in the
9036         * destination.
9037         *
9038         * @return
9039         */
9040        int doPostCopy(int uid) {
9041            return PackageManager.INSTALL_SUCCEEDED;
9042        }
9043
9044        protected boolean isFwdLocked() {
9045            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9046        }
9047
9048        UserHandle getUser() {
9049            return user;
9050        }
9051    }
9052
9053    class FileInstallArgs extends InstallArgs {
9054        File installDir;
9055        String codeFileName;
9056        String resourceFileName;
9057        String libraryPath;
9058        boolean created = false;
9059
9060        FileInstallArgs(InstallParams params) {
9061            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9062                    params.installerPackageName, params.getManifestDigest(),
9063                    params.getUser(), params.packageInstructionSetOverride,
9064                    params.packageAbiOverride);
9065        }
9066
9067        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9068                String instructionSet) {
9069            super(null, null, null, 0, null, null, null, instructionSet, null);
9070            File codeFile = new File(fullCodePath);
9071            installDir = codeFile.getParentFile();
9072            codeFileName = fullCodePath;
9073            resourceFileName = fullResourcePath;
9074            libraryPath = nativeLibraryPath;
9075        }
9076
9077        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9078            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9079            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9080            String apkName = getNextCodePath(null, pkgName, ".apk");
9081            codeFileName = new File(installDir, apkName + ".apk").getPath();
9082            resourceFileName = getResourcePathFromCodePath();
9083            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9084        }
9085
9086        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9087            final long lowThreshold;
9088
9089            final DeviceStorageMonitorInternal
9090                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9091            if (dsm == null) {
9092                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9093                lowThreshold = 0L;
9094            } else {
9095                if (dsm.isMemoryLow()) {
9096                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9097                    return false;
9098                }
9099
9100                lowThreshold = dsm.getMemoryLowThreshold();
9101            }
9102
9103            try {
9104                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9105                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9106                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9107            } finally {
9108                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9109            }
9110        }
9111
9112        String getCodePath() {
9113            return codeFileName;
9114        }
9115
9116        void createCopyFile() {
9117            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9118            codeFileName = createTempPackageFile(installDir).getPath();
9119            resourceFileName = getResourcePathFromCodePath();
9120            libraryPath = getLibraryPathFromCodePath();
9121            created = true;
9122        }
9123
9124        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9125            if (temp) {
9126                // Generate temp file name
9127                createCopyFile();
9128            }
9129            // Get a ParcelFileDescriptor to write to the output file
9130            File codeFile = new File(codeFileName);
9131            if (!created) {
9132                try {
9133                    codeFile.createNewFile();
9134                    // Set permissions
9135                    if (!setPermissions()) {
9136                        // Failed setting permissions.
9137                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9138                    }
9139                } catch (IOException e) {
9140                   Slog.w(TAG, "Failed to create file " + codeFile);
9141                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9142                }
9143            }
9144            ParcelFileDescriptor out = null;
9145            try {
9146                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9147            } catch (FileNotFoundException e) {
9148                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9149                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9150            }
9151            // Copy the resource now
9152            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9153            try {
9154                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9155                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9156                ret = imcs.copyResource(packageURI, null, out);
9157            } finally {
9158                IoUtils.closeQuietly(out);
9159                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9160            }
9161
9162            if (isFwdLocked()) {
9163                final File destResourceFile = new File(getResourcePath());
9164
9165                // Copy the public files
9166                try {
9167                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9168                } catch (IOException e) {
9169                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9170                            + " forward-locked app.");
9171                    destResourceFile.delete();
9172                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9173                }
9174            }
9175
9176            final File nativeLibraryFile = new File(getNativeLibraryPath());
9177            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9178            if (nativeLibraryFile.exists()) {
9179                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9180                nativeLibraryFile.delete();
9181            }
9182
9183            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9184            String[] abiList = (abiOverride != null) ?
9185                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9186            try {
9187                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9188                        abiOverride == null &&
9189                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9190                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9191                }
9192
9193                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9194                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9195                    return copyRet;
9196                }
9197            } catch (IOException e) {
9198                Slog.e(TAG, "Copying native libraries failed", e);
9199                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9200            } finally {
9201                handle.close();
9202            }
9203
9204            return ret;
9205        }
9206
9207        int doPreInstall(int status) {
9208            if (status != PackageManager.INSTALL_SUCCEEDED) {
9209                cleanUp();
9210            }
9211            return status;
9212        }
9213
9214        boolean doRename(int status, final String pkgName, String oldCodePath) {
9215            if (status != PackageManager.INSTALL_SUCCEEDED) {
9216                cleanUp();
9217                return false;
9218            } else {
9219                final File oldCodeFile = new File(getCodePath());
9220                final File oldResourceFile = new File(getResourcePath());
9221                final File oldLibraryFile = new File(getNativeLibraryPath());
9222
9223                // Rename APK file based on packageName
9224                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9225                final File newCodeFile = new File(installDir, apkName + ".apk");
9226                if (!oldCodeFile.renameTo(newCodeFile)) {
9227                    return false;
9228                }
9229                codeFileName = newCodeFile.getPath();
9230
9231                // Rename public resource file if it's forward-locked.
9232                final File newResFile = new File(getResourcePathFromCodePath());
9233                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9234                    return false;
9235                }
9236                resourceFileName = newResFile.getPath();
9237
9238                // Rename library path
9239                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9240                if (newLibraryFile.exists()) {
9241                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9242                    newLibraryFile.delete();
9243                }
9244                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9245                    Slog.e(TAG, "Cannot rename native library directory "
9246                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9247                    return false;
9248                }
9249                libraryPath = newLibraryFile.getPath();
9250
9251                // Attempt to set permissions
9252                if (!setPermissions()) {
9253                    return false;
9254                }
9255
9256                if (!SELinux.restorecon(newCodeFile)) {
9257                    return false;
9258                }
9259
9260                return true;
9261            }
9262        }
9263
9264        int doPostInstall(int status, int uid) {
9265            if (status != PackageManager.INSTALL_SUCCEEDED) {
9266                cleanUp();
9267            }
9268            return status;
9269        }
9270
9271        String getResourcePath() {
9272            return resourceFileName;
9273        }
9274
9275        private String getResourcePathFromCodePath() {
9276            final String codePath = getCodePath();
9277            if (isFwdLocked()) {
9278                final StringBuilder sb = new StringBuilder();
9279
9280                sb.append(mAppInstallDir.getPath());
9281                sb.append('/');
9282                sb.append(getApkName(codePath));
9283                sb.append(".zip");
9284
9285                /*
9286                 * If our APK is a temporary file, mark the resource as a
9287                 * temporary file as well so it can be cleaned up after
9288                 * catastrophic failure.
9289                 */
9290                if (codePath.endsWith(".tmp")) {
9291                    sb.append(".tmp");
9292                }
9293
9294                return sb.toString();
9295            } else {
9296                return codePath;
9297            }
9298        }
9299
9300        private String getLibraryPathFromCodePath() {
9301            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9302        }
9303
9304        @Override
9305        String getNativeLibraryPath() {
9306            if (libraryPath == null) {
9307                libraryPath = getLibraryPathFromCodePath();
9308            }
9309            return libraryPath;
9310        }
9311
9312        private boolean cleanUp() {
9313            boolean ret = true;
9314            String sourceDir = getCodePath();
9315            String publicSourceDir = getResourcePath();
9316            if (sourceDir != null) {
9317                File sourceFile = new File(sourceDir);
9318                if (!sourceFile.exists()) {
9319                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9320                    ret = false;
9321                }
9322                // Delete application's code and resources
9323                sourceFile.delete();
9324            }
9325            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9326                final File publicSourceFile = new File(publicSourceDir);
9327                if (!publicSourceFile.exists()) {
9328                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9329                }
9330                if (publicSourceFile.exists()) {
9331                    publicSourceFile.delete();
9332                }
9333            }
9334
9335            if (libraryPath != null) {
9336                File nativeLibraryFile = new File(libraryPath);
9337                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9338                if (!nativeLibraryFile.delete()) {
9339                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9340                }
9341            }
9342
9343            return ret;
9344        }
9345
9346        void cleanUpResourcesLI() {
9347            String sourceDir = getCodePath();
9348            if (cleanUp()) {
9349                if (instructionSet == null) {
9350                    throw new IllegalStateException("instructionSet == null");
9351                }
9352                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9353                if (retCode < 0) {
9354                    Slog.w(TAG, "Couldn't remove dex file for package: "
9355                            +  " at location "
9356                            + sourceDir + ", retcode=" + retCode);
9357                    // we don't consider this to be a failure of the core package deletion
9358                }
9359            }
9360        }
9361
9362        private boolean setPermissions() {
9363            // TODO Do this in a more elegant way later on. for now just a hack
9364            if (!isFwdLocked()) {
9365                final int filePermissions =
9366                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9367                    |FileUtils.S_IROTH;
9368                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9369                if (retCode != 0) {
9370                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9371                            getCodePath()
9372                            + ". The return code was: " + retCode);
9373                    // TODO Define new internal error
9374                    return false;
9375                }
9376                return true;
9377            }
9378            return true;
9379        }
9380
9381        boolean doPostDeleteLI(boolean delete) {
9382            // XXX err, shouldn't we respect the delete flag?
9383            cleanUpResourcesLI();
9384            return true;
9385        }
9386    }
9387
9388    private boolean isAsecExternal(String cid) {
9389        final String asecPath = PackageHelper.getSdFilesystem(cid);
9390        return !asecPath.startsWith(mAsecInternalPath);
9391    }
9392
9393    /**
9394     * Extract the MountService "container ID" from the full code path of an
9395     * .apk.
9396     */
9397    static String cidFromCodePath(String fullCodePath) {
9398        int eidx = fullCodePath.lastIndexOf("/");
9399        String subStr1 = fullCodePath.substring(0, eidx);
9400        int sidx = subStr1.lastIndexOf("/");
9401        return subStr1.substring(sidx+1, eidx);
9402    }
9403
9404    class AsecInstallArgs extends InstallArgs {
9405        static final String RES_FILE_NAME = "pkg.apk";
9406        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9407
9408        String cid;
9409        String packagePath;
9410        String resourcePath;
9411        String libraryPath;
9412
9413        AsecInstallArgs(InstallParams params) {
9414            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9415                    params.installerPackageName, params.getManifestDigest(),
9416                    params.getUser(), params.packageInstructionSetOverride,
9417                    params.packageAbiOverride);
9418        }
9419
9420        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9421                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9422            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9423                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9424                    null, null, null, instructionSet, null);
9425            // Extract cid from fullCodePath
9426            int eidx = fullCodePath.lastIndexOf("/");
9427            String subStr1 = fullCodePath.substring(0, eidx);
9428            int sidx = subStr1.lastIndexOf("/");
9429            cid = subStr1.substring(sidx+1, eidx);
9430            setCachePath(subStr1);
9431        }
9432
9433        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9434            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9435                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9436                    null, null, null, instructionSet, null);
9437            this.cid = cid;
9438            setCachePath(PackageHelper.getSdDir(cid));
9439        }
9440
9441        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9442                boolean isExternal, boolean isForwardLocked) {
9443            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9444                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9445                    null, null, null, instructionSet, null);
9446            this.cid = cid;
9447        }
9448
9449        void createCopyFile() {
9450            cid = getTempContainerId();
9451        }
9452
9453        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9454            try {
9455                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9456                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9457                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9458            } finally {
9459                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9460            }
9461        }
9462
9463        private final boolean isExternal() {
9464            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9465        }
9466
9467        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9468            if (temp) {
9469                createCopyFile();
9470            } else {
9471                /*
9472                 * Pre-emptively destroy the container since it's destroyed if
9473                 * copying fails due to it existing anyway.
9474                 */
9475                PackageHelper.destroySdDir(cid);
9476            }
9477
9478            final String newCachePath;
9479            try {
9480                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9481                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9482                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9483                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9484                        abiOverride);
9485            } finally {
9486                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9487            }
9488
9489            if (newCachePath != null) {
9490                setCachePath(newCachePath);
9491                return PackageManager.INSTALL_SUCCEEDED;
9492            } else {
9493                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9494            }
9495        }
9496
9497        @Override
9498        String getCodePath() {
9499            return packagePath;
9500        }
9501
9502        @Override
9503        String getResourcePath() {
9504            return resourcePath;
9505        }
9506
9507        @Override
9508        String getNativeLibraryPath() {
9509            return libraryPath;
9510        }
9511
9512        int doPreInstall(int status) {
9513            if (status != PackageManager.INSTALL_SUCCEEDED) {
9514                // Destroy container
9515                PackageHelper.destroySdDir(cid);
9516            } else {
9517                boolean mounted = PackageHelper.isContainerMounted(cid);
9518                if (!mounted) {
9519                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9520                            Process.SYSTEM_UID);
9521                    if (newCachePath != null) {
9522                        setCachePath(newCachePath);
9523                    } else {
9524                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9525                    }
9526                }
9527            }
9528            return status;
9529        }
9530
9531        boolean doRename(int status, final String pkgName,
9532                String oldCodePath) {
9533            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9534            String newCachePath = null;
9535            if (PackageHelper.isContainerMounted(cid)) {
9536                // Unmount the container
9537                if (!PackageHelper.unMountSdDir(cid)) {
9538                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9539                    return false;
9540                }
9541            }
9542            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9543                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9544                        " which might be stale. Will try to clean up.");
9545                // Clean up the stale container and proceed to recreate.
9546                if (!PackageHelper.destroySdDir(newCacheId)) {
9547                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9548                    return false;
9549                }
9550                // Successfully cleaned up stale container. Try to rename again.
9551                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9552                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9553                            + " inspite of cleaning it up.");
9554                    return false;
9555                }
9556            }
9557            if (!PackageHelper.isContainerMounted(newCacheId)) {
9558                Slog.w(TAG, "Mounting container " + newCacheId);
9559                newCachePath = PackageHelper.mountSdDir(newCacheId,
9560                        getEncryptKey(), Process.SYSTEM_UID);
9561            } else {
9562                newCachePath = PackageHelper.getSdDir(newCacheId);
9563            }
9564            if (newCachePath == null) {
9565                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9566                return false;
9567            }
9568            Log.i(TAG, "Succesfully renamed " + cid +
9569                    " to " + newCacheId +
9570                    " at new path: " + newCachePath);
9571            cid = newCacheId;
9572            setCachePath(newCachePath);
9573            return true;
9574        }
9575
9576        private void setCachePath(String newCachePath) {
9577            File cachePath = new File(newCachePath);
9578            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9579            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9580
9581            if (isFwdLocked()) {
9582                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9583            } else {
9584                resourcePath = packagePath;
9585            }
9586        }
9587
9588        int doPostInstall(int status, int uid) {
9589            if (status != PackageManager.INSTALL_SUCCEEDED) {
9590                cleanUp();
9591            } else {
9592                final int groupOwner;
9593                final String protectedFile;
9594                if (isFwdLocked()) {
9595                    groupOwner = UserHandle.getSharedAppGid(uid);
9596                    protectedFile = RES_FILE_NAME;
9597                } else {
9598                    groupOwner = -1;
9599                    protectedFile = null;
9600                }
9601
9602                if (uid < Process.FIRST_APPLICATION_UID
9603                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9604                    Slog.e(TAG, "Failed to finalize " + cid);
9605                    PackageHelper.destroySdDir(cid);
9606                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9607                }
9608
9609                boolean mounted = PackageHelper.isContainerMounted(cid);
9610                if (!mounted) {
9611                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9612                }
9613            }
9614            return status;
9615        }
9616
9617        private void cleanUp() {
9618            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9619
9620            // Destroy secure container
9621            PackageHelper.destroySdDir(cid);
9622        }
9623
9624        void cleanUpResourcesLI() {
9625            String sourceFile = getCodePath();
9626            // Remove dex file
9627            if (instructionSet == null) {
9628                throw new IllegalStateException("instructionSet == null");
9629            }
9630            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9631            if (retCode < 0) {
9632                Slog.w(TAG, "Couldn't remove dex file for package: "
9633                        + " at location "
9634                        + sourceFile.toString() + ", retcode=" + retCode);
9635                // we don't consider this to be a failure of the core package deletion
9636            }
9637            cleanUp();
9638        }
9639
9640        boolean matchContainer(String app) {
9641            if (cid.startsWith(app)) {
9642                return true;
9643            }
9644            return false;
9645        }
9646
9647        String getPackageName() {
9648            return getAsecPackageName(cid);
9649        }
9650
9651        boolean doPostDeleteLI(boolean delete) {
9652            boolean ret = false;
9653            boolean mounted = PackageHelper.isContainerMounted(cid);
9654            if (mounted) {
9655                // Unmount first
9656                ret = PackageHelper.unMountSdDir(cid);
9657            }
9658            if (ret && delete) {
9659                cleanUpResourcesLI();
9660            }
9661            return ret;
9662        }
9663
9664        @Override
9665        int doPreCopy() {
9666            if (isFwdLocked()) {
9667                if (!PackageHelper.fixSdPermissions(cid,
9668                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9669                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9670                }
9671            }
9672
9673            return PackageManager.INSTALL_SUCCEEDED;
9674        }
9675
9676        @Override
9677        int doPostCopy(int uid) {
9678            if (isFwdLocked()) {
9679                if (uid < Process.FIRST_APPLICATION_UID
9680                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9681                                RES_FILE_NAME)) {
9682                    Slog.e(TAG, "Failed to finalize " + cid);
9683                    PackageHelper.destroySdDir(cid);
9684                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9685                }
9686            }
9687
9688            return PackageManager.INSTALL_SUCCEEDED;
9689        }
9690    };
9691
9692    static String getAsecPackageName(String packageCid) {
9693        int idx = packageCid.lastIndexOf("-");
9694        if (idx == -1) {
9695            return packageCid;
9696        }
9697        return packageCid.substring(0, idx);
9698    }
9699
9700    // Utility method used to create code paths based on package name and available index.
9701    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9702        String idxStr = "";
9703        int idx = 1;
9704        // Fall back to default value of idx=1 if prefix is not
9705        // part of oldCodePath
9706        if (oldCodePath != null) {
9707            String subStr = oldCodePath;
9708            // Drop the suffix right away
9709            if (subStr.endsWith(suffix)) {
9710                subStr = subStr.substring(0, subStr.length() - suffix.length());
9711            }
9712            // If oldCodePath already contains prefix find out the
9713            // ending index to either increment or decrement.
9714            int sidx = subStr.lastIndexOf(prefix);
9715            if (sidx != -1) {
9716                subStr = subStr.substring(sidx + prefix.length());
9717                if (subStr != null) {
9718                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9719                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9720                    }
9721                    try {
9722                        idx = Integer.parseInt(subStr);
9723                        if (idx <= 1) {
9724                            idx++;
9725                        } else {
9726                            idx--;
9727                        }
9728                    } catch(NumberFormatException e) {
9729                    }
9730                }
9731            }
9732        }
9733        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9734        return prefix + idxStr;
9735    }
9736
9737    // Utility method used to ignore ADD/REMOVE events
9738    // by directory observer.
9739    private static boolean ignoreCodePath(String fullPathStr) {
9740        String apkName = getApkName(fullPathStr);
9741        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9742        if (idx != -1 && ((idx+1) < apkName.length())) {
9743            // Make sure the package ends with a numeral
9744            String version = apkName.substring(idx+1);
9745            try {
9746                Integer.parseInt(version);
9747                return true;
9748            } catch (NumberFormatException e) {}
9749        }
9750        return false;
9751    }
9752
9753    // Utility method that returns the relative package path with respect
9754    // to the installation directory. Like say for /data/data/com.test-1.apk
9755    // string com.test-1 is returned.
9756    static String getApkName(String codePath) {
9757        if (codePath == null) {
9758            return null;
9759        }
9760        int sidx = codePath.lastIndexOf("/");
9761        int eidx = codePath.lastIndexOf(".");
9762        if (eidx == -1) {
9763            eidx = codePath.length();
9764        } else if (eidx == 0) {
9765            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9766            return null;
9767        }
9768        return codePath.substring(sidx+1, eidx);
9769    }
9770
9771    class PackageInstalledInfo {
9772        String name;
9773        int uid;
9774        // The set of users that originally had this package installed.
9775        int[] origUsers;
9776        // The set of users that now have this package installed.
9777        int[] newUsers;
9778        PackageParser.Package pkg;
9779        int returnCode;
9780        PackageRemovedInfo removedInfo;
9781
9782        // In some error cases we want to convey more info back to the observer
9783        String origPackage;
9784        String origPermission;
9785    }
9786
9787    /*
9788     * Install a non-existing package.
9789     */
9790    private void installNewPackageLI(PackageParser.Package pkg,
9791            int parseFlags, int scanMode, UserHandle user,
9792            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9793        // Remember this for later, in case we need to rollback this install
9794        String pkgName = pkg.packageName;
9795
9796        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9797        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9798        synchronized(mPackages) {
9799            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9800                // A package with the same name is already installed, though
9801                // it has been renamed to an older name.  The package we
9802                // are trying to install should be installed as an update to
9803                // the existing one, but that has not been requested, so bail.
9804                Slog.w(TAG, "Attempt to re-install " + pkgName
9805                        + " without first uninstalling package running as "
9806                        + mSettings.mRenamedPackages.get(pkgName));
9807                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9808                return;
9809            }
9810            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9811                // Don't allow installation over an existing package with the same name.
9812                Slog.w(TAG, "Attempt to re-install " + pkgName
9813                        + " without first uninstalling.");
9814                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9815                return;
9816            }
9817        }
9818        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9819        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9820                System.currentTimeMillis(), user, abiOverride);
9821        if (newPackage == null) {
9822            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9823            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9824                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9825            }
9826        } else {
9827            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9828            // delete the partially installed application. the data directory will have to be
9829            // restored if it was already existing
9830            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9831                // remove package from internal structures.  Note that we want deletePackageX to
9832                // delete the package data and cache directories that it created in
9833                // scanPackageLocked, unless those directories existed before we even tried to
9834                // install.
9835                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9836                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9837                                res.removedInfo, true);
9838            }
9839        }
9840    }
9841
9842    private void replacePackageLI(PackageParser.Package pkg,
9843            int parseFlags, int scanMode, UserHandle user,
9844            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9845
9846        PackageParser.Package oldPackage;
9847        String pkgName = pkg.packageName;
9848        int[] allUsers;
9849        boolean[] perUserInstalled;
9850
9851        // First find the old package info and check signatures
9852        synchronized(mPackages) {
9853            oldPackage = mPackages.get(pkgName);
9854            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9855            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9856                    != PackageManager.SIGNATURE_MATCH) {
9857                Slog.w(TAG, "New package has a different signature: " + pkgName);
9858                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9859                return;
9860            }
9861
9862            // In case of rollback, remember per-user/profile install state
9863            PackageSetting ps = mSettings.mPackages.get(pkgName);
9864            allUsers = sUserManager.getUserIds();
9865            perUserInstalled = new boolean[allUsers.length];
9866            for (int i = 0; i < allUsers.length; i++) {
9867                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9868            }
9869        }
9870        boolean sysPkg = (isSystemApp(oldPackage));
9871        if (sysPkg) {
9872            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9873                    user, allUsers, perUserInstalled, installerPackageName, res,
9874                    abiOverride);
9875        } else {
9876            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9877                    user, allUsers, perUserInstalled, installerPackageName, res,
9878                    abiOverride);
9879        }
9880    }
9881
9882    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9883            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9884            int[] allUsers, boolean[] perUserInstalled,
9885            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9886        PackageParser.Package newPackage = null;
9887        String pkgName = deletedPackage.packageName;
9888        boolean deletedPkg = true;
9889        boolean updatedSettings = false;
9890
9891        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9892                + deletedPackage);
9893        long origUpdateTime;
9894        if (pkg.mExtras != null) {
9895            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9896        } else {
9897            origUpdateTime = 0;
9898        }
9899
9900        // First delete the existing package while retaining the data directory
9901        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9902                res.removedInfo, true)) {
9903            // If the existing package wasn't successfully deleted
9904            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9905            deletedPkg = false;
9906        } else {
9907            // Successfully deleted the old package. Now proceed with re-installation
9908            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9909            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9910                    System.currentTimeMillis(), user, abiOverride);
9911            if (newPackage == null) {
9912                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9913                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9914                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9915                }
9916            } else {
9917                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9918                updatedSettings = true;
9919            }
9920        }
9921
9922        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9923            // remove package from internal structures.  Note that we want deletePackageX to
9924            // delete the package data and cache directories that it created in
9925            // scanPackageLocked, unless those directories existed before we even tried to
9926            // install.
9927            if(updatedSettings) {
9928                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9929                deletePackageLI(
9930                        pkgName, null, true, allUsers, perUserInstalled,
9931                        PackageManager.DELETE_KEEP_DATA,
9932                                res.removedInfo, true);
9933            }
9934            // Since we failed to install the new package we need to restore the old
9935            // package that we deleted.
9936            if (deletedPkg) {
9937                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9938                File restoreFile = new File(deletedPackage.codePath);
9939                // Parse old package
9940                boolean oldOnSd = isExternal(deletedPackage);
9941                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9942                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9943                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9944                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9945                        | SCAN_UPDATE_TIME;
9946                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9947                        origUpdateTime, null, null) == null) {
9948                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9949                    return;
9950                }
9951                // Restore of old package succeeded. Update permissions.
9952                // writer
9953                synchronized (mPackages) {
9954                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9955                            UPDATE_PERMISSIONS_ALL);
9956                    // can downgrade to reader
9957                    mSettings.writeLPr();
9958                }
9959                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9960            }
9961        }
9962    }
9963
9964    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9965            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9966            int[] allUsers, boolean[] perUserInstalled,
9967            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9968        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9969                + ", old=" + deletedPackage);
9970        PackageParser.Package newPackage = null;
9971        boolean updatedSettings = false;
9972        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9973                PackageParser.PARSE_IS_SYSTEM;
9974        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9975            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9976        }
9977        String packageName = deletedPackage.packageName;
9978        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9979        if (packageName == null) {
9980            Slog.w(TAG, "Attempt to delete null packageName.");
9981            return;
9982        }
9983        PackageParser.Package oldPkg;
9984        PackageSetting oldPkgSetting;
9985        // reader
9986        synchronized (mPackages) {
9987            oldPkg = mPackages.get(packageName);
9988            oldPkgSetting = mSettings.mPackages.get(packageName);
9989            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9990                    (oldPkgSetting == null)) {
9991                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9992                return;
9993            }
9994        }
9995
9996        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9997
9998        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9999        res.removedInfo.removedPackage = packageName;
10000        // Remove existing system package
10001        removePackageLI(oldPkgSetting, true);
10002        // writer
10003        synchronized (mPackages) {
10004            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10005                // We didn't need to disable the .apk as a current system package,
10006                // which means we are replacing another update that is already
10007                // installed.  We need to make sure to delete the older one's .apk.
10008                res.removedInfo.args = createInstallArgs(0,
10009                        deletedPackage.applicationInfo.sourceDir,
10010                        deletedPackage.applicationInfo.publicSourceDir,
10011                        deletedPackage.applicationInfo.nativeLibraryDir,
10012                        getAppInstructionSet(deletedPackage.applicationInfo));
10013            } else {
10014                res.removedInfo.args = null;
10015            }
10016        }
10017
10018        // Successfully disabled the old package. Now proceed with re-installation
10019        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10020        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10021        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10022        if (newPackage == null) {
10023            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10024            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10025                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10026            }
10027        } else {
10028            if (newPackage.mExtras != null) {
10029                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10030                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10031                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10032
10033                // is the update attempting to change shared user? that isn't going to work...
10034                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10035                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10036                            + " to " + newPkgSetting.sharedUser);
10037                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10038                    updatedSettings = true;
10039                }
10040            }
10041
10042            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10043                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10044                updatedSettings = true;
10045            }
10046        }
10047
10048        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10049            // Re installation failed. Restore old information
10050            // Remove new pkg information
10051            if (newPackage != null) {
10052                removeInstalledPackageLI(newPackage, true);
10053            }
10054            // Add back the old system package
10055            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10056            // Restore the old system information in Settings
10057            synchronized(mPackages) {
10058                if (updatedSettings) {
10059                    mSettings.enableSystemPackageLPw(packageName);
10060                    mSettings.setInstallerPackageName(packageName,
10061                            oldPkgSetting.installerPackageName);
10062                }
10063                mSettings.writeLPr();
10064            }
10065        }
10066    }
10067
10068    // Utility method used to move dex files during install.
10069    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10070        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10071            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10072            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10073                                             instructionSet);
10074            if (retCode != 0) {
10075                /*
10076                 * Programs may be lazily run through dexopt, so the
10077                 * source may not exist. However, something seems to
10078                 * have gone wrong, so note that dexopt needs to be
10079                 * run again and remove the source file. In addition,
10080                 * remove the target to make sure there isn't a stale
10081                 * file from a previous version of the package.
10082                 */
10083                newPackage.mDexOptNeeded = true;
10084                mInstaller.rmdex(oldCodePath, instructionSet);
10085                mInstaller.rmdex(newPackage.codePath, instructionSet);
10086            }
10087        }
10088        return PackageManager.INSTALL_SUCCEEDED;
10089    }
10090
10091    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10092            int[] allUsers, boolean[] perUserInstalled,
10093            PackageInstalledInfo res) {
10094        String pkgName = newPackage.packageName;
10095        synchronized (mPackages) {
10096            //write settings. the installStatus will be incomplete at this stage.
10097            //note that the new package setting would have already been
10098            //added to mPackages. It hasn't been persisted yet.
10099            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10100            mSettings.writeLPr();
10101        }
10102
10103        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10104
10105        synchronized (mPackages) {
10106            updatePermissionsLPw(newPackage.packageName, newPackage,
10107                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10108                            ? UPDATE_PERMISSIONS_ALL : 0));
10109            // For system-bundled packages, we assume that installing an upgraded version
10110            // of the package implies that the user actually wants to run that new code,
10111            // so we enable the package.
10112            if (isSystemApp(newPackage)) {
10113                // NB: implicit assumption that system package upgrades apply to all users
10114                if (DEBUG_INSTALL) {
10115                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10116                }
10117                PackageSetting ps = mSettings.mPackages.get(pkgName);
10118                if (ps != null) {
10119                    if (res.origUsers != null) {
10120                        for (int userHandle : res.origUsers) {
10121                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10122                                    userHandle, installerPackageName);
10123                        }
10124                    }
10125                    // Also convey the prior install/uninstall state
10126                    if (allUsers != null && perUserInstalled != null) {
10127                        for (int i = 0; i < allUsers.length; i++) {
10128                            if (DEBUG_INSTALL) {
10129                                Slog.d(TAG, "    user " + allUsers[i]
10130                                        + " => " + perUserInstalled[i]);
10131                            }
10132                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10133                        }
10134                        // these install state changes will be persisted in the
10135                        // upcoming call to mSettings.writeLPr().
10136                    }
10137                }
10138            }
10139            res.name = pkgName;
10140            res.uid = newPackage.applicationInfo.uid;
10141            res.pkg = newPackage;
10142            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10143            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10144            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10145            //to update install status
10146            mSettings.writeLPr();
10147        }
10148    }
10149
10150    private void installPackageLI(InstallArgs args,
10151            boolean newInstall, PackageInstalledInfo res) {
10152        int pFlags = args.flags;
10153        String installerPackageName = args.installerPackageName;
10154        File tmpPackageFile = new File(args.getCodePath());
10155        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10156        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10157        boolean replace = false;
10158        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10159                | (newInstall ? SCAN_NEW_INSTALL : 0);
10160        // Result object to be returned
10161        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10162
10163        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10164        // Retrieve PackageSettings and parse package
10165        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10166                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10167                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10168        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10169        pp.setSeparateProcesses(mSeparateProcesses);
10170
10171        final PackageParser.Package pkg;
10172        try {
10173            pkg = pp.parseMonolithicPackage(tmpPackageFile, mMetrics,
10174                parseFlags);
10175        } catch (PackageParserException e) {
10176            res.returnCode = e.error;
10177            return;
10178        }
10179
10180        String pkgName = res.name = pkg.packageName;
10181        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10182            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10183                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10184                return;
10185            }
10186        }
10187
10188        try {
10189            pp.collectCertificates(pkg, parseFlags);
10190        } catch (PackageParserException e) {
10191            res.returnCode = e.error;
10192            return;
10193        }
10194
10195        /* If the installer passed in a manifest digest, compare it now. */
10196        if (args.manifestDigest != null) {
10197            if (DEBUG_INSTALL) {
10198                final String parsedManifest = pkg.manifestDigest == null ? "null"
10199                        : pkg.manifestDigest.toString();
10200                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10201                        + parsedManifest);
10202            }
10203
10204            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10205                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10206                return;
10207            }
10208        } else if (DEBUG_INSTALL) {
10209            final String parsedManifest = pkg.manifestDigest == null
10210                    ? "null" : pkg.manifestDigest.toString();
10211            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10212        }
10213
10214        // Get rid of all references to package scan path via parser.
10215        pp = null;
10216        String oldCodePath = null;
10217        boolean systemApp = false;
10218        synchronized (mPackages) {
10219            // Check whether the newly-scanned package wants to define an already-defined perm
10220            int N = pkg.permissions.size();
10221            for (int i = N-1; i >= 0; i--) {
10222                PackageParser.Permission perm = pkg.permissions.get(i);
10223                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10224                if (bp != null) {
10225                    // If the defining package is signed with our cert, it's okay.  This
10226                    // also includes the "updating the same package" case, of course.
10227                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10228                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10229                        // If the owning package is the system itself, we log but allow
10230                        // install to proceed; we fail the install on all other permission
10231                        // redefinitions.
10232                        if (!bp.sourcePackage.equals("android")) {
10233                            Slog.w(TAG, "Package " + pkg.packageName
10234                                    + " attempting to redeclare permission " + perm.info.name
10235                                    + " already owned by " + bp.sourcePackage);
10236                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10237                            res.origPermission = perm.info.name;
10238                            res.origPackage = bp.sourcePackage;
10239                            return;
10240                        } else {
10241                            Slog.w(TAG, "Package " + pkg.packageName
10242                                    + " attempting to redeclare system permission "
10243                                    + perm.info.name + "; ignoring new declaration");
10244                            pkg.permissions.remove(i);
10245                        }
10246                    }
10247                }
10248            }
10249
10250            // Check if installing already existing package
10251            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10252                String oldName = mSettings.mRenamedPackages.get(pkgName);
10253                if (pkg.mOriginalPackages != null
10254                        && pkg.mOriginalPackages.contains(oldName)
10255                        && mPackages.containsKey(oldName)) {
10256                    // This package is derived from an original package,
10257                    // and this device has been updating from that original
10258                    // name.  We must continue using the original name, so
10259                    // rename the new package here.
10260                    pkg.setPackageName(oldName);
10261                    pkgName = pkg.packageName;
10262                    replace = true;
10263                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10264                            + oldName + " pkgName=" + pkgName);
10265                } else if (mPackages.containsKey(pkgName)) {
10266                    // This package, under its official name, already exists
10267                    // on the device; we should replace it.
10268                    replace = true;
10269                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10270                }
10271            }
10272            PackageSetting ps = mSettings.mPackages.get(pkgName);
10273            if (ps != null) {
10274                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10275                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10276                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10277                    systemApp = (ps.pkg.applicationInfo.flags &
10278                            ApplicationInfo.FLAG_SYSTEM) != 0;
10279                }
10280                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10281            }
10282        }
10283
10284        if (systemApp && onSd) {
10285            // Disable updates to system apps on sdcard
10286            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10287            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10288            return;
10289        }
10290
10291        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10292            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10293            return;
10294        }
10295        // Set application objects path explicitly after the rename
10296        pkg.codePath = args.getCodePath();
10297        pkg.applicationInfo.sourceDir = args.getCodePath();
10298        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10299        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10300        if (replace) {
10301            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10302                    installerPackageName, res, args.abiOverride);
10303        } else {
10304            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10305                    installerPackageName, res, args.abiOverride);
10306        }
10307        synchronized (mPackages) {
10308            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10309            if (ps != null) {
10310                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10311            }
10312        }
10313    }
10314
10315    private static boolean isForwardLocked(PackageParser.Package pkg) {
10316        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10317    }
10318
10319
10320    private boolean isForwardLocked(PackageSetting ps) {
10321        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10322    }
10323
10324    private static boolean isExternal(PackageParser.Package pkg) {
10325        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10326    }
10327
10328    private static boolean isExternal(PackageSetting ps) {
10329        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10330    }
10331
10332    private static boolean isSystemApp(PackageParser.Package pkg) {
10333        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10334    }
10335
10336    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10337        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10338    }
10339
10340    private static boolean isSystemApp(ApplicationInfo info) {
10341        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10342    }
10343
10344    private static boolean isSystemApp(PackageSetting ps) {
10345        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10346    }
10347
10348    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10349        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10350    }
10351
10352    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10353        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10354    }
10355
10356    private int packageFlagsToInstallFlags(PackageSetting ps) {
10357        int installFlags = 0;
10358        if (isExternal(ps)) {
10359            installFlags |= PackageManager.INSTALL_EXTERNAL;
10360        }
10361        if (isForwardLocked(ps)) {
10362            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10363        }
10364        return installFlags;
10365    }
10366
10367    private void deleteTempPackageFiles() {
10368        final FilenameFilter filter = new FilenameFilter() {
10369            public boolean accept(File dir, String name) {
10370                return name.startsWith("vmdl") && name.endsWith(".tmp");
10371            }
10372        };
10373        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10374        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10375    }
10376
10377    private static final void deleteTempPackageFilesInDirectory(File directory,
10378            FilenameFilter filter) {
10379        final String[] tmpFilesList = directory.list(filter);
10380        if (tmpFilesList == null) {
10381            return;
10382        }
10383        for (int i = 0; i < tmpFilesList.length; i++) {
10384            final File tmpFile = new File(directory, tmpFilesList[i]);
10385            tmpFile.delete();
10386        }
10387    }
10388
10389    private File createTempPackageFile(File installDir) {
10390        File tmpPackageFile;
10391        try {
10392            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10393        } catch (IOException e) {
10394            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10395            return null;
10396        }
10397        try {
10398            FileUtils.setPermissions(
10399                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10400                    -1, -1);
10401            if (!SELinux.restorecon(tmpPackageFile)) {
10402                return null;
10403            }
10404        } catch (IOException e) {
10405            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10406            return null;
10407        }
10408        return tmpPackageFile;
10409    }
10410
10411    @Override
10412    public void deletePackageAsUser(final String packageName,
10413                                    final IPackageDeleteObserver observer,
10414                                    final int userId, final int flags) {
10415        mContext.enforceCallingOrSelfPermission(
10416                android.Manifest.permission.DELETE_PACKAGES, null);
10417        final int uid = Binder.getCallingUid();
10418        if (UserHandle.getUserId(uid) != userId) {
10419            mContext.enforceCallingPermission(
10420                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10421                    "deletePackage for user " + userId);
10422        }
10423        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10424            try {
10425                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10426            } catch (RemoteException re) {
10427            }
10428            return;
10429        }
10430
10431        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10432        // Queue up an async operation since the package deletion may take a little while.
10433        mHandler.post(new Runnable() {
10434            public void run() {
10435                mHandler.removeCallbacks(this);
10436                final int returnCode = deletePackageX(packageName, userId, flags);
10437                if (observer != null) {
10438                    try {
10439                        observer.packageDeleted(packageName, returnCode);
10440                    } catch (RemoteException e) {
10441                        Log.i(TAG, "Observer no longer exists.");
10442                    } //end catch
10443                } //end if
10444            } //end run
10445        });
10446    }
10447
10448    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10449        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10450                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10451        try {
10452            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10453                    || dpm.isDeviceOwner(packageName))) {
10454                return true;
10455            }
10456        } catch (RemoteException e) {
10457        }
10458        return false;
10459    }
10460
10461    /**
10462     *  This method is an internal method that could be get invoked either
10463     *  to delete an installed package or to clean up a failed installation.
10464     *  After deleting an installed package, a broadcast is sent to notify any
10465     *  listeners that the package has been installed. For cleaning up a failed
10466     *  installation, the broadcast is not necessary since the package's
10467     *  installation wouldn't have sent the initial broadcast either
10468     *  The key steps in deleting a package are
10469     *  deleting the package information in internal structures like mPackages,
10470     *  deleting the packages base directories through installd
10471     *  updating mSettings to reflect current status
10472     *  persisting settings for later use
10473     *  sending a broadcast if necessary
10474     */
10475    private int deletePackageX(String packageName, int userId, int flags) {
10476        final PackageRemovedInfo info = new PackageRemovedInfo();
10477        final boolean res;
10478
10479        if (isPackageDeviceAdmin(packageName, userId)) {
10480            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10481            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10482        }
10483
10484        boolean removedForAllUsers = false;
10485        boolean systemUpdate = false;
10486
10487        // for the uninstall-updates case and restricted profiles, remember the per-
10488        // userhandle installed state
10489        int[] allUsers;
10490        boolean[] perUserInstalled;
10491        synchronized (mPackages) {
10492            PackageSetting ps = mSettings.mPackages.get(packageName);
10493            allUsers = sUserManager.getUserIds();
10494            perUserInstalled = new boolean[allUsers.length];
10495            for (int i = 0; i < allUsers.length; i++) {
10496                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10497            }
10498        }
10499
10500        synchronized (mInstallLock) {
10501            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10502            res = deletePackageLI(packageName,
10503                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10504                            ? UserHandle.ALL : new UserHandle(userId),
10505                    true, allUsers, perUserInstalled,
10506                    flags | REMOVE_CHATTY, info, true);
10507            systemUpdate = info.isRemovedPackageSystemUpdate;
10508            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10509                removedForAllUsers = true;
10510            }
10511            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10512                    + " removedForAllUsers=" + removedForAllUsers);
10513        }
10514
10515        if (res) {
10516            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10517
10518            // If the removed package was a system update, the old system package
10519            // was re-enabled; we need to broadcast this information
10520            if (systemUpdate) {
10521                Bundle extras = new Bundle(1);
10522                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10523                        ? info.removedAppId : info.uid);
10524                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10525
10526                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10527                        extras, null, null, null);
10528                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10529                        extras, null, null, null);
10530                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10531                        null, packageName, null, null);
10532            }
10533        }
10534        // Force a gc here.
10535        Runtime.getRuntime().gc();
10536        // Delete the resources here after sending the broadcast to let
10537        // other processes clean up before deleting resources.
10538        if (info.args != null) {
10539            synchronized (mInstallLock) {
10540                info.args.doPostDeleteLI(true);
10541            }
10542        }
10543
10544        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10545    }
10546
10547    static class PackageRemovedInfo {
10548        String removedPackage;
10549        int uid = -1;
10550        int removedAppId = -1;
10551        int[] removedUsers = null;
10552        boolean isRemovedPackageSystemUpdate = false;
10553        // Clean up resources deleted packages.
10554        InstallArgs args = null;
10555
10556        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10557            Bundle extras = new Bundle(1);
10558            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10559            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10560            if (replacing) {
10561                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10562            }
10563            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10564            if (removedPackage != null) {
10565                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10566                        extras, null, null, removedUsers);
10567                if (fullRemove && !replacing) {
10568                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10569                            extras, null, null, removedUsers);
10570                }
10571            }
10572            if (removedAppId >= 0) {
10573                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10574                        removedUsers);
10575            }
10576        }
10577    }
10578
10579    /*
10580     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10581     * flag is not set, the data directory is removed as well.
10582     * make sure this flag is set for partially installed apps. If not its meaningless to
10583     * delete a partially installed application.
10584     */
10585    private void removePackageDataLI(PackageSetting ps,
10586            int[] allUserHandles, boolean[] perUserInstalled,
10587            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10588        String packageName = ps.name;
10589        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10590        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10591        // Retrieve object to delete permissions for shared user later on
10592        final PackageSetting deletedPs;
10593        // reader
10594        synchronized (mPackages) {
10595            deletedPs = mSettings.mPackages.get(packageName);
10596            if (outInfo != null) {
10597                outInfo.removedPackage = packageName;
10598                outInfo.removedUsers = deletedPs != null
10599                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10600                        : null;
10601            }
10602        }
10603        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10604            removeDataDirsLI(packageName);
10605            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10606        }
10607        // writer
10608        synchronized (mPackages) {
10609            if (deletedPs != null) {
10610                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10611                    if (outInfo != null) {
10612                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10613                    }
10614                    if (deletedPs != null) {
10615                        updatePermissionsLPw(deletedPs.name, null, 0);
10616                        if (deletedPs.sharedUser != null) {
10617                            // remove permissions associated with package
10618                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10619                        }
10620                    }
10621                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10622                }
10623                // make sure to preserve per-user disabled state if this removal was just
10624                // a downgrade of a system app to the factory package
10625                if (allUserHandles != null && perUserInstalled != null) {
10626                    if (DEBUG_REMOVE) {
10627                        Slog.d(TAG, "Propagating install state across downgrade");
10628                    }
10629                    for (int i = 0; i < allUserHandles.length; i++) {
10630                        if (DEBUG_REMOVE) {
10631                            Slog.d(TAG, "    user " + allUserHandles[i]
10632                                    + " => " + perUserInstalled[i]);
10633                        }
10634                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10635                    }
10636                }
10637            }
10638            // can downgrade to reader
10639            if (writeSettings) {
10640                // Save settings now
10641                mSettings.writeLPr();
10642            }
10643        }
10644        if (outInfo != null) {
10645            // A user ID was deleted here. Go through all users and remove it
10646            // from KeyStore.
10647            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10648        }
10649    }
10650
10651    static boolean locationIsPrivileged(File path) {
10652        try {
10653            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10654                    .getCanonicalPath();
10655            return path.getCanonicalPath().startsWith(privilegedAppDir);
10656        } catch (IOException e) {
10657            Slog.e(TAG, "Unable to access code path " + path);
10658        }
10659        return false;
10660    }
10661
10662    /*
10663     * Tries to delete system package.
10664     */
10665    private boolean deleteSystemPackageLI(PackageSetting newPs,
10666            int[] allUserHandles, boolean[] perUserInstalled,
10667            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10668        final boolean applyUserRestrictions
10669                = (allUserHandles != null) && (perUserInstalled != null);
10670        PackageSetting disabledPs = null;
10671        // Confirm if the system package has been updated
10672        // An updated system app can be deleted. This will also have to restore
10673        // the system pkg from system partition
10674        // reader
10675        synchronized (mPackages) {
10676            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10677        }
10678        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10679                + " disabledPs=" + disabledPs);
10680        if (disabledPs == null) {
10681            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10682            return false;
10683        } else if (DEBUG_REMOVE) {
10684            Slog.d(TAG, "Deleting system pkg from data partition");
10685        }
10686        if (DEBUG_REMOVE) {
10687            if (applyUserRestrictions) {
10688                Slog.d(TAG, "Remembering install states:");
10689                for (int i = 0; i < allUserHandles.length; i++) {
10690                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10691                }
10692            }
10693        }
10694        // Delete the updated package
10695        outInfo.isRemovedPackageSystemUpdate = true;
10696        if (disabledPs.versionCode < newPs.versionCode) {
10697            // Delete data for downgrades
10698            flags &= ~PackageManager.DELETE_KEEP_DATA;
10699        } else {
10700            // Preserve data by setting flag
10701            flags |= PackageManager.DELETE_KEEP_DATA;
10702        }
10703        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10704                allUserHandles, perUserInstalled, outInfo, writeSettings);
10705        if (!ret) {
10706            return false;
10707        }
10708        // writer
10709        synchronized (mPackages) {
10710            // Reinstate the old system package
10711            mSettings.enableSystemPackageLPw(newPs.name);
10712            // Remove any native libraries from the upgraded package.
10713            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10714        }
10715        // Install the system package
10716        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10717        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10718        if (locationIsPrivileged(disabledPs.codePath)) {
10719            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10720        }
10721        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10722                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10723
10724        if (newPkg == null) {
10725            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10726                    + " with error:" + mLastScanError);
10727            return false;
10728        }
10729        // writer
10730        synchronized (mPackages) {
10731            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10732            setInternalAppNativeLibraryPath(newPkg, ps);
10733            updatePermissionsLPw(newPkg.packageName, newPkg,
10734                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10735            if (applyUserRestrictions) {
10736                if (DEBUG_REMOVE) {
10737                    Slog.d(TAG, "Propagating install state across reinstall");
10738                }
10739                for (int i = 0; i < allUserHandles.length; i++) {
10740                    if (DEBUG_REMOVE) {
10741                        Slog.d(TAG, "    user " + allUserHandles[i]
10742                                + " => " + perUserInstalled[i]);
10743                    }
10744                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10745                }
10746                // Regardless of writeSettings we need to ensure that this restriction
10747                // state propagation is persisted
10748                mSettings.writeAllUsersPackageRestrictionsLPr();
10749            }
10750            // can downgrade to reader here
10751            if (writeSettings) {
10752                mSettings.writeLPr();
10753            }
10754        }
10755        return true;
10756    }
10757
10758    private boolean deleteInstalledPackageLI(PackageSetting ps,
10759            boolean deleteCodeAndResources, int flags,
10760            int[] allUserHandles, boolean[] perUserInstalled,
10761            PackageRemovedInfo outInfo, boolean writeSettings) {
10762        if (outInfo != null) {
10763            outInfo.uid = ps.appId;
10764        }
10765
10766        // Delete package data from internal structures and also remove data if flag is set
10767        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10768
10769        // Delete application code and resources
10770        if (deleteCodeAndResources && (outInfo != null)) {
10771            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10772                    ps.resourcePathString, ps.nativeLibraryPathString,
10773                    getAppInstructionSetFromSettings(ps));
10774        }
10775        return true;
10776    }
10777
10778    /*
10779     * This method handles package deletion in general
10780     */
10781    private boolean deletePackageLI(String packageName, UserHandle user,
10782            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10783            int flags, PackageRemovedInfo outInfo,
10784            boolean writeSettings) {
10785        if (packageName == null) {
10786            Slog.w(TAG, "Attempt to delete null packageName.");
10787            return false;
10788        }
10789        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10790        PackageSetting ps;
10791        boolean dataOnly = false;
10792        int removeUser = -1;
10793        int appId = -1;
10794        synchronized (mPackages) {
10795            ps = mSettings.mPackages.get(packageName);
10796            if (ps == null) {
10797                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10798                return false;
10799            }
10800            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10801                    && user.getIdentifier() != UserHandle.USER_ALL) {
10802                // The caller is asking that the package only be deleted for a single
10803                // user.  To do this, we just mark its uninstalled state and delete
10804                // its data.  If this is a system app, we only allow this to happen if
10805                // they have set the special DELETE_SYSTEM_APP which requests different
10806                // semantics than normal for uninstalling system apps.
10807                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10808                ps.setUserState(user.getIdentifier(),
10809                        COMPONENT_ENABLED_STATE_DEFAULT,
10810                        false, //installed
10811                        true,  //stopped
10812                        true,  //notLaunched
10813                        false, //blocked
10814                        null, null, null);
10815                if (!isSystemApp(ps)) {
10816                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10817                        // Other user still have this package installed, so all
10818                        // we need to do is clear this user's data and save that
10819                        // it is uninstalled.
10820                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10821                        removeUser = user.getIdentifier();
10822                        appId = ps.appId;
10823                        mSettings.writePackageRestrictionsLPr(removeUser);
10824                    } else {
10825                        // We need to set it back to 'installed' so the uninstall
10826                        // broadcasts will be sent correctly.
10827                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10828                        ps.setInstalled(true, user.getIdentifier());
10829                    }
10830                } else {
10831                    // This is a system app, so we assume that the
10832                    // other users still have this package installed, so all
10833                    // we need to do is clear this user's data and save that
10834                    // it is uninstalled.
10835                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10836                    removeUser = user.getIdentifier();
10837                    appId = ps.appId;
10838                    mSettings.writePackageRestrictionsLPr(removeUser);
10839                }
10840            }
10841        }
10842
10843        if (removeUser >= 0) {
10844            // From above, we determined that we are deleting this only
10845            // for a single user.  Continue the work here.
10846            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10847            if (outInfo != null) {
10848                outInfo.removedPackage = packageName;
10849                outInfo.removedAppId = appId;
10850                outInfo.removedUsers = new int[] {removeUser};
10851            }
10852            mInstaller.clearUserData(packageName, removeUser);
10853            removeKeystoreDataIfNeeded(removeUser, appId);
10854            schedulePackageCleaning(packageName, removeUser, false);
10855            return true;
10856        }
10857
10858        if (dataOnly) {
10859            // Delete application data first
10860            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10861            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10862            return true;
10863        }
10864
10865        boolean ret = false;
10866        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10867        if (isSystemApp(ps)) {
10868            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10869            // When an updated system application is deleted we delete the existing resources as well and
10870            // fall back to existing code in system partition
10871            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10872                    flags, outInfo, writeSettings);
10873        } else {
10874            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10875            // Kill application pre-emptively especially for apps on sd.
10876            killApplication(packageName, ps.appId, "uninstall pkg");
10877            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10878                    allUserHandles, perUserInstalled,
10879                    outInfo, writeSettings);
10880        }
10881
10882        return ret;
10883    }
10884
10885    private final class ClearStorageConnection implements ServiceConnection {
10886        IMediaContainerService mContainerService;
10887
10888        @Override
10889        public void onServiceConnected(ComponentName name, IBinder service) {
10890            synchronized (this) {
10891                mContainerService = IMediaContainerService.Stub.asInterface(service);
10892                notifyAll();
10893            }
10894        }
10895
10896        @Override
10897        public void onServiceDisconnected(ComponentName name) {
10898        }
10899    }
10900
10901    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10902        final boolean mounted;
10903        if (Environment.isExternalStorageEmulated()) {
10904            mounted = true;
10905        } else {
10906            final String status = Environment.getExternalStorageState();
10907
10908            mounted = status.equals(Environment.MEDIA_MOUNTED)
10909                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10910        }
10911
10912        if (!mounted) {
10913            return;
10914        }
10915
10916        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10917        int[] users;
10918        if (userId == UserHandle.USER_ALL) {
10919            users = sUserManager.getUserIds();
10920        } else {
10921            users = new int[] { userId };
10922        }
10923        final ClearStorageConnection conn = new ClearStorageConnection();
10924        if (mContext.bindServiceAsUser(
10925                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10926            try {
10927                for (int curUser : users) {
10928                    long timeout = SystemClock.uptimeMillis() + 5000;
10929                    synchronized (conn) {
10930                        long now = SystemClock.uptimeMillis();
10931                        while (conn.mContainerService == null && now < timeout) {
10932                            try {
10933                                conn.wait(timeout - now);
10934                            } catch (InterruptedException e) {
10935                            }
10936                        }
10937                    }
10938                    if (conn.mContainerService == null) {
10939                        return;
10940                    }
10941
10942                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10943                    clearDirectory(conn.mContainerService,
10944                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10945                    if (allData) {
10946                        clearDirectory(conn.mContainerService,
10947                                userEnv.buildExternalStorageAppDataDirs(packageName));
10948                        clearDirectory(conn.mContainerService,
10949                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10950                    }
10951                }
10952            } finally {
10953                mContext.unbindService(conn);
10954            }
10955        }
10956    }
10957
10958    @Override
10959    public void clearApplicationUserData(final String packageName,
10960            final IPackageDataObserver observer, final int userId) {
10961        mContext.enforceCallingOrSelfPermission(
10962                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10963        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10964        // Queue up an async operation since the package deletion may take a little while.
10965        mHandler.post(new Runnable() {
10966            public void run() {
10967                mHandler.removeCallbacks(this);
10968                final boolean succeeded;
10969                synchronized (mInstallLock) {
10970                    succeeded = clearApplicationUserDataLI(packageName, userId);
10971                }
10972                clearExternalStorageDataSync(packageName, userId, true);
10973                if (succeeded) {
10974                    // invoke DeviceStorageMonitor's update method to clear any notifications
10975                    DeviceStorageMonitorInternal
10976                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10977                    if (dsm != null) {
10978                        dsm.checkMemory();
10979                    }
10980                }
10981                if(observer != null) {
10982                    try {
10983                        observer.onRemoveCompleted(packageName, succeeded);
10984                    } catch (RemoteException e) {
10985                        Log.i(TAG, "Observer no longer exists.");
10986                    }
10987                } //end if observer
10988            } //end run
10989        });
10990    }
10991
10992    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10993        if (packageName == null) {
10994            Slog.w(TAG, "Attempt to delete null packageName.");
10995            return false;
10996        }
10997        PackageParser.Package p;
10998        boolean dataOnly = false;
10999        final int appId;
11000        synchronized (mPackages) {
11001            p = mPackages.get(packageName);
11002            if (p == null) {
11003                dataOnly = true;
11004                PackageSetting ps = mSettings.mPackages.get(packageName);
11005                if ((ps == null) || (ps.pkg == null)) {
11006                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11007                    return false;
11008                }
11009                p = ps.pkg;
11010            }
11011            if (!dataOnly) {
11012                // need to check this only for fully installed applications
11013                if (p == null) {
11014                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11015                    return false;
11016                }
11017                final ApplicationInfo applicationInfo = p.applicationInfo;
11018                if (applicationInfo == null) {
11019                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11020                    return false;
11021                }
11022            }
11023            if (p != null && p.applicationInfo != null) {
11024                appId = p.applicationInfo.uid;
11025            } else {
11026                appId = -1;
11027            }
11028        }
11029        int retCode = mInstaller.clearUserData(packageName, userId);
11030        if (retCode < 0) {
11031            Slog.w(TAG, "Couldn't remove cache files for package: "
11032                    + packageName);
11033            return false;
11034        }
11035        removeKeystoreDataIfNeeded(userId, appId);
11036        return true;
11037    }
11038
11039    /**
11040     * Remove entries from the keystore daemon. Will only remove it if the
11041     * {@code appId} is valid.
11042     */
11043    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11044        if (appId < 0) {
11045            return;
11046        }
11047
11048        final KeyStore keyStore = KeyStore.getInstance();
11049        if (keyStore != null) {
11050            if (userId == UserHandle.USER_ALL) {
11051                for (final int individual : sUserManager.getUserIds()) {
11052                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11053                }
11054            } else {
11055                keyStore.clearUid(UserHandle.getUid(userId, appId));
11056            }
11057        } else {
11058            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11059        }
11060    }
11061
11062    @Override
11063    public void deleteApplicationCacheFiles(final String packageName,
11064            final IPackageDataObserver observer) {
11065        mContext.enforceCallingOrSelfPermission(
11066                android.Manifest.permission.DELETE_CACHE_FILES, null);
11067        // Queue up an async operation since the package deletion may take a little while.
11068        final int userId = UserHandle.getCallingUserId();
11069        mHandler.post(new Runnable() {
11070            public void run() {
11071                mHandler.removeCallbacks(this);
11072                final boolean succeded;
11073                synchronized (mInstallLock) {
11074                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11075                }
11076                clearExternalStorageDataSync(packageName, userId, false);
11077                if(observer != null) {
11078                    try {
11079                        observer.onRemoveCompleted(packageName, succeded);
11080                    } catch (RemoteException e) {
11081                        Log.i(TAG, "Observer no longer exists.");
11082                    }
11083                } //end if observer
11084            } //end run
11085        });
11086    }
11087
11088    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11089        if (packageName == null) {
11090            Slog.w(TAG, "Attempt to delete null packageName.");
11091            return false;
11092        }
11093        PackageParser.Package p;
11094        synchronized (mPackages) {
11095            p = mPackages.get(packageName);
11096        }
11097        if (p == null) {
11098            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11099            return false;
11100        }
11101        final ApplicationInfo applicationInfo = p.applicationInfo;
11102        if (applicationInfo == null) {
11103            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11104            return false;
11105        }
11106        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11107        if (retCode < 0) {
11108            Slog.w(TAG, "Couldn't remove cache files for package: "
11109                       + packageName + " u" + userId);
11110            return false;
11111        }
11112        return true;
11113    }
11114
11115    @Override
11116    public void getPackageSizeInfo(final String packageName, int userHandle,
11117            final IPackageStatsObserver observer) {
11118        mContext.enforceCallingOrSelfPermission(
11119                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11120        if (packageName == null) {
11121            throw new IllegalArgumentException("Attempt to get size of null packageName");
11122        }
11123
11124        PackageStats stats = new PackageStats(packageName, userHandle);
11125
11126        /*
11127         * Queue up an async operation since the package measurement may take a
11128         * little while.
11129         */
11130        Message msg = mHandler.obtainMessage(INIT_COPY);
11131        msg.obj = new MeasureParams(stats, observer);
11132        mHandler.sendMessage(msg);
11133    }
11134
11135    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11136            PackageStats pStats) {
11137        if (packageName == null) {
11138            Slog.w(TAG, "Attempt to get size of null packageName.");
11139            return false;
11140        }
11141        PackageParser.Package p;
11142        boolean dataOnly = false;
11143        String libDirPath = null;
11144        String asecPath = null;
11145        PackageSetting ps = null;
11146        synchronized (mPackages) {
11147            p = mPackages.get(packageName);
11148            ps = mSettings.mPackages.get(packageName);
11149            if(p == null) {
11150                dataOnly = true;
11151                if((ps == null) || (ps.pkg == null)) {
11152                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11153                    return false;
11154                }
11155                p = ps.pkg;
11156            }
11157            if (ps != null) {
11158                libDirPath = ps.nativeLibraryPathString;
11159            }
11160            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11161                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11162                if (secureContainerId != null) {
11163                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11164                }
11165            }
11166        }
11167        String publicSrcDir = null;
11168        if(!dataOnly) {
11169            final ApplicationInfo applicationInfo = p.applicationInfo;
11170            if (applicationInfo == null) {
11171                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11172                return false;
11173            }
11174            if (isForwardLocked(p)) {
11175                publicSrcDir = applicationInfo.publicSourceDir;
11176            }
11177        }
11178        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11179                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11180                pStats);
11181        if (res < 0) {
11182            return false;
11183        }
11184
11185        // Fix-up for forward-locked applications in ASEC containers.
11186        if (!isExternal(p)) {
11187            pStats.codeSize += pStats.externalCodeSize;
11188            pStats.externalCodeSize = 0L;
11189        }
11190
11191        return true;
11192    }
11193
11194
11195    @Override
11196    public void addPackageToPreferred(String packageName) {
11197        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11198    }
11199
11200    @Override
11201    public void removePackageFromPreferred(String packageName) {
11202        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11203    }
11204
11205    @Override
11206    public List<PackageInfo> getPreferredPackages(int flags) {
11207        return new ArrayList<PackageInfo>();
11208    }
11209
11210    private int getUidTargetSdkVersionLockedLPr(int uid) {
11211        Object obj = mSettings.getUserIdLPr(uid);
11212        if (obj instanceof SharedUserSetting) {
11213            final SharedUserSetting sus = (SharedUserSetting) obj;
11214            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11215            final Iterator<PackageSetting> it = sus.packages.iterator();
11216            while (it.hasNext()) {
11217                final PackageSetting ps = it.next();
11218                if (ps.pkg != null) {
11219                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11220                    if (v < vers) vers = v;
11221                }
11222            }
11223            return vers;
11224        } else if (obj instanceof PackageSetting) {
11225            final PackageSetting ps = (PackageSetting) obj;
11226            if (ps.pkg != null) {
11227                return ps.pkg.applicationInfo.targetSdkVersion;
11228            }
11229        }
11230        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11231    }
11232
11233    @Override
11234    public void addPreferredActivity(IntentFilter filter, int match,
11235            ComponentName[] set, ComponentName activity, int userId) {
11236        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11237    }
11238
11239    private void addPreferredActivityInternal(IntentFilter filter, int match,
11240            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11241        // writer
11242        int callingUid = Binder.getCallingUid();
11243        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11244        if (filter.countActions() == 0) {
11245            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11246            return;
11247        }
11248        synchronized (mPackages) {
11249            if (mContext.checkCallingOrSelfPermission(
11250                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11251                    != PackageManager.PERMISSION_GRANTED) {
11252                if (getUidTargetSdkVersionLockedLPr(callingUid)
11253                        < Build.VERSION_CODES.FROYO) {
11254                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11255                            + callingUid);
11256                    return;
11257                }
11258                mContext.enforceCallingOrSelfPermission(
11259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11260            }
11261
11262            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11263            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11264            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11265                    new PreferredActivity(filter, match, set, activity, always));
11266            mSettings.writePackageRestrictionsLPr(userId);
11267        }
11268    }
11269
11270    @Override
11271    public void replacePreferredActivity(IntentFilter filter, int match,
11272            ComponentName[] set, ComponentName activity) {
11273        if (filter.countActions() != 1) {
11274            throw new IllegalArgumentException(
11275                    "replacePreferredActivity expects filter to have only 1 action.");
11276        }
11277        if (filter.countDataAuthorities() != 0
11278                || filter.countDataPaths() != 0
11279                || filter.countDataSchemes() > 1
11280                || filter.countDataTypes() != 0) {
11281            throw new IllegalArgumentException(
11282                    "replacePreferredActivity expects filter to have no data authorities, " +
11283                    "paths, or types; and at most one scheme.");
11284        }
11285        synchronized (mPackages) {
11286            if (mContext.checkCallingOrSelfPermission(
11287                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11288                    != PackageManager.PERMISSION_GRANTED) {
11289                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11290                        < Build.VERSION_CODES.FROYO) {
11291                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11292                            + Binder.getCallingUid());
11293                    return;
11294                }
11295                mContext.enforceCallingOrSelfPermission(
11296                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11297            }
11298
11299            final int callingUserId = UserHandle.getCallingUserId();
11300            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11301            if (pir != null) {
11302                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11303                if (filter.countDataSchemes() == 1) {
11304                    Uri.Builder builder = new Uri.Builder();
11305                    builder.scheme(filter.getDataScheme(0));
11306                    intent.setData(builder.build());
11307                }
11308                List<PreferredActivity> matches = pir.queryIntent(
11309                        intent, null, true, callingUserId);
11310                if (DEBUG_PREFERRED) {
11311                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11312                }
11313                for (int i = 0; i < matches.size(); i++) {
11314                    PreferredActivity pa = matches.get(i);
11315                    if (DEBUG_PREFERRED) {
11316                        Slog.i(TAG, "Removing preferred activity "
11317                                + pa.mPref.mComponent + ":");
11318                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11319                    }
11320                    pir.removeFilter(pa);
11321                }
11322            }
11323            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11324        }
11325    }
11326
11327    @Override
11328    public void clearPackagePreferredActivities(String packageName) {
11329        final int uid = Binder.getCallingUid();
11330        // writer
11331        synchronized (mPackages) {
11332            PackageParser.Package pkg = mPackages.get(packageName);
11333            if (pkg == null || pkg.applicationInfo.uid != uid) {
11334                if (mContext.checkCallingOrSelfPermission(
11335                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11336                        != PackageManager.PERMISSION_GRANTED) {
11337                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11338                            < Build.VERSION_CODES.FROYO) {
11339                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11340                                + Binder.getCallingUid());
11341                        return;
11342                    }
11343                    mContext.enforceCallingOrSelfPermission(
11344                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11345                }
11346            }
11347
11348            int user = UserHandle.getCallingUserId();
11349            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11350                mSettings.writePackageRestrictionsLPr(user);
11351                scheduleWriteSettingsLocked();
11352            }
11353        }
11354    }
11355
11356    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11357    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11358        ArrayList<PreferredActivity> removed = null;
11359        boolean changed = false;
11360        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11361            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11362            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11363            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11364                continue;
11365            }
11366            Iterator<PreferredActivity> it = pir.filterIterator();
11367            while (it.hasNext()) {
11368                PreferredActivity pa = it.next();
11369                // Mark entry for removal only if it matches the package name
11370                // and the entry is of type "always".
11371                if (packageName == null ||
11372                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11373                                && pa.mPref.mAlways)) {
11374                    if (removed == null) {
11375                        removed = new ArrayList<PreferredActivity>();
11376                    }
11377                    removed.add(pa);
11378                }
11379            }
11380            if (removed != null) {
11381                for (int j=0; j<removed.size(); j++) {
11382                    PreferredActivity pa = removed.get(j);
11383                    pir.removeFilter(pa);
11384                }
11385                changed = true;
11386            }
11387        }
11388        return changed;
11389    }
11390
11391    @Override
11392    public void resetPreferredActivities(int userId) {
11393        mContext.enforceCallingOrSelfPermission(
11394                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11395        // writer
11396        synchronized (mPackages) {
11397            int user = UserHandle.getCallingUserId();
11398            clearPackagePreferredActivitiesLPw(null, user);
11399            mSettings.readDefaultPreferredAppsLPw(this, user);
11400            mSettings.writePackageRestrictionsLPr(user);
11401            scheduleWriteSettingsLocked();
11402        }
11403    }
11404
11405    @Override
11406    public int getPreferredActivities(List<IntentFilter> outFilters,
11407            List<ComponentName> outActivities, String packageName) {
11408
11409        int num = 0;
11410        final int userId = UserHandle.getCallingUserId();
11411        // reader
11412        synchronized (mPackages) {
11413            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11414            if (pir != null) {
11415                final Iterator<PreferredActivity> it = pir.filterIterator();
11416                while (it.hasNext()) {
11417                    final PreferredActivity pa = it.next();
11418                    if (packageName == null
11419                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11420                                    && pa.mPref.mAlways)) {
11421                        if (outFilters != null) {
11422                            outFilters.add(new IntentFilter(pa));
11423                        }
11424                        if (outActivities != null) {
11425                            outActivities.add(pa.mPref.mComponent);
11426                        }
11427                    }
11428                }
11429            }
11430        }
11431
11432        return num;
11433    }
11434
11435    @Override
11436    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11437            int userId) {
11438        int callingUid = Binder.getCallingUid();
11439        if (callingUid != Process.SYSTEM_UID) {
11440            throw new SecurityException(
11441                    "addPersistentPreferredActivity can only be run by the system");
11442        }
11443        if (filter.countActions() == 0) {
11444            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11445            return;
11446        }
11447        synchronized (mPackages) {
11448            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11449                    " :");
11450            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11451            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11452                    new PersistentPreferredActivity(filter, activity));
11453            mSettings.writePackageRestrictionsLPr(userId);
11454        }
11455    }
11456
11457    @Override
11458    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11459        int callingUid = Binder.getCallingUid();
11460        if (callingUid != Process.SYSTEM_UID) {
11461            throw new SecurityException(
11462                    "clearPackagePersistentPreferredActivities can only be run by the system");
11463        }
11464        ArrayList<PersistentPreferredActivity> removed = null;
11465        boolean changed = false;
11466        synchronized (mPackages) {
11467            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11468                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11469                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11470                        .valueAt(i);
11471                if (userId != thisUserId) {
11472                    continue;
11473                }
11474                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11475                while (it.hasNext()) {
11476                    PersistentPreferredActivity ppa = it.next();
11477                    // Mark entry for removal only if it matches the package name.
11478                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11479                        if (removed == null) {
11480                            removed = new ArrayList<PersistentPreferredActivity>();
11481                        }
11482                        removed.add(ppa);
11483                    }
11484                }
11485                if (removed != null) {
11486                    for (int j=0; j<removed.size(); j++) {
11487                        PersistentPreferredActivity ppa = removed.get(j);
11488                        ppir.removeFilter(ppa);
11489                    }
11490                    changed = true;
11491                }
11492            }
11493
11494            if (changed) {
11495                mSettings.writePackageRestrictionsLPr(userId);
11496            }
11497        }
11498    }
11499
11500    @Override
11501    public void addCrossProfileIntentFilter(IntentFilter filter, boolean removable,
11502            int sourceUserId, int targetUserId) {
11503        mContext.enforceCallingOrSelfPermission(
11504                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11505        if (filter.countActions() == 0) {
11506            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11507            return;
11508        }
11509        synchronized (mPackages) {
11510            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(
11511                    new CrossProfileIntentFilter(filter, removable, targetUserId));
11512            mSettings.writePackageRestrictionsLPr(sourceUserId);
11513        }
11514    }
11515
11516    @Override
11517    public void clearCrossProfileIntentFilters(int sourceUserId) {
11518        mContext.enforceCallingOrSelfPermission(
11519                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11520        synchronized (mPackages) {
11521            CrossProfileIntentResolver cpir =
11522                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11523            HashSet<CrossProfileIntentFilter> set =
11524                    new HashSet<CrossProfileIntentFilter>(cpir.filterSet());
11525            for (CrossProfileIntentFilter cpif : set) {
11526                if (cpif.isRemovable()) cpir.removeFilter(cpif);
11527            }
11528            mSettings.writePackageRestrictionsLPr(sourceUserId);
11529        }
11530    }
11531
11532    @Override
11533    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11534        Intent intent = new Intent(Intent.ACTION_MAIN);
11535        intent.addCategory(Intent.CATEGORY_HOME);
11536
11537        final int callingUserId = UserHandle.getCallingUserId();
11538        List<ResolveInfo> list = queryIntentActivities(intent, null,
11539                PackageManager.GET_META_DATA, callingUserId);
11540        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11541                true, false, false, callingUserId);
11542
11543        allHomeCandidates.clear();
11544        if (list != null) {
11545            for (ResolveInfo ri : list) {
11546                allHomeCandidates.add(ri);
11547            }
11548        }
11549        return (preferred == null || preferred.activityInfo == null)
11550                ? null
11551                : new ComponentName(preferred.activityInfo.packageName,
11552                        preferred.activityInfo.name);
11553    }
11554
11555    @Override
11556    public void setApplicationEnabledSetting(String appPackageName,
11557            int newState, int flags, int userId, String callingPackage) {
11558        if (!sUserManager.exists(userId)) return;
11559        if (callingPackage == null) {
11560            callingPackage = Integer.toString(Binder.getCallingUid());
11561        }
11562        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11563    }
11564
11565    @Override
11566    public void setComponentEnabledSetting(ComponentName componentName,
11567            int newState, int flags, int userId) {
11568        if (!sUserManager.exists(userId)) return;
11569        setEnabledSetting(componentName.getPackageName(),
11570                componentName.getClassName(), newState, flags, userId, null);
11571    }
11572
11573    private void setEnabledSetting(final String packageName, String className, int newState,
11574            final int flags, int userId, String callingPackage) {
11575        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11576              || newState == COMPONENT_ENABLED_STATE_ENABLED
11577              || newState == COMPONENT_ENABLED_STATE_DISABLED
11578              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11579              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11580            throw new IllegalArgumentException("Invalid new component state: "
11581                    + newState);
11582        }
11583        PackageSetting pkgSetting;
11584        final int uid = Binder.getCallingUid();
11585        final int permission = mContext.checkCallingOrSelfPermission(
11586                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11587        enforceCrossUserPermission(uid, userId, false, "set enabled");
11588        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11589        boolean sendNow = false;
11590        boolean isApp = (className == null);
11591        String componentName = isApp ? packageName : className;
11592        int packageUid = -1;
11593        ArrayList<String> components;
11594
11595        // writer
11596        synchronized (mPackages) {
11597            pkgSetting = mSettings.mPackages.get(packageName);
11598            if (pkgSetting == null) {
11599                if (className == null) {
11600                    throw new IllegalArgumentException(
11601                            "Unknown package: " + packageName);
11602                }
11603                throw new IllegalArgumentException(
11604                        "Unknown component: " + packageName
11605                        + "/" + className);
11606            }
11607            // Allow root and verify that userId is not being specified by a different user
11608            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11609                throw new SecurityException(
11610                        "Permission Denial: attempt to change component state from pid="
11611                        + Binder.getCallingPid()
11612                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11613            }
11614            if (className == null) {
11615                // We're dealing with an application/package level state change
11616                if (pkgSetting.getEnabled(userId) == newState) {
11617                    // Nothing to do
11618                    return;
11619                }
11620                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11621                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11622                    // Don't care about who enables an app.
11623                    callingPackage = null;
11624                }
11625                pkgSetting.setEnabled(newState, userId, callingPackage);
11626                // pkgSetting.pkg.mSetEnabled = newState;
11627            } else {
11628                // We're dealing with a component level state change
11629                // First, verify that this is a valid class name.
11630                PackageParser.Package pkg = pkgSetting.pkg;
11631                if (pkg == null || !pkg.hasComponentClassName(className)) {
11632                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11633                        throw new IllegalArgumentException("Component class " + className
11634                                + " does not exist in " + packageName);
11635                    } else {
11636                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11637                                + className + " does not exist in " + packageName);
11638                    }
11639                }
11640                switch (newState) {
11641                case COMPONENT_ENABLED_STATE_ENABLED:
11642                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11643                        return;
11644                    }
11645                    break;
11646                case COMPONENT_ENABLED_STATE_DISABLED:
11647                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11648                        return;
11649                    }
11650                    break;
11651                case COMPONENT_ENABLED_STATE_DEFAULT:
11652                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11653                        return;
11654                    }
11655                    break;
11656                default:
11657                    Slog.e(TAG, "Invalid new component state: " + newState);
11658                    return;
11659                }
11660            }
11661            mSettings.writePackageRestrictionsLPr(userId);
11662            components = mPendingBroadcasts.get(userId, packageName);
11663            final boolean newPackage = components == null;
11664            if (newPackage) {
11665                components = new ArrayList<String>();
11666            }
11667            if (!components.contains(componentName)) {
11668                components.add(componentName);
11669            }
11670            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11671                sendNow = true;
11672                // Purge entry from pending broadcast list if another one exists already
11673                // since we are sending one right away.
11674                mPendingBroadcasts.remove(userId, packageName);
11675            } else {
11676                if (newPackage) {
11677                    mPendingBroadcasts.put(userId, packageName, components);
11678                }
11679                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11680                    // Schedule a message
11681                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11682                }
11683            }
11684        }
11685
11686        long callingId = Binder.clearCallingIdentity();
11687        try {
11688            if (sendNow) {
11689                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11690                sendPackageChangedBroadcast(packageName,
11691                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11692            }
11693        } finally {
11694            Binder.restoreCallingIdentity(callingId);
11695        }
11696    }
11697
11698    private void sendPackageChangedBroadcast(String packageName,
11699            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11700        if (DEBUG_INSTALL)
11701            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11702                    + componentNames);
11703        Bundle extras = new Bundle(4);
11704        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11705        String nameList[] = new String[componentNames.size()];
11706        componentNames.toArray(nameList);
11707        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11708        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11709        extras.putInt(Intent.EXTRA_UID, packageUid);
11710        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11711                new int[] {UserHandle.getUserId(packageUid)});
11712    }
11713
11714    @Override
11715    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11716        if (!sUserManager.exists(userId)) return;
11717        final int uid = Binder.getCallingUid();
11718        final int permission = mContext.checkCallingOrSelfPermission(
11719                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11720        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11721        enforceCrossUserPermission(uid, userId, true, "stop package");
11722        // writer
11723        synchronized (mPackages) {
11724            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11725                    uid, userId)) {
11726                scheduleWritePackageRestrictionsLocked(userId);
11727            }
11728        }
11729    }
11730
11731    @Override
11732    public String getInstallerPackageName(String packageName) {
11733        // reader
11734        synchronized (mPackages) {
11735            return mSettings.getInstallerPackageNameLPr(packageName);
11736        }
11737    }
11738
11739    @Override
11740    public int getApplicationEnabledSetting(String packageName, int userId) {
11741        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11742        int uid = Binder.getCallingUid();
11743        enforceCrossUserPermission(uid, userId, false, "get enabled");
11744        // reader
11745        synchronized (mPackages) {
11746            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11747        }
11748    }
11749
11750    @Override
11751    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11752        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11753        int uid = Binder.getCallingUid();
11754        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11755        // reader
11756        synchronized (mPackages) {
11757            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11758        }
11759    }
11760
11761    @Override
11762    public void enterSafeMode() {
11763        enforceSystemOrRoot("Only the system can request entering safe mode");
11764
11765        if (!mSystemReady) {
11766            mSafeMode = true;
11767        }
11768    }
11769
11770    @Override
11771    public void systemReady() {
11772        mSystemReady = true;
11773
11774        // Read the compatibilty setting when the system is ready.
11775        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11776                mContext.getContentResolver(),
11777                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11778        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11779        if (DEBUG_SETTINGS) {
11780            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11781        }
11782
11783        synchronized (mPackages) {
11784            // Verify that all of the preferred activity components actually
11785            // exist.  It is possible for applications to be updated and at
11786            // that point remove a previously declared activity component that
11787            // had been set as a preferred activity.  We try to clean this up
11788            // the next time we encounter that preferred activity, but it is
11789            // possible for the user flow to never be able to return to that
11790            // situation so here we do a sanity check to make sure we haven't
11791            // left any junk around.
11792            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11793            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11794                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11795                removed.clear();
11796                for (PreferredActivity pa : pir.filterSet()) {
11797                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11798                        removed.add(pa);
11799                    }
11800                }
11801                if (removed.size() > 0) {
11802                    for (int r=0; r<removed.size(); r++) {
11803                        PreferredActivity pa = removed.get(r);
11804                        Slog.w(TAG, "Removing dangling preferred activity: "
11805                                + pa.mPref.mComponent);
11806                        pir.removeFilter(pa);
11807                    }
11808                    mSettings.writePackageRestrictionsLPr(
11809                            mSettings.mPreferredActivities.keyAt(i));
11810                }
11811            }
11812        }
11813        sUserManager.systemReady();
11814    }
11815
11816    @Override
11817    public boolean isSafeMode() {
11818        return mSafeMode;
11819    }
11820
11821    @Override
11822    public boolean hasSystemUidErrors() {
11823        return mHasSystemUidErrors;
11824    }
11825
11826    static String arrayToString(int[] array) {
11827        StringBuffer buf = new StringBuffer(128);
11828        buf.append('[');
11829        if (array != null) {
11830            for (int i=0; i<array.length; i++) {
11831                if (i > 0) buf.append(", ");
11832                buf.append(array[i]);
11833            }
11834        }
11835        buf.append(']');
11836        return buf.toString();
11837    }
11838
11839    static class DumpState {
11840        public static final int DUMP_LIBS = 1 << 0;
11841
11842        public static final int DUMP_FEATURES = 1 << 1;
11843
11844        public static final int DUMP_RESOLVERS = 1 << 2;
11845
11846        public static final int DUMP_PERMISSIONS = 1 << 3;
11847
11848        public static final int DUMP_PACKAGES = 1 << 4;
11849
11850        public static final int DUMP_SHARED_USERS = 1 << 5;
11851
11852        public static final int DUMP_MESSAGES = 1 << 6;
11853
11854        public static final int DUMP_PROVIDERS = 1 << 7;
11855
11856        public static final int DUMP_VERIFIERS = 1 << 8;
11857
11858        public static final int DUMP_PREFERRED = 1 << 9;
11859
11860        public static final int DUMP_PREFERRED_XML = 1 << 10;
11861
11862        public static final int DUMP_KEYSETS = 1 << 11;
11863
11864        public static final int DUMP_VERSION = 1 << 12;
11865
11866        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11867
11868        private int mTypes;
11869
11870        private int mOptions;
11871
11872        private boolean mTitlePrinted;
11873
11874        private SharedUserSetting mSharedUser;
11875
11876        public boolean isDumping(int type) {
11877            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11878                return true;
11879            }
11880
11881            return (mTypes & type) != 0;
11882        }
11883
11884        public void setDump(int type) {
11885            mTypes |= type;
11886        }
11887
11888        public boolean isOptionEnabled(int option) {
11889            return (mOptions & option) != 0;
11890        }
11891
11892        public void setOptionEnabled(int option) {
11893            mOptions |= option;
11894        }
11895
11896        public boolean onTitlePrinted() {
11897            final boolean printed = mTitlePrinted;
11898            mTitlePrinted = true;
11899            return printed;
11900        }
11901
11902        public boolean getTitlePrinted() {
11903            return mTitlePrinted;
11904        }
11905
11906        public void setTitlePrinted(boolean enabled) {
11907            mTitlePrinted = enabled;
11908        }
11909
11910        public SharedUserSetting getSharedUser() {
11911            return mSharedUser;
11912        }
11913
11914        public void setSharedUser(SharedUserSetting user) {
11915            mSharedUser = user;
11916        }
11917    }
11918
11919    @Override
11920    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11921        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11922                != PackageManager.PERMISSION_GRANTED) {
11923            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11924                    + Binder.getCallingPid()
11925                    + ", uid=" + Binder.getCallingUid()
11926                    + " without permission "
11927                    + android.Manifest.permission.DUMP);
11928            return;
11929        }
11930
11931        DumpState dumpState = new DumpState();
11932        boolean fullPreferred = false;
11933        boolean checkin = false;
11934
11935        String packageName = null;
11936
11937        int opti = 0;
11938        while (opti < args.length) {
11939            String opt = args[opti];
11940            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11941                break;
11942            }
11943            opti++;
11944            if ("-a".equals(opt)) {
11945                // Right now we only know how to print all.
11946            } else if ("-h".equals(opt)) {
11947                pw.println("Package manager dump options:");
11948                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11949                pw.println("    --checkin: dump for a checkin");
11950                pw.println("    -f: print details of intent filters");
11951                pw.println("    -h: print this help");
11952                pw.println("  cmd may be one of:");
11953                pw.println("    l[ibraries]: list known shared libraries");
11954                pw.println("    f[ibraries]: list device features");
11955                pw.println("    k[eysets]: print known keysets");
11956                pw.println("    r[esolvers]: dump intent resolvers");
11957                pw.println("    perm[issions]: dump permissions");
11958                pw.println("    pref[erred]: print preferred package settings");
11959                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11960                pw.println("    prov[iders]: dump content providers");
11961                pw.println("    p[ackages]: dump installed packages");
11962                pw.println("    s[hared-users]: dump shared user IDs");
11963                pw.println("    m[essages]: print collected runtime messages");
11964                pw.println("    v[erifiers]: print package verifier info");
11965                pw.println("    version: print database version info");
11966                pw.println("    write: write current settings now");
11967                pw.println("    <package.name>: info about given package");
11968                return;
11969            } else if ("--checkin".equals(opt)) {
11970                checkin = true;
11971            } else if ("-f".equals(opt)) {
11972                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11973            } else {
11974                pw.println("Unknown argument: " + opt + "; use -h for help");
11975            }
11976        }
11977
11978        // Is the caller requesting to dump a particular piece of data?
11979        if (opti < args.length) {
11980            String cmd = args[opti];
11981            opti++;
11982            // Is this a package name?
11983            if ("android".equals(cmd) || cmd.contains(".")) {
11984                packageName = cmd;
11985                // When dumping a single package, we always dump all of its
11986                // filter information since the amount of data will be reasonable.
11987                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11988            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11989                dumpState.setDump(DumpState.DUMP_LIBS);
11990            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11991                dumpState.setDump(DumpState.DUMP_FEATURES);
11992            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11993                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11994            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11995                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11996            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11997                dumpState.setDump(DumpState.DUMP_PREFERRED);
11998            } else if ("preferred-xml".equals(cmd)) {
11999                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12000                if (opti < args.length && "--full".equals(args[opti])) {
12001                    fullPreferred = true;
12002                    opti++;
12003                }
12004            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12005                dumpState.setDump(DumpState.DUMP_PACKAGES);
12006            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12007                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12008            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12009                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12010            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12011                dumpState.setDump(DumpState.DUMP_MESSAGES);
12012            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12013                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12014            } else if ("version".equals(cmd)) {
12015                dumpState.setDump(DumpState.DUMP_VERSION);
12016            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12017                dumpState.setDump(DumpState.DUMP_KEYSETS);
12018            } else if ("write".equals(cmd)) {
12019                synchronized (mPackages) {
12020                    mSettings.writeLPr();
12021                    pw.println("Settings written.");
12022                    return;
12023                }
12024            }
12025        }
12026
12027        if (checkin) {
12028            pw.println("vers,1");
12029        }
12030
12031        // reader
12032        synchronized (mPackages) {
12033            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12034                if (!checkin) {
12035                    if (dumpState.onTitlePrinted())
12036                        pw.println();
12037                    pw.println("Database versions:");
12038                    pw.print("  SDK Version:");
12039                    pw.print(" internal=");
12040                    pw.print(mSettings.mInternalSdkPlatform);
12041                    pw.print(" external=");
12042                    pw.println(mSettings.mExternalSdkPlatform);
12043                    pw.print("  DB Version:");
12044                    pw.print(" internal=");
12045                    pw.print(mSettings.mInternalDatabaseVersion);
12046                    pw.print(" external=");
12047                    pw.println(mSettings.mExternalDatabaseVersion);
12048                }
12049            }
12050
12051            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12052                if (!checkin) {
12053                    if (dumpState.onTitlePrinted())
12054                        pw.println();
12055                    pw.println("Verifiers:");
12056                    pw.print("  Required: ");
12057                    pw.print(mRequiredVerifierPackage);
12058                    pw.print(" (uid=");
12059                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12060                    pw.println(")");
12061                } else if (mRequiredVerifierPackage != null) {
12062                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12063                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12064                }
12065            }
12066
12067            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12068                boolean printedHeader = false;
12069                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12070                while (it.hasNext()) {
12071                    String name = it.next();
12072                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12073                    if (!checkin) {
12074                        if (!printedHeader) {
12075                            if (dumpState.onTitlePrinted())
12076                                pw.println();
12077                            pw.println("Libraries:");
12078                            printedHeader = true;
12079                        }
12080                        pw.print("  ");
12081                    } else {
12082                        pw.print("lib,");
12083                    }
12084                    pw.print(name);
12085                    if (!checkin) {
12086                        pw.print(" -> ");
12087                    }
12088                    if (ent.path != null) {
12089                        if (!checkin) {
12090                            pw.print("(jar) ");
12091                            pw.print(ent.path);
12092                        } else {
12093                            pw.print(",jar,");
12094                            pw.print(ent.path);
12095                        }
12096                    } else {
12097                        if (!checkin) {
12098                            pw.print("(apk) ");
12099                            pw.print(ent.apk);
12100                        } else {
12101                            pw.print(",apk,");
12102                            pw.print(ent.apk);
12103                        }
12104                    }
12105                    pw.println();
12106                }
12107            }
12108
12109            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12110                if (dumpState.onTitlePrinted())
12111                    pw.println();
12112                if (!checkin) {
12113                    pw.println("Features:");
12114                }
12115                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12116                while (it.hasNext()) {
12117                    String name = it.next();
12118                    if (!checkin) {
12119                        pw.print("  ");
12120                    } else {
12121                        pw.print("feat,");
12122                    }
12123                    pw.println(name);
12124                }
12125            }
12126
12127            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12128                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12129                        : "Activity Resolver Table:", "  ", packageName,
12130                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12131                    dumpState.setTitlePrinted(true);
12132                }
12133                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12134                        : "Receiver Resolver Table:", "  ", packageName,
12135                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12136                    dumpState.setTitlePrinted(true);
12137                }
12138                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12139                        : "Service Resolver Table:", "  ", packageName,
12140                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12141                    dumpState.setTitlePrinted(true);
12142                }
12143                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12144                        : "Provider Resolver Table:", "  ", packageName,
12145                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12146                    dumpState.setTitlePrinted(true);
12147                }
12148            }
12149
12150            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12151                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12152                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12153                    int user = mSettings.mPreferredActivities.keyAt(i);
12154                    if (pir.dump(pw,
12155                            dumpState.getTitlePrinted()
12156                                ? "\nPreferred Activities User " + user + ":"
12157                                : "Preferred Activities User " + user + ":", "  ",
12158                            packageName, true)) {
12159                        dumpState.setTitlePrinted(true);
12160                    }
12161                }
12162            }
12163
12164            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12165                pw.flush();
12166                FileOutputStream fout = new FileOutputStream(fd);
12167                BufferedOutputStream str = new BufferedOutputStream(fout);
12168                XmlSerializer serializer = new FastXmlSerializer();
12169                try {
12170                    serializer.setOutput(str, "utf-8");
12171                    serializer.startDocument(null, true);
12172                    serializer.setFeature(
12173                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12174                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12175                    serializer.endDocument();
12176                    serializer.flush();
12177                } catch (IllegalArgumentException e) {
12178                    pw.println("Failed writing: " + e);
12179                } catch (IllegalStateException e) {
12180                    pw.println("Failed writing: " + e);
12181                } catch (IOException e) {
12182                    pw.println("Failed writing: " + e);
12183                }
12184            }
12185
12186            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12187                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12188            }
12189
12190            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12191                boolean printedSomething = false;
12192                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12193                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12194                        continue;
12195                    }
12196                    if (!printedSomething) {
12197                        if (dumpState.onTitlePrinted())
12198                            pw.println();
12199                        pw.println("Registered ContentProviders:");
12200                        printedSomething = true;
12201                    }
12202                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12203                    pw.print("    "); pw.println(p.toString());
12204                }
12205                printedSomething = false;
12206                for (Map.Entry<String, PackageParser.Provider> entry :
12207                        mProvidersByAuthority.entrySet()) {
12208                    PackageParser.Provider p = entry.getValue();
12209                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12210                        continue;
12211                    }
12212                    if (!printedSomething) {
12213                        if (dumpState.onTitlePrinted())
12214                            pw.println();
12215                        pw.println("ContentProvider Authorities:");
12216                        printedSomething = true;
12217                    }
12218                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12219                    pw.print("    "); pw.println(p.toString());
12220                    if (p.info != null && p.info.applicationInfo != null) {
12221                        final String appInfo = p.info.applicationInfo.toString();
12222                        pw.print("      applicationInfo="); pw.println(appInfo);
12223                    }
12224                }
12225            }
12226
12227            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12228                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12229            }
12230
12231            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12232                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12233            }
12234
12235            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12236                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12237            }
12238
12239            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12240                if (dumpState.onTitlePrinted())
12241                    pw.println();
12242                mSettings.dumpReadMessagesLPr(pw, dumpState);
12243
12244                pw.println();
12245                pw.println("Package warning messages:");
12246                final File fname = getSettingsProblemFile();
12247                FileInputStream in = null;
12248                try {
12249                    in = new FileInputStream(fname);
12250                    final int avail = in.available();
12251                    final byte[] data = new byte[avail];
12252                    in.read(data);
12253                    pw.print(new String(data));
12254                } catch (FileNotFoundException e) {
12255                } catch (IOException e) {
12256                } finally {
12257                    if (in != null) {
12258                        try {
12259                            in.close();
12260                        } catch (IOException e) {
12261                        }
12262                    }
12263                }
12264            }
12265        }
12266    }
12267
12268    // ------- apps on sdcard specific code -------
12269    static final boolean DEBUG_SD_INSTALL = false;
12270
12271    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12272
12273    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12274
12275    private boolean mMediaMounted = false;
12276
12277    private String getEncryptKey() {
12278        try {
12279            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12280                    SD_ENCRYPTION_KEYSTORE_NAME);
12281            if (sdEncKey == null) {
12282                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12283                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12284                if (sdEncKey == null) {
12285                    Slog.e(TAG, "Failed to create encryption keys");
12286                    return null;
12287                }
12288            }
12289            return sdEncKey;
12290        } catch (NoSuchAlgorithmException nsae) {
12291            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12292            return null;
12293        } catch (IOException ioe) {
12294            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12295            return null;
12296        }
12297
12298    }
12299
12300    /* package */static String getTempContainerId() {
12301        int tmpIdx = 1;
12302        String list[] = PackageHelper.getSecureContainerList();
12303        if (list != null) {
12304            for (final String name : list) {
12305                // Ignore null and non-temporary container entries
12306                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12307                    continue;
12308                }
12309
12310                String subStr = name.substring(mTempContainerPrefix.length());
12311                try {
12312                    int cid = Integer.parseInt(subStr);
12313                    if (cid >= tmpIdx) {
12314                        tmpIdx = cid + 1;
12315                    }
12316                } catch (NumberFormatException e) {
12317                }
12318            }
12319        }
12320        return mTempContainerPrefix + tmpIdx;
12321    }
12322
12323    /*
12324     * Update media status on PackageManager.
12325     */
12326    @Override
12327    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12328        int callingUid = Binder.getCallingUid();
12329        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12330            throw new SecurityException("Media status can only be updated by the system");
12331        }
12332        // reader; this apparently protects mMediaMounted, but should probably
12333        // be a different lock in that case.
12334        synchronized (mPackages) {
12335            Log.i(TAG, "Updating external media status from "
12336                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12337                    + (mediaStatus ? "mounted" : "unmounted"));
12338            if (DEBUG_SD_INSTALL)
12339                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12340                        + ", mMediaMounted=" + mMediaMounted);
12341            if (mediaStatus == mMediaMounted) {
12342                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12343                        : 0, -1);
12344                mHandler.sendMessage(msg);
12345                return;
12346            }
12347            mMediaMounted = mediaStatus;
12348        }
12349        // Queue up an async operation since the package installation may take a
12350        // little while.
12351        mHandler.post(new Runnable() {
12352            public void run() {
12353                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12354            }
12355        });
12356    }
12357
12358    /**
12359     * Called by MountService when the initial ASECs to scan are available.
12360     * Should block until all the ASEC containers are finished being scanned.
12361     */
12362    public void scanAvailableAsecs() {
12363        updateExternalMediaStatusInner(true, false, false);
12364        if (mShouldRestoreconData) {
12365            SELinuxMMAC.setRestoreconDone();
12366            mShouldRestoreconData = false;
12367        }
12368    }
12369
12370    /*
12371     * Collect information of applications on external media, map them against
12372     * existing containers and update information based on current mount status.
12373     * Please note that we always have to report status if reportStatus has been
12374     * set to true especially when unloading packages.
12375     */
12376    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12377            boolean externalStorage) {
12378        // Collection of uids
12379        int uidArr[] = null;
12380        // Collection of stale containers
12381        HashSet<String> removeCids = new HashSet<String>();
12382        // Collection of packages on external media with valid containers.
12383        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12384        // Get list of secure containers.
12385        final String list[] = PackageHelper.getSecureContainerList();
12386        if (list == null || list.length == 0) {
12387            Log.i(TAG, "No secure containers on sdcard");
12388        } else {
12389            // Process list of secure containers and categorize them
12390            // as active or stale based on their package internal state.
12391            int uidList[] = new int[list.length];
12392            int num = 0;
12393            // reader
12394            synchronized (mPackages) {
12395                for (String cid : list) {
12396                    if (DEBUG_SD_INSTALL)
12397                        Log.i(TAG, "Processing container " + cid);
12398                    String pkgName = getAsecPackageName(cid);
12399                    if (pkgName == null) {
12400                        if (DEBUG_SD_INSTALL)
12401                            Log.i(TAG, "Container : " + cid + " stale");
12402                        removeCids.add(cid);
12403                        continue;
12404                    }
12405                    if (DEBUG_SD_INSTALL)
12406                        Log.i(TAG, "Looking for pkg : " + pkgName);
12407
12408                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12409                    if (ps == null) {
12410                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12411                        removeCids.add(cid);
12412                        continue;
12413                    }
12414
12415                    /*
12416                     * Skip packages that are not external if we're unmounting
12417                     * external storage.
12418                     */
12419                    if (externalStorage && !isMounted && !isExternal(ps)) {
12420                        continue;
12421                    }
12422
12423                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12424                            getAppInstructionSetFromSettings(ps),
12425                            isForwardLocked(ps));
12426                    // The package status is changed only if the code path
12427                    // matches between settings and the container id.
12428                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12429                        if (DEBUG_SD_INSTALL) {
12430                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12431                                    + " at code path: " + ps.codePathString);
12432                        }
12433
12434                        // We do have a valid package installed on sdcard
12435                        processCids.put(args, ps.codePathString);
12436                        final int uid = ps.appId;
12437                        if (uid != -1) {
12438                            uidList[num++] = uid;
12439                        }
12440                    } else {
12441                        Log.i(TAG, "Deleting stale container for " + cid);
12442                        removeCids.add(cid);
12443                    }
12444                }
12445            }
12446
12447            if (num > 0) {
12448                // Sort uid list
12449                Arrays.sort(uidList, 0, num);
12450                // Throw away duplicates
12451                uidArr = new int[num];
12452                uidArr[0] = uidList[0];
12453                int di = 0;
12454                for (int i = 1; i < num; i++) {
12455                    if (uidList[i - 1] != uidList[i]) {
12456                        uidArr[di++] = uidList[i];
12457                    }
12458                }
12459            }
12460        }
12461        // Process packages with valid entries.
12462        if (isMounted) {
12463            if (DEBUG_SD_INSTALL)
12464                Log.i(TAG, "Loading packages");
12465            loadMediaPackages(processCids, uidArr, removeCids);
12466            startCleaningPackages();
12467        } else {
12468            if (DEBUG_SD_INSTALL)
12469                Log.i(TAG, "Unloading packages");
12470            unloadMediaPackages(processCids, uidArr, reportStatus);
12471        }
12472    }
12473
12474   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12475           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12476        int size = pkgList.size();
12477        if (size > 0) {
12478            // Send broadcasts here
12479            Bundle extras = new Bundle();
12480            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12481                    .toArray(new String[size]));
12482            if (uidArr != null) {
12483                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12484            }
12485            if (replacing) {
12486                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12487            }
12488            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12489                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12490            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12491        }
12492    }
12493
12494   /*
12495     * Look at potentially valid container ids from processCids If package
12496     * information doesn't match the one on record or package scanning fails,
12497     * the cid is added to list of removeCids. We currently don't delete stale
12498     * containers.
12499     */
12500   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12501            HashSet<String> removeCids) {
12502        ArrayList<String> pkgList = new ArrayList<String>();
12503        Set<AsecInstallArgs> keys = processCids.keySet();
12504        boolean doGc = false;
12505        for (AsecInstallArgs args : keys) {
12506            String codePath = processCids.get(args);
12507            if (DEBUG_SD_INSTALL)
12508                Log.i(TAG, "Loading container : " + args.cid);
12509            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12510            try {
12511                // Make sure there are no container errors first.
12512                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12513                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12514                            + " when installing from sdcard");
12515                    continue;
12516                }
12517                // Check code path here.
12518                if (codePath == null || !codePath.equals(args.getCodePath())) {
12519                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12520                            + " does not match one in settings " + codePath);
12521                    continue;
12522                }
12523                // Parse package
12524                int parseFlags = mDefParseFlags;
12525                if (args.isExternal()) {
12526                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12527                }
12528                if (args.isFwdLocked()) {
12529                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12530                }
12531
12532                doGc = true;
12533                synchronized (mInstallLock) {
12534                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12535                            0, 0, null, null);
12536                    // Scan the package
12537                    if (pkg != null) {
12538                        /*
12539                         * TODO why is the lock being held? doPostInstall is
12540                         * called in other places without the lock. This needs
12541                         * to be straightened out.
12542                         */
12543                        // writer
12544                        synchronized (mPackages) {
12545                            retCode = PackageManager.INSTALL_SUCCEEDED;
12546                            pkgList.add(pkg.packageName);
12547                            // Post process args
12548                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12549                                    pkg.applicationInfo.uid);
12550                        }
12551                    } else {
12552                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12553                    }
12554                }
12555
12556            } finally {
12557                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12558                    // Don't destroy container here. Wait till gc clears things
12559                    // up.
12560                    removeCids.add(args.cid);
12561                }
12562            }
12563        }
12564        // writer
12565        synchronized (mPackages) {
12566            // If the platform SDK has changed since the last time we booted,
12567            // we need to re-grant app permission to catch any new ones that
12568            // appear. This is really a hack, and means that apps can in some
12569            // cases get permissions that the user didn't initially explicitly
12570            // allow... it would be nice to have some better way to handle
12571            // this situation.
12572            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12573            if (regrantPermissions)
12574                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12575                        + mSdkVersion + "; regranting permissions for external storage");
12576            mSettings.mExternalSdkPlatform = mSdkVersion;
12577
12578            // Make sure group IDs have been assigned, and any permission
12579            // changes in other apps are accounted for
12580            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12581                    | (regrantPermissions
12582                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12583                            : 0));
12584
12585            mSettings.updateExternalDatabaseVersion();
12586
12587            // can downgrade to reader
12588            // Persist settings
12589            mSettings.writeLPr();
12590        }
12591        // Send a broadcast to let everyone know we are done processing
12592        if (pkgList.size() > 0) {
12593            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12594        }
12595        // Force gc to avoid any stale parser references that we might have.
12596        if (doGc) {
12597            Runtime.getRuntime().gc();
12598        }
12599        // List stale containers and destroy stale temporary containers.
12600        if (removeCids != null) {
12601            for (String cid : removeCids) {
12602                if (cid.startsWith(mTempContainerPrefix)) {
12603                    Log.i(TAG, "Destroying stale temporary container " + cid);
12604                    PackageHelper.destroySdDir(cid);
12605                } else {
12606                    Log.w(TAG, "Container " + cid + " is stale");
12607               }
12608           }
12609        }
12610    }
12611
12612   /*
12613     * Utility method to unload a list of specified containers
12614     */
12615    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12616        // Just unmount all valid containers.
12617        for (AsecInstallArgs arg : cidArgs) {
12618            synchronized (mInstallLock) {
12619                arg.doPostDeleteLI(false);
12620           }
12621       }
12622   }
12623
12624    /*
12625     * Unload packages mounted on external media. This involves deleting package
12626     * data from internal structures, sending broadcasts about diabled packages,
12627     * gc'ing to free up references, unmounting all secure containers
12628     * corresponding to packages on external media, and posting a
12629     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12630     * that we always have to post this message if status has been requested no
12631     * matter what.
12632     */
12633    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12634            final boolean reportStatus) {
12635        if (DEBUG_SD_INSTALL)
12636            Log.i(TAG, "unloading media packages");
12637        ArrayList<String> pkgList = new ArrayList<String>();
12638        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12639        final Set<AsecInstallArgs> keys = processCids.keySet();
12640        for (AsecInstallArgs args : keys) {
12641            String pkgName = args.getPackageName();
12642            if (DEBUG_SD_INSTALL)
12643                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12644            // Delete package internally
12645            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12646            synchronized (mInstallLock) {
12647                boolean res = deletePackageLI(pkgName, null, false, null, null,
12648                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12649                if (res) {
12650                    pkgList.add(pkgName);
12651                } else {
12652                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12653                    failedList.add(args);
12654                }
12655            }
12656        }
12657
12658        // reader
12659        synchronized (mPackages) {
12660            // We didn't update the settings after removing each package;
12661            // write them now for all packages.
12662            mSettings.writeLPr();
12663        }
12664
12665        // We have to absolutely send UPDATED_MEDIA_STATUS only
12666        // after confirming that all the receivers processed the ordered
12667        // broadcast when packages get disabled, force a gc to clean things up.
12668        // and unload all the containers.
12669        if (pkgList.size() > 0) {
12670            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12671                    new IIntentReceiver.Stub() {
12672                public void performReceive(Intent intent, int resultCode, String data,
12673                        Bundle extras, boolean ordered, boolean sticky,
12674                        int sendingUser) throws RemoteException {
12675                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12676                            reportStatus ? 1 : 0, 1, keys);
12677                    mHandler.sendMessage(msg);
12678                }
12679            });
12680        } else {
12681            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12682                    keys);
12683            mHandler.sendMessage(msg);
12684        }
12685    }
12686
12687    /** Binder call */
12688    @Override
12689    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12690            final int flags) {
12691        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12692        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12693        int returnCode = PackageManager.MOVE_SUCCEEDED;
12694        int currFlags = 0;
12695        int newFlags = 0;
12696        // reader
12697        synchronized (mPackages) {
12698            PackageParser.Package pkg = mPackages.get(packageName);
12699            if (pkg == null) {
12700                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12701            } else {
12702                // Disable moving fwd locked apps and system packages
12703                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12704                    Slog.w(TAG, "Cannot move system application");
12705                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12706                } else if (pkg.mOperationPending) {
12707                    Slog.w(TAG, "Attempt to move package which has pending operations");
12708                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12709                } else {
12710                    // Find install location first
12711                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12712                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12713                        Slog.w(TAG, "Ambigous flags specified for move location.");
12714                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12715                    } else {
12716                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12717                                : PackageManager.INSTALL_INTERNAL;
12718                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12719                                : PackageManager.INSTALL_INTERNAL;
12720
12721                        if (newFlags == currFlags) {
12722                            Slog.w(TAG, "No move required. Trying to move to same location");
12723                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12724                        } else {
12725                            if (isForwardLocked(pkg)) {
12726                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12727                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12728                            }
12729                        }
12730                    }
12731                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12732                        pkg.mOperationPending = true;
12733                    }
12734                }
12735            }
12736
12737            /*
12738             * TODO this next block probably shouldn't be inside the lock. We
12739             * can't guarantee these won't change after this is fired off
12740             * anyway.
12741             */
12742            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12743                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12744                        null, -1, user),
12745                        returnCode);
12746            } else {
12747                Message msg = mHandler.obtainMessage(INIT_COPY);
12748                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12749                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12750                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12751                        instructionSet);
12752                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12753                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12754                msg.obj = mp;
12755                mHandler.sendMessage(msg);
12756            }
12757        }
12758    }
12759
12760    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12761        // Queue up an async operation since the package deletion may take a
12762        // little while.
12763        mHandler.post(new Runnable() {
12764            public void run() {
12765                // TODO fix this; this does nothing.
12766                mHandler.removeCallbacks(this);
12767                int returnCode = currentStatus;
12768                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12769                    int uidArr[] = null;
12770                    ArrayList<String> pkgList = null;
12771                    synchronized (mPackages) {
12772                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12773                        if (pkg == null) {
12774                            Slog.w(TAG, " Package " + mp.packageName
12775                                    + " doesn't exist. Aborting move");
12776                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12777                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12778                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12779                                    + mp.srcArgs.getCodePath() + " to "
12780                                    + pkg.applicationInfo.sourceDir
12781                                    + " Aborting move and returning error");
12782                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12783                        } else {
12784                            uidArr = new int[] {
12785                                pkg.applicationInfo.uid
12786                            };
12787                            pkgList = new ArrayList<String>();
12788                            pkgList.add(mp.packageName);
12789                        }
12790                    }
12791                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12792                        // Send resources unavailable broadcast
12793                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12794                        // Update package code and resource paths
12795                        synchronized (mInstallLock) {
12796                            synchronized (mPackages) {
12797                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12798                                // Recheck for package again.
12799                                if (pkg == null) {
12800                                    Slog.w(TAG, " Package " + mp.packageName
12801                                            + " doesn't exist. Aborting move");
12802                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12803                                } else if (!mp.srcArgs.getCodePath().equals(
12804                                        pkg.applicationInfo.sourceDir)) {
12805                                    Slog.w(TAG, "Package " + mp.packageName
12806                                            + " code path changed from " + mp.srcArgs.getCodePath()
12807                                            + " to " + pkg.applicationInfo.sourceDir
12808                                            + " Aborting move and returning error");
12809                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12810                                } else {
12811                                    final String oldCodePath = pkg.codePath;
12812                                    final String newCodePath = mp.targetArgs.getCodePath();
12813                                    final String newResPath = mp.targetArgs.getResourcePath();
12814                                    final String newNativePath = mp.targetArgs
12815                                            .getNativeLibraryPath();
12816
12817                                    final File newNativeDir = new File(newNativePath);
12818
12819                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12820                                        // NOTE: We do not report any errors from the APK scan and library
12821                                        // copy at this point.
12822                                        NativeLibraryHelper.ApkHandle handle =
12823                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12824                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12825                                                handle, Build.SUPPORTED_ABIS);
12826                                        if (abi >= 0) {
12827                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12828                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12829                                        }
12830                                        handle.close();
12831                                    }
12832                                    final int[] users = sUserManager.getUserIds();
12833                                    for (int user : users) {
12834                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12835                                                newNativePath, user) < 0) {
12836                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12837                                        }
12838                                    }
12839
12840                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12841                                        pkg.codePath = newCodePath;
12842                                        // Move dex files around
12843                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12844                                            // Moving of dex files failed. Set
12845                                            // error code and abort move.
12846                                            pkg.codePath = oldCodePath;
12847                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12848                                        }
12849                                    }
12850
12851                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12852                                        pkg.applicationInfo.sourceDir = newCodePath;
12853                                        pkg.applicationInfo.publicSourceDir = newResPath;
12854                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12855                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12856                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12857                                        ps.codePathString = ps.codePath.getPath();
12858                                        ps.resourcePath = new File(
12859                                                pkg.applicationInfo.publicSourceDir);
12860                                        ps.resourcePathString = ps.resourcePath.getPath();
12861                                        ps.nativeLibraryPathString = newNativePath;
12862                                        // Set the application info flag
12863                                        // correctly.
12864                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12865                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12866                                        } else {
12867                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12868                                        }
12869                                        ps.setFlags(pkg.applicationInfo.flags);
12870                                        mAppDirs.remove(oldCodePath);
12871                                        mAppDirs.put(newCodePath, pkg);
12872                                        // Persist settings
12873                                        mSettings.writeLPr();
12874                                    }
12875                                }
12876                            }
12877                        }
12878                        // Send resources available broadcast
12879                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12880                    }
12881                }
12882                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12883                    // Clean up failed installation
12884                    if (mp.targetArgs != null) {
12885                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12886                                -1);
12887                    }
12888                } else {
12889                    // Force a gc to clear things up.
12890                    Runtime.getRuntime().gc();
12891                    // Delete older code
12892                    synchronized (mInstallLock) {
12893                        mp.srcArgs.doPostDeleteLI(true);
12894                    }
12895                }
12896
12897                // Allow more operations on this file if we didn't fail because
12898                // an operation was already pending for this package.
12899                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12900                    synchronized (mPackages) {
12901                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12902                        if (pkg != null) {
12903                            pkg.mOperationPending = false;
12904                       }
12905                   }
12906                }
12907
12908                IPackageMoveObserver observer = mp.observer;
12909                if (observer != null) {
12910                    try {
12911                        observer.packageMoved(mp.packageName, returnCode);
12912                    } catch (RemoteException e) {
12913                        Log.i(TAG, "Observer no longer exists.");
12914                    }
12915                }
12916            }
12917        });
12918    }
12919
12920    @Override
12921    public boolean setInstallLocation(int loc) {
12922        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12923                null);
12924        if (getInstallLocation() == loc) {
12925            return true;
12926        }
12927        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12928                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12929            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12930                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12931            return true;
12932        }
12933        return false;
12934   }
12935
12936    @Override
12937    public int getInstallLocation() {
12938        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12939                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12940                PackageHelper.APP_INSTALL_AUTO);
12941    }
12942
12943    /** Called by UserManagerService */
12944    void cleanUpUserLILPw(int userHandle) {
12945        mDirtyUsers.remove(userHandle);
12946        mSettings.removeUserLPr(userHandle);
12947        mPendingBroadcasts.remove(userHandle);
12948        if (mInstaller != null) {
12949            // Technically, we shouldn't be doing this with the package lock
12950            // held.  However, this is very rare, and there is already so much
12951            // other disk I/O going on, that we'll let it slide for now.
12952            mInstaller.removeUserDataDirs(userHandle);
12953        }
12954    }
12955
12956    /** Called by UserManagerService */
12957    void createNewUserLILPw(int userHandle, File path) {
12958        if (mInstaller != null) {
12959            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12960        }
12961    }
12962
12963    @Override
12964    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12965        mContext.enforceCallingOrSelfPermission(
12966                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12967                "Only package verification agents can read the verifier device identity");
12968
12969        synchronized (mPackages) {
12970            return mSettings.getVerifierDeviceIdentityLPw();
12971        }
12972    }
12973
12974    @Override
12975    public void setPermissionEnforced(String permission, boolean enforced) {
12976        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12977        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12978            synchronized (mPackages) {
12979                if (mSettings.mReadExternalStorageEnforced == null
12980                        || mSettings.mReadExternalStorageEnforced != enforced) {
12981                    mSettings.mReadExternalStorageEnforced = enforced;
12982                    mSettings.writeLPr();
12983                }
12984            }
12985            // kill any non-foreground processes so we restart them and
12986            // grant/revoke the GID.
12987            final IActivityManager am = ActivityManagerNative.getDefault();
12988            if (am != null) {
12989                final long token = Binder.clearCallingIdentity();
12990                try {
12991                    am.killProcessesBelowForeground("setPermissionEnforcement");
12992                } catch (RemoteException e) {
12993                } finally {
12994                    Binder.restoreCallingIdentity(token);
12995                }
12996            }
12997        } else {
12998            throw new IllegalArgumentException("No selective enforcement for " + permission);
12999        }
13000    }
13001
13002    @Override
13003    @Deprecated
13004    public boolean isPermissionEnforced(String permission) {
13005        return true;
13006    }
13007
13008    @Override
13009    public boolean isStorageLow() {
13010        final long token = Binder.clearCallingIdentity();
13011        try {
13012            final DeviceStorageMonitorInternal
13013                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13014            if (dsm != null) {
13015                return dsm.isMemoryLow();
13016            } else {
13017                return false;
13018            }
13019        } finally {
13020            Binder.restoreCallingIdentity(token);
13021        }
13022    }
13023
13024    @Override
13025    public IPackageInstaller getPackageInstaller() {
13026        return mInstallerService;
13027    }
13028}
13029