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